Add BSD-2.0 license for sqlcipher
[platform/core/security/key-manager.git] / src / manager / sqlcipher / sqlcipher.c
1 /*
2  * Copyright (c) 2008-2012 Zetetic LLC
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *     * Redistributions of source code must retain the above copyright
8  *       notice, this list of conditions and the following disclaimer.
9  *     * Redistributions in binary form must reproduce the above copyright
10  *       notice, this list of conditions and the following disclaimer in the
11  *       documentation and/or other materials provided with the distribution.
12  *     * Neither the name of the ZETETIC LLC nor the
13  *       names of its contributors may be used to endorse or promote products
14  *       derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
20  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 /******************************************************************************
28 ** This file is an amalgamation of many separate C source files from SQLite
29 ** version 3.7.9.  By combining all the individual C code files into this 
30 ** single large file, the entire code can be compiled as a single translation
31 ** unit.  This allows many compilers to do optimizations that would not be
32 ** possible if the files were compiled separately.  Performance improvements
33 ** of 5% or more are commonly seen when SQLite is compiled as a single
34 ** translation unit.
35 **
36 ** This file is all you need to compile SQLite.  To use SQLite in other
37 ** programs, you need this file and the "sqlcipher3.h" header file that defines
38 ** the programming interface to the SQLite library.  (If you do not have 
39 ** the "sqlcipher3.h" header file at hand, you will find a copy embedded within
40 ** the text of this file.  Search for "Begin file sqlcipher3.h" to find the start
41 ** of the embedded sqlcipher3.h header file.) Additional code files may be needed
42 ** if you want a wrapper to interface SQLite with your choice of programming
43 ** language. The code for the "sqlcipher3" command-line shell is also in a
44 ** separate file. This file contains only code for the core SQLite library.
45 */
46 #pragma GCC diagnostic push
47 #pragma GCC diagnostic warning "-Wunused-but-set-variable"
48 #pragma GCC diagnostic warning "-Wunused-parameter"
49 #pragma GCC diagnostic warning "-Wsign-compare"
50
51 #define SQLCIPHER_CORE 1
52 #define SQLCIPHER_AMALGAMATION 1
53 #ifndef SQLCIPHER_PRIVATE
54 # define SQLCIPHER_PRIVATE static
55 #endif
56 #ifndef SQLCIPHER_API
57 # define SQLCIPHER_API
58 #endif
59 /************** Begin file sqlcipherInt.h ***************************************/
60 /*
61 ** 2001 September 15
62 **
63 ** The author disclaims copyright to this source code.  In place of
64 ** a legal notice, here is a blessing:
65 **
66 **    May you do good and not evil.
67 **    May you find forgiveness for yourself and forgive others.
68 **    May you share freely, never taking more than you give.
69 **
70 *************************************************************************
71 ** Internal interface definitions for SQLite.
72 **
73 */
74 #ifndef _SQLCIPHERINT_H_
75 #define _SQLCIPHERINT_H_
76
77 /*
78 ** These #defines should enable >2GB file support on POSIX if the
79 ** underlying operating system supports it.  If the OS lacks
80 ** large file support, or if the OS is windows, these should be no-ops.
81 **
82 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
83 ** system #includes.  Hence, this block of code must be the very first
84 ** code in all source files.
85 **
86 ** Large file support can be disabled using the -DSQLCIPHER_DISABLE_LFS switch
87 ** on the compiler command line.  This is necessary if you are compiling
88 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
89 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
90 ** without this option, LFS is enable.  But LFS does not exist in the kernel
91 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
92 ** portability you should omit LFS.
93 **
94 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
95 */
96 #ifndef SQLCIPHER_DISABLE_LFS
97 # define _LARGE_FILE       1
98 # ifndef _FILE_OFFSET_BITS
99 #   define _FILE_OFFSET_BITS 64
100 # endif
101 # define _LARGEFILE_SOURCE 1
102 #endif
103
104 /*
105 ** Include the configuration header output by 'configure' if we're using the
106 ** autoconf-based build
107 */
108 #ifdef _HAVE_SQLCIPHER_CONFIG_H
109 #include "config.h"
110 #endif
111
112 /************** Include sqlcipherLimit.h in the middle of sqlcipherInt.h ***********/
113 /************** Begin file sqlcipherLimit.h *************************************/
114 /*
115 ** 2007 May 7
116 **
117 ** The author disclaims copyright to this source code.  In place of
118 ** a legal notice, here is a blessing:
119 **
120 **    May you do good and not evil.
121 **    May you find forgiveness for yourself and forgive others.
122 **    May you share freely, never taking more than you give.
123 **
124 *************************************************************************
125 ** 
126 ** This file defines various limits of what SQLite can process.
127 */
128
129 /*
130 ** The maximum length of a TEXT or BLOB in bytes.   This also
131 ** limits the size of a row in a table or index.
132 **
133 ** The hard limit is the ability of a 32-bit signed integer
134 ** to count the size: 2^31-1 or 2147483647.
135 */
136 #ifndef SQLCIPHER_MAX_LENGTH
137 # define SQLCIPHER_MAX_LENGTH 1000000000
138 #endif
139
140 /*
141 ** This is the maximum number of
142 **
143 **    * Columns in a table
144 **    * Columns in an index
145 **    * Columns in a view
146 **    * Terms in the SET clause of an UPDATE statement
147 **    * Terms in the result set of a SELECT statement
148 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
149 **    * Terms in the VALUES clause of an INSERT statement
150 **
151 ** The hard upper limit here is 32676.  Most database people will
152 ** tell you that in a well-normalized database, you usually should
153 ** not have more than a dozen or so columns in any table.  And if
154 ** that is the case, there is no point in having more than a few
155 ** dozen values in any of the other situations described above.
156 */
157 #ifndef SQLCIPHER_MAX_COLUMN
158 # define SQLCIPHER_MAX_COLUMN 2000
159 #endif
160
161 /*
162 ** The maximum length of a single SQL statement in bytes.
163 **
164 ** It used to be the case that setting this value to zero would
165 ** turn the limit off.  That is no longer true.  It is not possible
166 ** to turn this limit off.
167 */
168 #ifndef SQLCIPHER_MAX_SQL_LENGTH
169 # define SQLCIPHER_MAX_SQL_LENGTH 1000000000
170 #endif
171
172 /*
173 ** The maximum depth of an expression tree. This is limited to 
174 ** some extent by SQLCIPHER_MAX_SQL_LENGTH. But sometime you might 
175 ** want to place more severe limits on the complexity of an 
176 ** expression.
177 **
178 ** A value of 0 used to mean that the limit was not enforced.
179 ** But that is no longer true.  The limit is now strictly enforced
180 ** at all times.
181 */
182 #ifndef SQLCIPHER_MAX_EXPR_DEPTH
183 # define SQLCIPHER_MAX_EXPR_DEPTH 1000
184 #endif
185
186 /*
187 ** The maximum number of terms in a compound SELECT statement.
188 ** The code generator for compound SELECT statements does one
189 ** level of recursion for each term.  A stack overflow can result
190 ** if the number of terms is too large.  In practice, most SQL
191 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
192 ** any limit on the number of terms in a compount SELECT.
193 */
194 #ifndef SQLCIPHER_MAX_COMPOUND_SELECT
195 # define SQLCIPHER_MAX_COMPOUND_SELECT 500
196 #endif
197
198 /*
199 ** The maximum number of opcodes in a VDBE program.
200 ** Not currently enforced.
201 */
202 #ifndef SQLCIPHER_MAX_VDBE_OP
203 # define SQLCIPHER_MAX_VDBE_OP 25000
204 #endif
205
206 /*
207 ** The maximum number of arguments to an SQL function.
208 */
209 #ifndef SQLCIPHER_MAX_FUNCTION_ARG
210 # define SQLCIPHER_MAX_FUNCTION_ARG 127
211 #endif
212
213 /*
214 ** The maximum number of in-memory pages to use for the main database
215 ** table and for temporary tables.  The SQLCIPHER_DEFAULT_CACHE_SIZE
216 */
217 #ifndef SQLCIPHER_DEFAULT_CACHE_SIZE
218 # define SQLCIPHER_DEFAULT_CACHE_SIZE  2000
219 #endif
220 #ifndef SQLCIPHER_DEFAULT_TEMP_CACHE_SIZE
221 # define SQLCIPHER_DEFAULT_TEMP_CACHE_SIZE  500
222 #endif
223
224 /*
225 ** The default number of frames to accumulate in the log file before
226 ** checkpointing the database in WAL mode.
227 */
228 #ifndef SQLCIPHER_DEFAULT_WAL_AUTOCHECKPOINT
229 # define SQLCIPHER_DEFAULT_WAL_AUTOCHECKPOINT  1000
230 #endif
231
232 /*
233 ** The maximum number of attached databases.  This must be between 0
234 ** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
235 ** is used internally to track attached databases.
236 */
237 #ifndef SQLCIPHER_MAX_ATTACHED
238 # define SQLCIPHER_MAX_ATTACHED 10
239 #endif
240
241
242 /*
243 ** The maximum value of a ?nnn wildcard that the parser will accept.
244 */
245 #ifndef SQLCIPHER_MAX_VARIABLE_NUMBER
246 # define SQLCIPHER_MAX_VARIABLE_NUMBER 999
247 #endif
248
249 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
250 ** imposed by the use of 16-bit offsets within each page.
251 **
252 ** Earlier versions of SQLite allowed the user to change this value at
253 ** compile time. This is no longer permitted, on the grounds that it creates
254 ** a library that is technically incompatible with an SQLite library 
255 ** compiled with a different limit. If a process operating on a database 
256 ** with a page-size of 65536 bytes crashes, then an instance of SQLite 
257 ** compiled with the default page-size limit will not be able to rollback 
258 ** the aborted transaction. This could lead to database corruption.
259 */
260 #ifdef SQLCIPHER_MAX_PAGE_SIZE
261 # undef SQLCIPHER_MAX_PAGE_SIZE
262 #endif
263 #define SQLCIPHER_MAX_PAGE_SIZE 65536
264
265
266 /*
267 ** The default size of a database page.
268 */
269 #ifndef SQLCIPHER_DEFAULT_PAGE_SIZE
270 # define SQLCIPHER_DEFAULT_PAGE_SIZE 1024
271 #endif
272 #if SQLCIPHER_DEFAULT_PAGE_SIZE>SQLCIPHER_MAX_PAGE_SIZE
273 # undef SQLCIPHER_DEFAULT_PAGE_SIZE
274 # define SQLCIPHER_DEFAULT_PAGE_SIZE SQLCIPHER_MAX_PAGE_SIZE
275 #endif
276
277 /*
278 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
279 ** with page size SQLCIPHER_DEFAULT_PAGE_SIZE. However, based on certain
280 ** device characteristics (sector-size and atomic write() support),
281 ** SQLite may choose a larger value. This constant is the maximum value
282 ** SQLite will choose on its own.
283 */
284 #ifndef SQLCIPHER_MAX_DEFAULT_PAGE_SIZE
285 # define SQLCIPHER_MAX_DEFAULT_PAGE_SIZE 8192
286 #endif
287 #if SQLCIPHER_MAX_DEFAULT_PAGE_SIZE>SQLCIPHER_MAX_PAGE_SIZE
288 # undef SQLCIPHER_MAX_DEFAULT_PAGE_SIZE
289 # define SQLCIPHER_MAX_DEFAULT_PAGE_SIZE SQLCIPHER_MAX_PAGE_SIZE
290 #endif
291
292
293 /*
294 ** Maximum number of pages in one database file.
295 **
296 ** This is really just the default value for the max_page_count pragma.
297 ** This value can be lowered (or raised) at run-time using that the
298 ** max_page_count macro.
299 */
300 #ifndef SQLCIPHER_MAX_PAGE_COUNT
301 # define SQLCIPHER_MAX_PAGE_COUNT 1073741823
302 #endif
303
304 /*
305 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
306 ** operator.
307 */
308 #ifndef SQLCIPHER_MAX_LIKE_PATTERN_LENGTH
309 # define SQLCIPHER_MAX_LIKE_PATTERN_LENGTH 50000
310 #endif
311
312 /*
313 ** Maximum depth of recursion for triggers.
314 **
315 ** A value of 1 means that a trigger program will not be able to itself
316 ** fire any triggers. A value of 0 means that no trigger programs at all 
317 ** may be executed.
318 */
319 #ifndef SQLCIPHER_MAX_TRIGGER_DEPTH
320 # define SQLCIPHER_MAX_TRIGGER_DEPTH 1000
321 #endif
322
323 /************** End of sqlcipherLimit.h *****************************************/
324 /************** Continuing where we left off in sqlcipherInt.h ******************/
325
326 /* Disable nuisance warnings on Borland compilers */
327 #if defined(__BORLANDC__)
328 #pragma warn -rch /* unreachable code */
329 #pragma warn -ccc /* Condition is always true or false */
330 #pragma warn -aus /* Assigned value is never used */
331 #pragma warn -csu /* Comparing signed and unsigned */
332 #pragma warn -spa /* Suspicious pointer arithmetic */
333 #endif
334
335 /* Needed for various definitions... */
336 #ifndef _GNU_SOURCE
337 # define _GNU_SOURCE
338 #endif
339
340 /*
341 ** Include standard header files as necessary
342 */
343 #ifdef HAVE_STDINT_H
344 #include <stdint.h>
345 #endif
346 #ifdef HAVE_INTTYPES_H
347 #include <inttypes.h>
348 #endif
349
350 /*
351 ** The following macros are used to cast pointers to integers and
352 ** integers to pointers.  The way you do this varies from one compiler
353 ** to the next, so we have developed the following set of #if statements
354 ** to generate appropriate macros for a wide range of compilers.
355 **
356 ** The correct "ANSI" way to do this is to use the intptr_t type. 
357 ** Unfortunately, that typedef is not available on all compilers, or
358 ** if it is available, it requires an #include of specific headers
359 ** that vary from one machine to the next.
360 **
361 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
362 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
363 ** So we have to define the macros in different ways depending on the
364 ** compiler.
365 */
366 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
367 # define SQLCIPHER_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
368 # define SQLCIPHER_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
369 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
370 # define SQLCIPHER_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
371 # define SQLCIPHER_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
372 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
373 # define SQLCIPHER_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
374 # define SQLCIPHER_PTR_TO_INT(X)  ((int)(intptr_t)(X))
375 #else                          /* Generates a warning - but it always works */
376 # define SQLCIPHER_INT_TO_PTR(X)  ((void*)(X))
377 # define SQLCIPHER_PTR_TO_INT(X)  ((int)(X))
378 #endif
379
380 /*
381 ** The SQLCIPHER_THREADSAFE macro must be defined as 0, 1, or 2.
382 ** 0 means mutexes are permanently disable and the library is never
383 ** threadsafe.  1 means the library is serialized which is the highest
384 ** level of threadsafety.  2 means the libary is multithreaded - multiple
385 ** threads can use SQLite as long as no two threads try to use the same
386 ** database connection at the same time.
387 **
388 ** Older versions of SQLite used an optional THREADSAFE macro.
389 ** We support that for legacy.
390 */
391 #if !defined(SQLCIPHER_THREADSAFE)
392 #if defined(THREADSAFE)
393 # define SQLCIPHER_THREADSAFE THREADSAFE
394 #else
395 # define SQLCIPHER_THREADSAFE 1 /* IMP: R-07272-22309 */
396 #endif
397 #endif
398
399 /*
400 ** The SQLCIPHER_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
401 ** It determines whether or not the features related to 
402 ** SQLCIPHER_CONFIG_MEMSTATUS are available by default or not. This value can
403 ** be overridden at runtime using the sqlcipher3_config() API.
404 */
405 #if !defined(SQLCIPHER_DEFAULT_MEMSTATUS)
406 # define SQLCIPHER_DEFAULT_MEMSTATUS 1
407 #endif
408
409 /*
410 ** Exactly one of the following macros must be defined in order to
411 ** specify which memory allocation subsystem to use.
412 **
413 **     SQLCIPHER_SYSTEM_MALLOC          // Use normal system malloc()
414 **     SQLCIPHER_WIN32_MALLOC           // Use Win32 native heap API
415 **     SQLCIPHER_MEMDEBUG               // Debugging version of system malloc()
416 **
417 ** On Windows, if the SQLCIPHER_WIN32_MALLOC_VALIDATE macro is defined and the
418 ** assert() macro is enabled, each call into the Win32 native heap subsystem
419 ** will cause HeapValidate to be called.  If heap validation should fail, an
420 ** assertion will be triggered.
421 **
422 ** (Historical note:  There used to be several other options, but we've
423 ** pared it down to just these three.)
424 **
425 ** If none of the above are defined, then set SQLCIPHER_SYSTEM_MALLOC as
426 ** the default.
427 */
428 #if defined(SQLCIPHER_SYSTEM_MALLOC)+defined(SQLCIPHER_WIN32_MALLOC)+defined(SQLCIPHER_MEMDEBUG)>1
429 # error "At most one of the following compile-time configuration options\
430  is allows: SQLCIPHER_SYSTEM_MALLOC, SQLCIPHER_WIN32_MALLOC, SQLCIPHER_MEMDEBUG"
431 #endif
432 #if defined(SQLCIPHER_SYSTEM_MALLOC)+defined(SQLCIPHER_WIN32_MALLOC)+defined(SQLCIPHER_MEMDEBUG)==0
433 # define SQLCIPHER_SYSTEM_MALLOC 1
434 #endif
435
436 /*
437 ** If SQLCIPHER_MALLOC_SOFT_LIMIT is not zero, then try to keep the
438 ** sizes of memory allocations below this value where possible.
439 */
440 #if !defined(SQLCIPHER_MALLOC_SOFT_LIMIT)
441 # define SQLCIPHER_MALLOC_SOFT_LIMIT 1024
442 #endif
443
444 /*
445 ** We need to define _XOPEN_SOURCE as follows in order to enable
446 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
447 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
448 ** so it is omitted there.  See ticket #2673.
449 **
450 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
451 ** implemented on some systems.  So we avoid defining it at all
452 ** if it is already defined or if it is unneeded because we are
453 ** not doing a threadsafe build.  Ticket #2681.
454 **
455 ** See also ticket #2741.
456 */
457 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLCIPHER_THREADSAFE
458 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
459 #endif
460
461 /*
462 ** The TCL headers are only needed when compiling the TCL bindings.
463 */
464 #if defined(SQLCIPHER_TCL) || defined(TCLSH)
465 # include <tcl.h>
466 #endif
467
468 /*
469 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
470 ** Setting NDEBUG makes the code smaller and run faster.  So the following
471 ** lines are added to automatically set NDEBUG unless the -DSQLCIPHER_DEBUG=1
472 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
473 ** feature.
474 */
475 #if !defined(NDEBUG) && !defined(SQLCIPHER_DEBUG) 
476 # define NDEBUG 1
477 #endif
478
479 /*
480 ** The testcase() macro is used to aid in coverage testing.  When 
481 ** doing coverage testing, the condition inside the argument to
482 ** testcase() must be evaluated both true and false in order to
483 ** get full branch coverage.  The testcase() macro is inserted
484 ** to help ensure adequate test coverage in places where simple
485 ** condition/decision coverage is inadequate.  For example, testcase()
486 ** can be used to make sure boundary values are tested.  For
487 ** bitmask tests, testcase() can be used to make sure each bit
488 ** is significant and used at least once.  On switch statements
489 ** where multiple cases go to the same block of code, testcase()
490 ** can insure that all cases are evaluated.
491 **
492 */
493 #ifdef SQLCIPHER_COVERAGE_TEST
494 SQLCIPHER_PRIVATE   void sqlcipher3Coverage(int);
495 # define testcase(X)  if( X ){ sqlcipher3Coverage(__LINE__); }
496 #else
497 # define testcase(X)
498 #endif
499
500 /*
501 ** The TESTONLY macro is used to enclose variable declarations or
502 ** other bits of code that are needed to support the arguments
503 ** within testcase() and assert() macros.
504 */
505 #if !defined(NDEBUG) || defined(SQLCIPHER_COVERAGE_TEST)
506 # define TESTONLY(X)  X
507 #else
508 # define TESTONLY(X)
509 #endif
510
511 /*
512 ** Sometimes we need a small amount of code such as a variable initialization
513 ** to setup for a later assert() statement.  We do not want this code to
514 ** appear when assert() is disabled.  The following macro is therefore
515 ** used to contain that setup code.  The "VVA" acronym stands for
516 ** "Verification, Validation, and Accreditation".  In other words, the
517 ** code within VVA_ONLY() will only run during verification processes.
518 */
519 #ifndef NDEBUG
520 # define VVA_ONLY(X)  X
521 #else
522 # define VVA_ONLY(X)
523 #endif
524
525 /*
526 ** The ALWAYS and NEVER macros surround boolean expressions which 
527 ** are intended to always be true or false, respectively.  Such
528 ** expressions could be omitted from the code completely.  But they
529 ** are included in a few cases in order to enhance the resilience
530 ** of SQLite to unexpected behavior - to make the code "self-healing"
531 ** or "ductile" rather than being "brittle" and crashing at the first
532 ** hint of unplanned behavior.
533 **
534 ** In other words, ALWAYS and NEVER are added for defensive code.
535 **
536 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
537 ** be true and false so that the unreachable code then specify will
538 ** not be counted as untested code.
539 */
540 #if defined(SQLCIPHER_COVERAGE_TEST)
541 # define ALWAYS(X)      (1)
542 # define NEVER(X)       (0)
543 #elif !defined(NDEBUG)
544 # define ALWAYS(X)      ((X)?1:(assert(0),0))
545 # define NEVER(X)       ((X)?(assert(0),1):0)
546 #else
547 # define ALWAYS(X)      (X)
548 # define NEVER(X)       (X)
549 #endif
550
551 /*
552 ** Return true (non-zero) if the input is a integer that is too large
553 ** to fit in 32-bits.  This macro is used inside of various testcase()
554 ** macros to verify that we have tested SQLite for large-file support.
555 */
556 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
557
558 /*
559 ** The macro unlikely() is a hint that surrounds a boolean
560 ** expression that is usually false.  Macro likely() surrounds
561 ** a boolean expression that is usually true.  GCC is able to
562 ** use these hints to generate better code, sometimes.
563 */
564 #if defined(__GNUC__) && 0
565 # define likely(X)    __builtin_expect((X),1)
566 # define unlikely(X)  __builtin_expect((X),0)
567 #else
568 # define likely(X)    !!(X)
569 # define unlikely(X)  !!(X)
570 #endif
571
572 /************** Include sqlcipher3.h in the middle of sqlcipherInt.h ***************/
573 /************** Begin file sqlcipher3.h *****************************************/
574 /*
575 ** 2001 September 15
576 **
577 ** The author disclaims copyright to this source code.  In place of
578 ** a legal notice, here is a blessing:
579 **
580 **    May you do good and not evil.
581 **    May you find forgiveness for yourself and forgive others.
582 **    May you share freely, never taking more than you give.
583 **
584 *************************************************************************
585 ** This header file defines the interface that the SQLite library
586 ** presents to client programs.  If a C-function, structure, datatype,
587 ** or constant definition does not appear in this file, then it is
588 ** not a published API of SQLite, is subject to change without
589 ** notice, and should not be referenced by programs that use SQLite.
590 **
591 ** Some of the definitions that are in this file are marked as
592 ** "experimental".  Experimental interfaces are normally new
593 ** features recently added to SQLite.  We do not anticipate changes
594 ** to experimental interfaces but reserve the right to make minor changes
595 ** if experience from use "in the wild" suggest such changes are prudent.
596 **
597 ** The official C-language API documentation for SQLite is derived
598 ** from comments in this file.  This file is the authoritative source
599 ** on how SQLite interfaces are suppose to operate.
600 **
601 ** The name of this file under configuration management is "sqlcipher.h.in".
602 ** The makefile makes some minor changes to this file (such as inserting
603 ** the version number) and changes its name to "sqlcipher3.h" as
604 ** part of the build process.
605 */
606 #ifndef _SQLCIPHER3_H_
607 #define _SQLCIPHER3_H_
608 #include <stdarg.h>     /* Needed for the definition of va_list */
609
610 /*
611 ** Make sure we can call this stuff from C++.
612 */
613 #if 0
614 extern "C" {
615 #endif
616
617
618 /*
619 ** Add the ability to override 'extern'
620 */
621 #ifndef SQLCIPHER_EXTERN
622 # define SQLCIPHER_EXTERN extern
623 #endif
624
625 #ifndef SQLCIPHER_API
626 # define SQLCIPHER_API
627 #endif
628
629
630 /*
631 ** These no-op macros are used in front of interfaces to mark those
632 ** interfaces as either deprecated or experimental.  New applications
633 ** should not use deprecated interfaces - they are support for backwards
634 ** compatibility only.  Application writers should be aware that
635 ** experimental interfaces are subject to change in point releases.
636 **
637 ** These macros used to resolve to various kinds of compiler magic that
638 ** would generate warning messages when they were used.  But that
639 ** compiler magic ended up generating such a flurry of bug reports
640 ** that we have taken it all out and gone back to using simple
641 ** noop macros.
642 */
643 #define SQLCIPHER_DEPRECATED
644 #define SQLCIPHER_EXPERIMENTAL
645
646 /*
647 ** Ensure these symbols were not defined by some previous header file.
648 */
649 #ifdef SQLCIPHER_VERSION
650 # undef SQLCIPHER_VERSION
651 #endif
652 #ifdef SQLCIPHER_VERSION_NUMBER
653 # undef SQLCIPHER_VERSION_NUMBER
654 #endif
655
656 /*
657 ** CAPI3REF: Compile-Time Library Version Numbers
658 **
659 ** ^(The [SQLCIPHER_VERSION] C preprocessor macro in the sqlcipher3.h header
660 ** evaluates to a string literal that is the SQLite version in the
661 ** format "X.Y.Z" where X is the major version number (always 3 for
662 ** SQLite3) and Y is the minor version number and Z is the release number.)^
663 ** ^(The [SQLCIPHER_VERSION_NUMBER] C preprocessor macro resolves to an integer
664 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
665 ** numbers used in [SQLCIPHER_VERSION].)^
666 ** The SQLCIPHER_VERSION_NUMBER for any given release of SQLite will also
667 ** be larger than the release from which it is derived.  Either Y will
668 ** be held constant and Z will be incremented or else Y will be incremented
669 ** and Z will be reset to zero.
670 **
671 ** Since version 3.6.18, SQLite source code has been stored in the
672 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
673 ** system</a>.  ^The SQLCIPHER_SOURCE_ID macro evaluates to
674 ** a string which identifies a particular check-in of SQLite
675 ** within its configuration management system.  ^The SQLCIPHER_SOURCE_ID
676 ** string contains the date and time of the check-in (UTC) and an SHA1
677 ** hash of the entire source tree.
678 **
679 ** See also: [sqlcipher3_libversion()],
680 ** [sqlcipher3_libversion_number()], [sqlcipher3_sourceid()],
681 ** [sqlcipher_version()] and [sqlcipher_source_id()].
682 */
683 #define SQLCIPHER_VERSION        "3.7.9"
684 #define SQLCIPHER_VERSION_NUMBER 3007009
685 #define SQLCIPHER_SOURCE_ID      "2011-11-01 00:52:41 c7c6050ef060877ebe77b41d959e9df13f8c9b5e"
686
687 /*
688 ** CAPI3REF: Run-Time Library Version Numbers
689 ** KEYWORDS: sqlcipher3_version, sqlcipher3_sourceid
690 **
691 ** These interfaces provide the same information as the [SQLCIPHER_VERSION],
692 ** [SQLCIPHER_VERSION_NUMBER], and [SQLCIPHER_SOURCE_ID] C preprocessor macros
693 ** but are associated with the library instead of the header file.  ^(Cautious
694 ** programmers might include assert() statements in their application to
695 ** verify that values returned by these interfaces match the macros in
696 ** the header, and thus insure that the application is
697 ** compiled with matching library and header files.
698 **
699 ** <blockquote><pre>
700 ** assert( sqlcipher3_libversion_number()==SQLCIPHER_VERSION_NUMBER );
701 ** assert( strcmp(sqlcipher3_sourceid(),SQLCIPHER_SOURCE_ID)==0 );
702 ** assert( strcmp(sqlcipher3_libversion(),SQLCIPHER_VERSION)==0 );
703 ** </pre></blockquote>)^
704 **
705 ** ^The sqlcipher3_version[] string constant contains the text of [SQLCIPHER_VERSION]
706 ** macro.  ^The sqlcipher3_libversion() function returns a pointer to the
707 ** to the sqlcipher3_version[] string constant.  The sqlcipher3_libversion()
708 ** function is provided for use in DLLs since DLL users usually do not have
709 ** direct access to string constants within the DLL.  ^The
710 ** sqlcipher3_libversion_number() function returns an integer equal to
711 ** [SQLCIPHER_VERSION_NUMBER].  ^The sqlcipher3_sourceid() function returns 
712 ** a pointer to a string constant whose value is the same as the 
713 ** [SQLCIPHER_SOURCE_ID] C preprocessor macro.
714 **
715 ** See also: [sqlcipher_version()] and [sqlcipher_source_id()].
716 */
717 SQLCIPHER_API const char sqlcipher3_version[] = SQLCIPHER_VERSION;
718 SQLCIPHER_API const char *sqlcipher3_libversion(void);
719 SQLCIPHER_API const char *sqlcipher3_sourceid(void);
720 SQLCIPHER_API int sqlcipher3_libversion_number(void);
721
722 /*
723 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
724 **
725 ** ^The sqlcipher3_compileoption_used() function returns 0 or 1 
726 ** indicating whether the specified option was defined at 
727 ** compile time.  ^The SQLCIPHER_ prefix may be omitted from the 
728 ** option name passed to sqlcipher3_compileoption_used().  
729 **
730 ** ^The sqlcipher3_compileoption_get() function allows iterating
731 ** over the list of options that were defined at compile time by
732 ** returning the N-th compile time option string.  ^If N is out of range,
733 ** sqlcipher3_compileoption_get() returns a NULL pointer.  ^The SQLCIPHER_ 
734 ** prefix is omitted from any strings returned by 
735 ** sqlcipher3_compileoption_get().
736 **
737 ** ^Support for the diagnostic functions sqlcipher3_compileoption_used()
738 ** and sqlcipher3_compileoption_get() may be omitted by specifying the 
739 ** [SQLCIPHER_OMIT_COMPILEOPTION_DIAGS] option at compile time.
740 **
741 ** See also: SQL functions [sqlcipher_compileoption_used()] and
742 ** [sqlcipher_compileoption_get()] and the [compile_options pragma].
743 */
744 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
745 SQLCIPHER_API int sqlcipher3_compileoption_used(const char *zOptName);
746 SQLCIPHER_API const char *sqlcipher3_compileoption_get(int N);
747 #endif
748
749 /*
750 ** CAPI3REF: Test To See If The Library Is Threadsafe
751 **
752 ** ^The sqlcipher3_threadsafe() function returns zero if and only if
753 ** SQLite was compiled mutexing code omitted due to the
754 ** [SQLCIPHER_THREADSAFE] compile-time option being set to 0.
755 **
756 ** SQLite can be compiled with or without mutexes.  When
757 ** the [SQLCIPHER_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
758 ** are enabled and SQLite is threadsafe.  When the
759 ** [SQLCIPHER_THREADSAFE] macro is 0, 
760 ** the mutexes are omitted.  Without the mutexes, it is not safe
761 ** to use SQLite concurrently from more than one thread.
762 **
763 ** Enabling mutexes incurs a measurable performance penalty.
764 ** So if speed is of utmost importance, it makes sense to disable
765 ** the mutexes.  But for maximum safety, mutexes should be enabled.
766 ** ^The default behavior is for mutexes to be enabled.
767 **
768 ** This interface can be used by an application to make sure that the
769 ** version of SQLite that it is linking against was compiled with
770 ** the desired setting of the [SQLCIPHER_THREADSAFE] macro.
771 **
772 ** This interface only reports on the compile-time mutex setting
773 ** of the [SQLCIPHER_THREADSAFE] flag.  If SQLite is compiled with
774 ** SQLCIPHER_THREADSAFE=1 or =2 then mutexes are enabled by default but
775 ** can be fully or partially disabled using a call to [sqlcipher3_config()]
776 ** with the verbs [SQLCIPHER_CONFIG_SINGLETHREAD], [SQLCIPHER_CONFIG_MULTITHREAD],
777 ** or [SQLCIPHER_CONFIG_MUTEX].  ^(The return value of the
778 ** sqlcipher3_threadsafe() function shows only the compile-time setting of
779 ** thread safety, not any run-time changes to that setting made by
780 ** sqlcipher3_config(). In other words, the return value from sqlcipher3_threadsafe()
781 ** is unchanged by calls to sqlcipher3_config().)^
782 **
783 ** See the [threading mode] documentation for additional information.
784 */
785 SQLCIPHER_API int sqlcipher3_threadsafe(void);
786
787 /*
788 ** CAPI3REF: Database Connection Handle
789 ** KEYWORDS: {database connection} {database connections}
790 **
791 ** Each open SQLite database is represented by a pointer to an instance of
792 ** the opaque structure named "sqlcipher3".  It is useful to think of an sqlcipher3
793 ** pointer as an object.  The [sqlcipher3_open()], [sqlcipher3_open16()], and
794 ** [sqlcipher3_open_v2()] interfaces are its constructors, and [sqlcipher3_close()]
795 ** is its destructor.  There are many other interfaces (such as
796 ** [sqlcipher3_prepare_v2()], [sqlcipher3_create_function()], and
797 ** [sqlcipher3_busy_timeout()] to name but three) that are methods on an
798 ** sqlcipher3 object.
799 */
800 typedef struct sqlcipher3 sqlcipher3;
801
802 /*
803 ** CAPI3REF: 64-Bit Integer Types
804 ** KEYWORDS: sqlcipher_int64 sqlcipher_uint64
805 **
806 ** Because there is no cross-platform way to specify 64-bit integer types
807 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
808 **
809 ** The sqlcipher3_int64 and sqlcipher3_uint64 are the preferred type definitions.
810 ** The sqlcipher_int64 and sqlcipher_uint64 types are supported for backwards
811 ** compatibility only.
812 **
813 ** ^The sqlcipher3_int64 and sqlcipher_int64 types can store integer values
814 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
815 ** sqlcipher3_uint64 and sqlcipher_uint64 types can store integer values 
816 ** between 0 and +18446744073709551615 inclusive.
817 */
818 #ifdef SQLCIPHER_INT64_TYPE
819   typedef SQLCIPHER_INT64_TYPE sqlcipher_int64;
820   typedef unsigned SQLCIPHER_INT64_TYPE sqlcipher_uint64;
821 #elif defined(_MSC_VER) || defined(__BORLANDC__)
822   typedef __int64 sqlcipher_int64;
823   typedef unsigned __int64 sqlcipher_uint64;
824 #else
825   typedef long long int sqlcipher_int64;
826   typedef unsigned long long int sqlcipher_uint64;
827 #endif
828 typedef sqlcipher_int64 sqlcipher3_int64;
829 typedef sqlcipher_uint64 sqlcipher3_uint64;
830
831 /*
832 ** If compiling for a processor that lacks floating point support,
833 ** substitute integer for floating-point.
834 */
835 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
836 # define double sqlcipher3_int64
837 #endif
838
839 /*
840 ** CAPI3REF: Closing A Database Connection
841 **
842 ** ^The sqlcipher3_close() routine is the destructor for the [sqlcipher3] object.
843 ** ^Calls to sqlcipher3_close() return SQLCIPHER_OK if the [sqlcipher3] object is
844 ** successfully destroyed and all associated resources are deallocated.
845 **
846 ** Applications must [sqlcipher3_finalize | finalize] all [prepared statements]
847 ** and [sqlcipher3_blob_close | close] all [BLOB handles] associated with
848 ** the [sqlcipher3] object prior to attempting to close the object.  ^If
849 ** sqlcipher3_close() is called on a [database connection] that still has
850 ** outstanding [prepared statements] or [BLOB handles], then it returns
851 ** SQLCIPHER_BUSY.
852 **
853 ** ^If [sqlcipher3_close()] is invoked while a transaction is open,
854 ** the transaction is automatically rolled back.
855 **
856 ** The C parameter to [sqlcipher3_close(C)] must be either a NULL
857 ** pointer or an [sqlcipher3] object pointer obtained
858 ** from [sqlcipher3_open()], [sqlcipher3_open16()], or
859 ** [sqlcipher3_open_v2()], and not previously closed.
860 ** ^Calling sqlcipher3_close() with a NULL pointer argument is a 
861 ** harmless no-op.
862 */
863 SQLCIPHER_API int sqlcipher3_close(sqlcipher3 *);
864
865 /*
866 ** The type for a callback function.
867 ** This is legacy and deprecated.  It is included for historical
868 ** compatibility and is not documented.
869 */
870 typedef int (*sqlcipher3_callback)(void*,int,char**, char**);
871
872 /*
873 ** CAPI3REF: One-Step Query Execution Interface
874 **
875 ** The sqlcipher3_exec() interface is a convenience wrapper around
876 ** [sqlcipher3_prepare_v2()], [sqlcipher3_step()], and [sqlcipher3_finalize()],
877 ** that allows an application to run multiple statements of SQL
878 ** without having to use a lot of C code. 
879 **
880 ** ^The sqlcipher3_exec() interface runs zero or more UTF-8 encoded,
881 ** semicolon-separate SQL statements passed into its 2nd argument,
882 ** in the context of the [database connection] passed in as its 1st
883 ** argument.  ^If the callback function of the 3rd argument to
884 ** sqlcipher3_exec() is not NULL, then it is invoked for each result row
885 ** coming out of the evaluated SQL statements.  ^The 4th argument to
886 ** sqlcipher3_exec() is relayed through to the 1st argument of each
887 ** callback invocation.  ^If the callback pointer to sqlcipher3_exec()
888 ** is NULL, then no callback is ever invoked and result rows are
889 ** ignored.
890 **
891 ** ^If an error occurs while evaluating the SQL statements passed into
892 ** sqlcipher3_exec(), then execution of the current statement stops and
893 ** subsequent statements are skipped.  ^If the 5th parameter to sqlcipher3_exec()
894 ** is not NULL then any error message is written into memory obtained
895 ** from [sqlcipher3_malloc()] and passed back through the 5th parameter.
896 ** To avoid memory leaks, the application should invoke [sqlcipher3_free()]
897 ** on error message strings returned through the 5th parameter of
898 ** of sqlcipher3_exec() after the error message string is no longer needed.
899 ** ^If the 5th parameter to sqlcipher3_exec() is not NULL and no errors
900 ** occur, then sqlcipher3_exec() sets the pointer in its 5th parameter to
901 ** NULL before returning.
902 **
903 ** ^If an sqlcipher3_exec() callback returns non-zero, the sqlcipher3_exec()
904 ** routine returns SQLCIPHER_ABORT without invoking the callback again and
905 ** without running any subsequent SQL statements.
906 **
907 ** ^The 2nd argument to the sqlcipher3_exec() callback function is the
908 ** number of columns in the result.  ^The 3rd argument to the sqlcipher3_exec()
909 ** callback is an array of pointers to strings obtained as if from
910 ** [sqlcipher3_column_text()], one for each column.  ^If an element of a
911 ** result row is NULL then the corresponding string pointer for the
912 ** sqlcipher3_exec() callback is a NULL pointer.  ^The 4th argument to the
913 ** sqlcipher3_exec() callback is an array of pointers to strings where each
914 ** entry represents the name of corresponding result column as obtained
915 ** from [sqlcipher3_column_name()].
916 **
917 ** ^If the 2nd parameter to sqlcipher3_exec() is a NULL pointer, a pointer
918 ** to an empty string, or a pointer that contains only whitespace and/or 
919 ** SQL comments, then no SQL statements are evaluated and the database
920 ** is not changed.
921 **
922 ** Restrictions:
923 **
924 ** <ul>
925 ** <li> The application must insure that the 1st parameter to sqlcipher3_exec()
926 **      is a valid and open [database connection].
927 ** <li> The application must not close [database connection] specified by
928 **      the 1st parameter to sqlcipher3_exec() while sqlcipher3_exec() is running.
929 ** <li> The application must not modify the SQL statement text passed into
930 **      the 2nd parameter of sqlcipher3_exec() while sqlcipher3_exec() is running.
931 ** </ul>
932 */
933 SQLCIPHER_API int sqlcipher3_exec(
934   sqlcipher3*,                                  /* An open database */
935   const char *sql,                           /* SQL to be evaluated */
936   int (*callback)(void*,int,char**,char**),  /* Callback function */
937   void *,                                    /* 1st argument to callback */
938   char **errmsg                              /* Error msg written here */
939 );
940
941 /*
942 ** CAPI3REF: Result Codes
943 ** KEYWORDS: SQLCIPHER_OK {error code} {error codes}
944 ** KEYWORDS: {result code} {result codes}
945 **
946 ** Many SQLite functions return an integer result code from the set shown
947 ** here in order to indicates success or failure.
948 **
949 ** New error codes may be added in future versions of SQLite.
950 **
951 ** See also: [SQLCIPHER_IOERR_READ | extended result codes],
952 ** [sqlcipher3_vtab_on_conflict()] [SQLCIPHER_ROLLBACK | result codes].
953 */
954 #define SQLCIPHER_OK           0   /* Successful result */
955 /* beginning-of-error-codes */
956 #define SQLCIPHER_ERROR        1   /* SQL error or missing database */
957 #define SQLCIPHER_INTERNAL     2   /* Internal logic error in SQLite */
958 #define SQLCIPHER_PERM         3   /* Access permission denied */
959 #define SQLCIPHER_ABORT        4   /* Callback routine requested an abort */
960 #define SQLCIPHER_BUSY         5   /* The database file is locked */
961 #define SQLCIPHER_LOCKED       6   /* A table in the database is locked */
962 #define SQLCIPHER_NOMEM        7   /* A malloc() failed */
963 #define SQLCIPHER_READONLY     8   /* Attempt to write a readonly database */
964 #define SQLCIPHER_INTERRUPT    9   /* Operation terminated by sqlcipher3_interrupt()*/
965 #define SQLCIPHER_IOERR       10   /* Some kind of disk I/O error occurred */
966 #define SQLCIPHER_CORRUPT     11   /* The database disk image is malformed */
967 #define SQLCIPHER_NOTFOUND    12   /* Unknown opcode in sqlcipher3_file_control() */
968 #define SQLCIPHER_FULL        13   /* Insertion failed because database is full */
969 #define SQLCIPHER_CANTOPEN    14   /* Unable to open the database file */
970 #define SQLCIPHER_PROTOCOL    15   /* Database lock protocol error */
971 #define SQLCIPHER_EMPTY       16   /* Database is empty */
972 #define SQLCIPHER_SCHEMA      17   /* The database schema changed */
973 #define SQLCIPHER_TOOBIG      18   /* String or BLOB exceeds size limit */
974 #define SQLCIPHER_CONSTRAINT  19   /* Abort due to constraint violation */
975 #define SQLCIPHER_MISMATCH    20   /* Data type mismatch */
976 #define SQLCIPHER_MISUSE      21   /* Library used incorrectly */
977 #define SQLCIPHER_NOLFS       22   /* Uses OS features not supported on host */
978 #define SQLCIPHER_AUTH        23   /* Authorization denied */
979 #define SQLCIPHER_FORMAT      24   /* Auxiliary database format error */
980 #define SQLCIPHER_RANGE       25   /* 2nd parameter to sqlcipher3_bind out of range */
981 #define SQLCIPHER_NOTADB      26   /* File opened that is not a database file */
982 #define SQLCIPHER_ROW         100  /* sqlcipher3_step() has another row ready */
983 #define SQLCIPHER_DONE        101  /* sqlcipher3_step() has finished executing */
984 /* end-of-error-codes */
985
986 /*
987 ** CAPI3REF: Extended Result Codes
988 ** KEYWORDS: {extended error code} {extended error codes}
989 ** KEYWORDS: {extended result code} {extended result codes}
990 **
991 ** In its default configuration, SQLite API routines return one of 26 integer
992 ** [SQLCIPHER_OK | result codes].  However, experience has shown that many of
993 ** these result codes are too coarse-grained.  They do not provide as
994 ** much information about problems as programmers might like.  In an effort to
995 ** address this, newer versions of SQLite (version 3.3.8 and later) include
996 ** support for additional result codes that provide more detailed information
997 ** about errors. The extended result codes are enabled or disabled
998 ** on a per database connection basis using the
999 ** [sqlcipher3_extended_result_codes()] API.
1000 **
1001 ** Some of the available extended result codes are listed here.
1002 ** One may expect the number of extended result codes will be expand
1003 ** over time.  Software that uses extended result codes should expect
1004 ** to see new result codes in future releases of SQLite.
1005 **
1006 ** The SQLCIPHER_OK result code will never be extended.  It will always
1007 ** be exactly zero.
1008 */
1009 #define SQLCIPHER_IOERR_READ              (SQLCIPHER_IOERR | (1<<8))
1010 #define SQLCIPHER_IOERR_SHORT_READ        (SQLCIPHER_IOERR | (2<<8))
1011 #define SQLCIPHER_IOERR_WRITE             (SQLCIPHER_IOERR | (3<<8))
1012 #define SQLCIPHER_IOERR_FSYNC             (SQLCIPHER_IOERR | (4<<8))
1013 #define SQLCIPHER_IOERR_DIR_FSYNC         (SQLCIPHER_IOERR | (5<<8))
1014 #define SQLCIPHER_IOERR_TRUNCATE          (SQLCIPHER_IOERR | (6<<8))
1015 #define SQLCIPHER_IOERR_FSTAT             (SQLCIPHER_IOERR | (7<<8))
1016 #define SQLCIPHER_IOERR_UNLOCK            (SQLCIPHER_IOERR | (8<<8))
1017 #define SQLCIPHER_IOERR_RDLOCK            (SQLCIPHER_IOERR | (9<<8))
1018 #define SQLCIPHER_IOERR_DELETE            (SQLCIPHER_IOERR | (10<<8))
1019 #define SQLCIPHER_IOERR_BLOCKED           (SQLCIPHER_IOERR | (11<<8))
1020 #define SQLCIPHER_IOERR_NOMEM             (SQLCIPHER_IOERR | (12<<8))
1021 #define SQLCIPHER_IOERR_ACCESS            (SQLCIPHER_IOERR | (13<<8))
1022 #define SQLCIPHER_IOERR_CHECKRESERVEDLOCK (SQLCIPHER_IOERR | (14<<8))
1023 #define SQLCIPHER_IOERR_LOCK              (SQLCIPHER_IOERR | (15<<8))
1024 #define SQLCIPHER_IOERR_CLOSE             (SQLCIPHER_IOERR | (16<<8))
1025 #define SQLCIPHER_IOERR_DIR_CLOSE         (SQLCIPHER_IOERR | (17<<8))
1026 #define SQLCIPHER_IOERR_SHMOPEN           (SQLCIPHER_IOERR | (18<<8))
1027 #define SQLCIPHER_IOERR_SHMSIZE           (SQLCIPHER_IOERR | (19<<8))
1028 #define SQLCIPHER_IOERR_SHMLOCK           (SQLCIPHER_IOERR | (20<<8))
1029 #define SQLCIPHER_IOERR_SHMMAP            (SQLCIPHER_IOERR | (21<<8))
1030 #define SQLCIPHER_IOERR_SEEK              (SQLCIPHER_IOERR | (22<<8))
1031 #define SQLCIPHER_LOCKED_SHAREDCACHE      (SQLCIPHER_LOCKED |  (1<<8))
1032 #define SQLCIPHER_BUSY_RECOVERY           (SQLCIPHER_BUSY   |  (1<<8))
1033 #define SQLCIPHER_CANTOPEN_NOTEMPDIR      (SQLCIPHER_CANTOPEN | (1<<8))
1034 #define SQLCIPHER_CORRUPT_VTAB            (SQLCIPHER_CORRUPT | (1<<8))
1035 #define SQLCIPHER_READONLY_RECOVERY       (SQLCIPHER_READONLY | (1<<8))
1036 #define SQLCIPHER_READONLY_CANTLOCK       (SQLCIPHER_READONLY | (2<<8))
1037
1038 /*
1039 ** CAPI3REF: Flags For File Open Operations
1040 **
1041 ** These bit values are intended for use in the
1042 ** 3rd parameter to the [sqlcipher3_open_v2()] interface and
1043 ** in the 4th parameter to the [sqlcipher3_vfs.xOpen] method.
1044 */
1045 #define SQLCIPHER_OPEN_READONLY         0x00000001  /* Ok for sqlcipher3_open_v2() */
1046 #define SQLCIPHER_OPEN_READWRITE        0x00000002  /* Ok for sqlcipher3_open_v2() */
1047 #define SQLCIPHER_OPEN_CREATE           0x00000004  /* Ok for sqlcipher3_open_v2() */
1048 #define SQLCIPHER_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1049 #define SQLCIPHER_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1050 #define SQLCIPHER_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1051 #define SQLCIPHER_OPEN_URI              0x00000040  /* Ok for sqlcipher3_open_v2() */
1052 #define SQLCIPHER_OPEN_MAIN_DB          0x00000100  /* VFS only */
1053 #define SQLCIPHER_OPEN_TEMP_DB          0x00000200  /* VFS only */
1054 #define SQLCIPHER_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1055 #define SQLCIPHER_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1056 #define SQLCIPHER_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1057 #define SQLCIPHER_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1058 #define SQLCIPHER_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1059 #define SQLCIPHER_OPEN_NOMUTEX          0x00008000  /* Ok for sqlcipher3_open_v2() */
1060 #define SQLCIPHER_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlcipher3_open_v2() */
1061 #define SQLCIPHER_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlcipher3_open_v2() */
1062 #define SQLCIPHER_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlcipher3_open_v2() */
1063 #define SQLCIPHER_OPEN_WAL              0x00080000  /* VFS only */
1064
1065 /* Reserved:                         0x00F00000 */
1066
1067 /*
1068 ** CAPI3REF: Device Characteristics
1069 **
1070 ** The xDeviceCharacteristics method of the [sqlcipher3_io_methods]
1071 ** object returns an integer which is a vector of the these
1072 ** bit values expressing I/O characteristics of the mass storage
1073 ** device that holds the file that the [sqlcipher3_io_methods]
1074 ** refers to.
1075 **
1076 ** The SQLCIPHER_IOCAP_ATOMIC property means that all writes of
1077 ** any size are atomic.  The SQLCIPHER_IOCAP_ATOMICnnn values
1078 ** mean that writes of blocks that are nnn bytes in size and
1079 ** are aligned to an address which is an integer multiple of
1080 ** nnn are atomic.  The SQLCIPHER_IOCAP_SAFE_APPEND value means
1081 ** that when data is appended to a file, the data is appended
1082 ** first then the size of the file is extended, never the other
1083 ** way around.  The SQLCIPHER_IOCAP_SEQUENTIAL property means that
1084 ** information is written to disk in the same order as calls
1085 ** to xWrite().
1086 */
1087 #define SQLCIPHER_IOCAP_ATOMIC                 0x00000001
1088 #define SQLCIPHER_IOCAP_ATOMIC512              0x00000002
1089 #define SQLCIPHER_IOCAP_ATOMIC1K               0x00000004
1090 #define SQLCIPHER_IOCAP_ATOMIC2K               0x00000008
1091 #define SQLCIPHER_IOCAP_ATOMIC4K               0x00000010
1092 #define SQLCIPHER_IOCAP_ATOMIC8K               0x00000020
1093 #define SQLCIPHER_IOCAP_ATOMIC16K              0x00000040
1094 #define SQLCIPHER_IOCAP_ATOMIC32K              0x00000080
1095 #define SQLCIPHER_IOCAP_ATOMIC64K              0x00000100
1096 #define SQLCIPHER_IOCAP_SAFE_APPEND            0x00000200
1097 #define SQLCIPHER_IOCAP_SEQUENTIAL             0x00000400
1098 #define SQLCIPHER_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1099
1100 /*
1101 ** CAPI3REF: File Locking Levels
1102 **
1103 ** SQLite uses one of these integer values as the second
1104 ** argument to calls it makes to the xLock() and xUnlock() methods
1105 ** of an [sqlcipher3_io_methods] object.
1106 */
1107 #define SQLCIPHER_LOCK_NONE          0
1108 #define SQLCIPHER_LOCK_SHARED        1
1109 #define SQLCIPHER_LOCK_RESERVED      2
1110 #define SQLCIPHER_LOCK_PENDING       3
1111 #define SQLCIPHER_LOCK_EXCLUSIVE     4
1112
1113 /*
1114 ** CAPI3REF: Synchronization Type Flags
1115 **
1116 ** When SQLite invokes the xSync() method of an
1117 ** [sqlcipher3_io_methods] object it uses a combination of
1118 ** these integer values as the second argument.
1119 **
1120 ** When the SQLCIPHER_SYNC_DATAONLY flag is used, it means that the
1121 ** sync operation only needs to flush data to mass storage.  Inode
1122 ** information need not be flushed. If the lower four bits of the flag
1123 ** equal SQLCIPHER_SYNC_NORMAL, that means to use normal fsync() semantics.
1124 ** If the lower four bits equal SQLCIPHER_SYNC_FULL, that means
1125 ** to use Mac OS X style fullsync instead of fsync().
1126 **
1127 ** Do not confuse the SQLCIPHER_SYNC_NORMAL and SQLCIPHER_SYNC_FULL flags
1128 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1129 ** settings.  The [synchronous pragma] determines when calls to the
1130 ** xSync VFS method occur and applies uniformly across all platforms.
1131 ** The SQLCIPHER_SYNC_NORMAL and SQLCIPHER_SYNC_FULL flags determine how
1132 ** energetic or rigorous or forceful the sync operations are and
1133 ** only make a difference on Mac OSX for the default SQLite code.
1134 ** (Third-party VFS implementations might also make the distinction
1135 ** between SQLCIPHER_SYNC_NORMAL and SQLCIPHER_SYNC_FULL, but among the
1136 ** operating systems natively supported by SQLite, only Mac OSX
1137 ** cares about the difference.)
1138 */
1139 #define SQLCIPHER_SYNC_NORMAL        0x00002
1140 #define SQLCIPHER_SYNC_FULL          0x00003
1141 #define SQLCIPHER_SYNC_DATAONLY      0x00010
1142
1143 /*
1144 ** CAPI3REF: OS Interface Open File Handle
1145 **
1146 ** An [sqlcipher3_file] object represents an open file in the 
1147 ** [sqlcipher3_vfs | OS interface layer].  Individual OS interface
1148 ** implementations will
1149 ** want to subclass this object by appending additional fields
1150 ** for their own use.  The pMethods entry is a pointer to an
1151 ** [sqlcipher3_io_methods] object that defines methods for performing
1152 ** I/O operations on the open file.
1153 */
1154 typedef struct sqlcipher3_file sqlcipher3_file;
1155 struct sqlcipher3_file {
1156   const struct sqlcipher3_io_methods *pMethods;  /* Methods for an open file */
1157 };
1158
1159 /*
1160 ** CAPI3REF: OS Interface File Virtual Methods Object
1161 **
1162 ** Every file opened by the [sqlcipher3_vfs.xOpen] method populates an
1163 ** [sqlcipher3_file] object (or, more commonly, a subclass of the
1164 ** [sqlcipher3_file] object) with a pointer to an instance of this object.
1165 ** This object defines the methods used to perform various operations
1166 ** against the open file represented by the [sqlcipher3_file] object.
1167 **
1168 ** If the [sqlcipher3_vfs.xOpen] method sets the sqlcipher3_file.pMethods element 
1169 ** to a non-NULL pointer, then the sqlcipher3_io_methods.xClose method
1170 ** may be invoked even if the [sqlcipher3_vfs.xOpen] reported that it failed.  The
1171 ** only way to prevent a call to xClose following a failed [sqlcipher3_vfs.xOpen]
1172 ** is for the [sqlcipher3_vfs.xOpen] to set the sqlcipher3_file.pMethods element
1173 ** to NULL.
1174 **
1175 ** The flags argument to xSync may be one of [SQLCIPHER_SYNC_NORMAL] or
1176 ** [SQLCIPHER_SYNC_FULL].  The first choice is the normal fsync().
1177 ** The second choice is a Mac OS X style fullsync.  The [SQLCIPHER_SYNC_DATAONLY]
1178 ** flag may be ORed in to indicate that only the data of the file
1179 ** and not its inode needs to be synced.
1180 **
1181 ** The integer values to xLock() and xUnlock() are one of
1182 ** <ul>
1183 ** <li> [SQLCIPHER_LOCK_NONE],
1184 ** <li> [SQLCIPHER_LOCK_SHARED],
1185 ** <li> [SQLCIPHER_LOCK_RESERVED],
1186 ** <li> [SQLCIPHER_LOCK_PENDING], or
1187 ** <li> [SQLCIPHER_LOCK_EXCLUSIVE].
1188 ** </ul>
1189 ** xLock() increases the lock. xUnlock() decreases the lock.
1190 ** The xCheckReservedLock() method checks whether any database connection,
1191 ** either in this process or in some other process, is holding a RESERVED,
1192 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1193 ** if such a lock exists and false otherwise.
1194 **
1195 ** The xFileControl() method is a generic interface that allows custom
1196 ** VFS implementations to directly control an open file using the
1197 ** [sqlcipher3_file_control()] interface.  The second "op" argument is an
1198 ** integer opcode.  The third argument is a generic pointer intended to
1199 ** point to a structure that may contain arguments or space in which to
1200 ** write return values.  Potential uses for xFileControl() might be
1201 ** functions to enable blocking locks with timeouts, to change the
1202 ** locking strategy (for example to use dot-file locks), to inquire
1203 ** about the status of a lock, or to break stale locks.  The SQLite
1204 ** core reserves all opcodes less than 100 for its own use.
1205 ** A [SQLCIPHER_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1206 ** Applications that define a custom xFileControl method should use opcodes
1207 ** greater than 100 to avoid conflicts.  VFS implementations should
1208 ** return [SQLCIPHER_NOTFOUND] for file control opcodes that they do not
1209 ** recognize.
1210 **
1211 ** The xSectorSize() method returns the sector size of the
1212 ** device that underlies the file.  The sector size is the
1213 ** minimum write that can be performed without disturbing
1214 ** other bytes in the file.  The xDeviceCharacteristics()
1215 ** method returns a bit vector describing behaviors of the
1216 ** underlying device:
1217 **
1218 ** <ul>
1219 ** <li> [SQLCIPHER_IOCAP_ATOMIC]
1220 ** <li> [SQLCIPHER_IOCAP_ATOMIC512]
1221 ** <li> [SQLCIPHER_IOCAP_ATOMIC1K]
1222 ** <li> [SQLCIPHER_IOCAP_ATOMIC2K]
1223 ** <li> [SQLCIPHER_IOCAP_ATOMIC4K]
1224 ** <li> [SQLCIPHER_IOCAP_ATOMIC8K]
1225 ** <li> [SQLCIPHER_IOCAP_ATOMIC16K]
1226 ** <li> [SQLCIPHER_IOCAP_ATOMIC32K]
1227 ** <li> [SQLCIPHER_IOCAP_ATOMIC64K]
1228 ** <li> [SQLCIPHER_IOCAP_SAFE_APPEND]
1229 ** <li> [SQLCIPHER_IOCAP_SEQUENTIAL]
1230 ** </ul>
1231 **
1232 ** The SQLCIPHER_IOCAP_ATOMIC property means that all writes of
1233 ** any size are atomic.  The SQLCIPHER_IOCAP_ATOMICnnn values
1234 ** mean that writes of blocks that are nnn bytes in size and
1235 ** are aligned to an address which is an integer multiple of
1236 ** nnn are atomic.  The SQLCIPHER_IOCAP_SAFE_APPEND value means
1237 ** that when data is appended to a file, the data is appended
1238 ** first then the size of the file is extended, never the other
1239 ** way around.  The SQLCIPHER_IOCAP_SEQUENTIAL property means that
1240 ** information is written to disk in the same order as calls
1241 ** to xWrite().
1242 **
1243 ** If xRead() returns SQLCIPHER_IOERR_SHORT_READ it must also fill
1244 ** in the unread portions of the buffer with zeros.  A VFS that
1245 ** fails to zero-fill short reads might seem to work.  However,
1246 ** failure to zero-fill short reads will eventually lead to
1247 ** database corruption.
1248 */
1249 typedef struct sqlcipher3_io_methods sqlcipher3_io_methods;
1250 struct sqlcipher3_io_methods {
1251   int iVersion;
1252   int (*xClose)(sqlcipher3_file*);
1253   int (*xRead)(sqlcipher3_file*, void*, int iAmt, sqlcipher3_int64 iOfst);
1254   int (*xWrite)(sqlcipher3_file*, const void*, int iAmt, sqlcipher3_int64 iOfst);
1255   int (*xTruncate)(sqlcipher3_file*, sqlcipher3_int64 size);
1256   int (*xSync)(sqlcipher3_file*, int flags);
1257   int (*xFileSize)(sqlcipher3_file*, sqlcipher3_int64 *pSize);
1258   int (*xLock)(sqlcipher3_file*, int);
1259   int (*xUnlock)(sqlcipher3_file*, int);
1260   int (*xCheckReservedLock)(sqlcipher3_file*, int *pResOut);
1261   int (*xFileControl)(sqlcipher3_file*, int op, void *pArg);
1262   int (*xSectorSize)(sqlcipher3_file*);
1263   int (*xDeviceCharacteristics)(sqlcipher3_file*);
1264   /* Methods above are valid for version 1 */
1265   int (*xShmMap)(sqlcipher3_file*, int iPg, int pgsz, int, void volatile**);
1266   int (*xShmLock)(sqlcipher3_file*, int offset, int n, int flags);
1267   void (*xShmBarrier)(sqlcipher3_file*);
1268   int (*xShmUnmap)(sqlcipher3_file*, int deleteFlag);
1269   /* Methods above are valid for version 2 */
1270   /* Additional methods may be added in future releases */
1271 };
1272
1273 /*
1274 ** CAPI3REF: Standard File Control Opcodes
1275 **
1276 ** These integer constants are opcodes for the xFileControl method
1277 ** of the [sqlcipher3_io_methods] object and for the [sqlcipher3_file_control()]
1278 ** interface.
1279 **
1280 ** The [SQLCIPHER_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1281 ** opcode causes the xFileControl method to write the current state of
1282 ** the lock (one of [SQLCIPHER_LOCK_NONE], [SQLCIPHER_LOCK_SHARED],
1283 ** [SQLCIPHER_LOCK_RESERVED], [SQLCIPHER_LOCK_PENDING], or [SQLCIPHER_LOCK_EXCLUSIVE])
1284 ** into an integer that the pArg argument points to. This capability
1285 ** is used during testing and only needs to be supported when SQLCIPHER_TEST
1286 ** is defined.
1287 **
1288 ** The [SQLCIPHER_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1289 ** layer a hint of how large the database file will grow to be during the
1290 ** current transaction.  This hint is not guaranteed to be accurate but it
1291 ** is often close.  The underlying VFS might choose to preallocate database
1292 ** file space based on this hint in order to help writes to the database
1293 ** file run faster.
1294 **
1295 ** The [SQLCIPHER_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1296 ** extends and truncates the database file in chunks of a size specified
1297 ** by the user. The fourth argument to [sqlcipher3_file_control()] should 
1298 ** point to an integer (type int) containing the new chunk-size to use
1299 ** for the nominated database. Allocating database file space in large
1300 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1301 ** improve performance on some systems.
1302 **
1303 ** The [SQLCIPHER_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1304 ** to the [sqlcipher3_file] object associated with a particular database
1305 ** connection.  See the [sqlcipher3_file_control()] documentation for
1306 ** additional information.
1307 **
1308 ** ^(The [SQLCIPHER_FCNTL_SYNC_OMITTED] opcode is generated internally by
1309 ** SQLite and sent to all VFSes in place of a call to the xSync method
1310 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1311 ** Some specialized VFSes need this signal in order to operate correctly
1312 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most 
1313 ** VFSes do not need this signal and should silently ignore this opcode.
1314 ** Applications should not call [sqlcipher3_file_control()] with this
1315 ** opcode as doing so may disrupt the operation of the specialized VFSes
1316 ** that do require it.  
1317 **
1318 ** ^The [SQLCIPHER_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1319 ** retry counts and intervals for certain disk I/O operations for the
1320 ** windows [VFS] in order to work to provide robustness against
1321 ** anti-virus programs.  By default, the windows VFS will retry file read,
1322 ** file write, and file delete operations up to 10 times, with a delay
1323 ** of 25 milliseconds before the first retry and with the delay increasing
1324 ** by an additional 25 milliseconds with each subsequent retry.  This
1325 ** opcode allows those to values (10 retries and 25 milliseconds of delay)
1326 ** to be adjusted.  The values are changed for all database connections
1327 ** within the same process.  The argument is a pointer to an array of two
1328 ** integers where the first integer i the new retry count and the second
1329 ** integer is the delay.  If either integer is negative, then the setting
1330 ** is not changed but instead the prior value of that setting is written
1331 ** into the array entry, allowing the current retry settings to be
1332 ** interrogated.  The zDbName parameter is ignored.
1333 **
1334 ** ^The [SQLCIPHER_FCNTL_PERSIST_WAL] opcode is used to set or query the
1335 ** persistent [WAL | Write AHead Log] setting.  By default, the auxiliary
1336 ** write ahead log and shared memory files used for transaction control
1337 ** are automatically deleted when the latest connection to the database
1338 ** closes.  Setting persistent WAL mode causes those files to persist after
1339 ** close.  Persisting the files is useful when other processes that do not
1340 ** have write permission on the directory containing the database file want
1341 ** to read the database file, as the WAL and shared memory files must exist
1342 ** in order for the database to be readable.  The fourth parameter to
1343 ** [sqlcipher3_file_control()] for this opcode should be a pointer to an integer.
1344 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1345 ** WAL mode.  If the integer is -1, then it is overwritten with the current
1346 ** WAL persistence setting.
1347 **
1348 ** ^The [SQLCIPHER_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1349 ** a write transaction to indicate that, unless it is rolled back for some
1350 ** reason, the entire database file will be overwritten by the current 
1351 ** transaction. This is used by VACUUM operations.
1352 */
1353 #define SQLCIPHER_FCNTL_LOCKSTATE        1
1354 #define SQLCIPHER_GET_LOCKPROXYFILE      2
1355 #define SQLCIPHER_SET_LOCKPROXYFILE      3
1356 #define SQLCIPHER_LAST_ERRNO             4
1357 #define SQLCIPHER_FCNTL_SIZE_HINT        5
1358 #define SQLCIPHER_FCNTL_CHUNK_SIZE       6
1359 #define SQLCIPHER_FCNTL_FILE_POINTER     7
1360 #define SQLCIPHER_FCNTL_SYNC_OMITTED     8
1361 #define SQLCIPHER_FCNTL_WIN32_AV_RETRY   9
1362 #define SQLCIPHER_FCNTL_PERSIST_WAL     10
1363 #define SQLCIPHER_FCNTL_OVERWRITE       11
1364
1365 /*
1366 ** CAPI3REF: Mutex Handle
1367 **
1368 ** The mutex module within SQLite defines [sqlcipher3_mutex] to be an
1369 ** abstract type for a mutex object.  The SQLite core never looks
1370 ** at the internal representation of an [sqlcipher3_mutex].  It only
1371 ** deals with pointers to the [sqlcipher3_mutex] object.
1372 **
1373 ** Mutexes are created using [sqlcipher3_mutex_alloc()].
1374 */
1375 typedef struct sqlcipher3_mutex sqlcipher3_mutex;
1376
1377 /*
1378 ** CAPI3REF: OS Interface Object
1379 **
1380 ** An instance of the sqlcipher3_vfs object defines the interface between
1381 ** the SQLite core and the underlying operating system.  The "vfs"
1382 ** in the name of the object stands for "virtual file system".  See
1383 ** the [VFS | VFS documentation] for further information.
1384 **
1385 ** The value of the iVersion field is initially 1 but may be larger in
1386 ** future versions of SQLite.  Additional fields may be appended to this
1387 ** object when the iVersion value is increased.  Note that the structure
1388 ** of the sqlcipher3_vfs object changes in the transaction between
1389 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1390 ** modified.
1391 **
1392 ** The szOsFile field is the size of the subclassed [sqlcipher3_file]
1393 ** structure used by this VFS.  mxPathname is the maximum length of
1394 ** a pathname in this VFS.
1395 **
1396 ** Registered sqlcipher3_vfs objects are kept on a linked list formed by
1397 ** the pNext pointer.  The [sqlcipher3_vfs_register()]
1398 ** and [sqlcipher3_vfs_unregister()] interfaces manage this list
1399 ** in a thread-safe way.  The [sqlcipher3_vfs_find()] interface
1400 ** searches the list.  Neither the application code nor the VFS
1401 ** implementation should use the pNext pointer.
1402 **
1403 ** The pNext field is the only field in the sqlcipher3_vfs
1404 ** structure that SQLite will ever modify.  SQLite will only access
1405 ** or modify this field while holding a particular static mutex.
1406 ** The application should never modify anything within the sqlcipher3_vfs
1407 ** object once the object has been registered.
1408 **
1409 ** The zName field holds the name of the VFS module.  The name must
1410 ** be unique across all VFS modules.
1411 **
1412 ** [[sqlcipher3_vfs.xOpen]]
1413 ** ^SQLite guarantees that the zFilename parameter to xOpen
1414 ** is either a NULL pointer or string obtained
1415 ** from xFullPathname() with an optional suffix added.
1416 ** ^If a suffix is added to the zFilename parameter, it will
1417 ** consist of a single "-" character followed by no more than
1418 ** 10 alphanumeric and/or "-" characters.
1419 ** ^SQLite further guarantees that
1420 ** the string will be valid and unchanged until xClose() is
1421 ** called. Because of the previous sentence,
1422 ** the [sqlcipher3_file] can safely store a pointer to the
1423 ** filename if it needs to remember the filename for some reason.
1424 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1425 ** must invent its own temporary name for the file.  ^Whenever the 
1426 ** xFilename parameter is NULL it will also be the case that the
1427 ** flags parameter will include [SQLCIPHER_OPEN_DELETEONCLOSE].
1428 **
1429 ** The flags argument to xOpen() includes all bits set in
1430 ** the flags argument to [sqlcipher3_open_v2()].  Or if [sqlcipher3_open()]
1431 ** or [sqlcipher3_open16()] is used, then flags includes at least
1432 ** [SQLCIPHER_OPEN_READWRITE] | [SQLCIPHER_OPEN_CREATE]. 
1433 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1434 ** include [SQLCIPHER_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1435 **
1436 ** ^(SQLite will also add one of the following flags to the xOpen()
1437 ** call, depending on the object being opened:
1438 **
1439 ** <ul>
1440 ** <li>  [SQLCIPHER_OPEN_MAIN_DB]
1441 ** <li>  [SQLCIPHER_OPEN_MAIN_JOURNAL]
1442 ** <li>  [SQLCIPHER_OPEN_TEMP_DB]
1443 ** <li>  [SQLCIPHER_OPEN_TEMP_JOURNAL]
1444 ** <li>  [SQLCIPHER_OPEN_TRANSIENT_DB]
1445 ** <li>  [SQLCIPHER_OPEN_SUBJOURNAL]
1446 ** <li>  [SQLCIPHER_OPEN_MASTER_JOURNAL]
1447 ** <li>  [SQLCIPHER_OPEN_WAL]
1448 ** </ul>)^
1449 **
1450 ** The file I/O implementation can use the object type flags to
1451 ** change the way it deals with files.  For example, an application
1452 ** that does not care about crash recovery or rollback might make
1453 ** the open of a journal file a no-op.  Writes to this journal would
1454 ** also be no-ops, and any attempt to read the journal would return
1455 ** SQLCIPHER_IOERR.  Or the implementation might recognize that a database
1456 ** file will be doing page-aligned sector reads and writes in a random
1457 ** order and set up its I/O subsystem accordingly.
1458 **
1459 ** SQLite might also add one of the following flags to the xOpen method:
1460 **
1461 ** <ul>
1462 ** <li> [SQLCIPHER_OPEN_DELETEONCLOSE]
1463 ** <li> [SQLCIPHER_OPEN_EXCLUSIVE]
1464 ** </ul>
1465 **
1466 ** The [SQLCIPHER_OPEN_DELETEONCLOSE] flag means the file should be
1467 ** deleted when it is closed.  ^The [SQLCIPHER_OPEN_DELETEONCLOSE]
1468 ** will be set for TEMP databases and their journals, transient
1469 ** databases, and subjournals.
1470 **
1471 ** ^The [SQLCIPHER_OPEN_EXCLUSIVE] flag is always used in conjunction
1472 ** with the [SQLCIPHER_OPEN_CREATE] flag, which are both directly
1473 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1474 ** API.  The SQLCIPHER_OPEN_EXCLUSIVE flag, when paired with the 
1475 ** SQLCIPHER_OPEN_CREATE, is used to indicate that file should always
1476 ** be created, and that it is an error if it already exists.
1477 ** It is <i>not</i> used to indicate the file should be opened 
1478 ** for exclusive access.
1479 **
1480 ** ^At least szOsFile bytes of memory are allocated by SQLite
1481 ** to hold the  [sqlcipher3_file] structure passed as the third
1482 ** argument to xOpen.  The xOpen method does not have to
1483 ** allocate the structure; it should just fill it in.  Note that
1484 ** the xOpen method must set the sqlcipher3_file.pMethods to either
1485 ** a valid [sqlcipher3_io_methods] object or to NULL.  xOpen must do
1486 ** this even if the open fails.  SQLite expects that the sqlcipher3_file.pMethods
1487 ** element will be valid after xOpen returns regardless of the success
1488 ** or failure of the xOpen call.
1489 **
1490 ** [[sqlcipher3_vfs.xAccess]]
1491 ** ^The flags argument to xAccess() may be [SQLCIPHER_ACCESS_EXISTS]
1492 ** to test for the existence of a file, or [SQLCIPHER_ACCESS_READWRITE] to
1493 ** test whether a file is readable and writable, or [SQLCIPHER_ACCESS_READ]
1494 ** to test whether a file is at least readable.   The file can be a
1495 ** directory.
1496 **
1497 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1498 ** output buffer xFullPathname.  The exact size of the output buffer
1499 ** is also passed as a parameter to both  methods. If the output buffer
1500 ** is not large enough, [SQLCIPHER_CANTOPEN] should be returned. Since this is
1501 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1502 ** to prevent this by setting mxPathname to a sufficiently large value.
1503 **
1504 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1505 ** interfaces are not strictly a part of the filesystem, but they are
1506 ** included in the VFS structure for completeness.
1507 ** The xRandomness() function attempts to return nBytes bytes
1508 ** of good-quality randomness into zOut.  The return value is
1509 ** the actual number of bytes of randomness obtained.
1510 ** The xSleep() method causes the calling thread to sleep for at
1511 ** least the number of microseconds given.  ^The xCurrentTime()
1512 ** method returns a Julian Day Number for the current date and time as
1513 ** a floating point value.
1514 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1515 ** Day Number multiplied by 86400000 (the number of milliseconds in 
1516 ** a 24-hour day).  
1517 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1518 ** date and time if that method is available (if iVersion is 2 or 
1519 ** greater and the function pointer is not NULL) and will fall back
1520 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1521 **
1522 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1523 ** are not used by the SQLite core.  These optional interfaces are provided
1524 ** by some VFSes to facilitate testing of the VFS code. By overriding 
1525 ** system calls with functions under its control, a test program can
1526 ** simulate faults and error conditions that would otherwise be difficult
1527 ** or impossible to induce.  The set of system calls that can be overridden
1528 ** varies from one VFS to another, and from one version of the same VFS to the
1529 ** next.  Applications that use these interfaces must be prepared for any
1530 ** or all of these interfaces to be NULL or for their behavior to change
1531 ** from one release to the next.  Applications must not attempt to access
1532 ** any of these methods if the iVersion of the VFS is less than 3.
1533 */
1534 typedef struct sqlcipher3_vfs sqlcipher3_vfs;
1535 typedef void (*sqlcipher3_syscall_ptr)(void);
1536 struct sqlcipher3_vfs {
1537   int iVersion;            /* Structure version number (currently 3) */
1538   int szOsFile;            /* Size of subclassed sqlcipher3_file */
1539   int mxPathname;          /* Maximum file pathname length */
1540   sqlcipher3_vfs *pNext;      /* Next registered VFS */
1541   const char *zName;       /* Name of this virtual file system */
1542   void *pAppData;          /* Pointer to application-specific data */
1543   int (*xOpen)(sqlcipher3_vfs*, const char *zName, sqlcipher3_file*,
1544                int flags, int *pOutFlags);
1545   int (*xDelete)(sqlcipher3_vfs*, const char *zName, int syncDir);
1546   int (*xAccess)(sqlcipher3_vfs*, const char *zName, int flags, int *pResOut);
1547   int (*xFullPathname)(sqlcipher3_vfs*, const char *zName, int nOut, char *zOut);
1548   void *(*xDlOpen)(sqlcipher3_vfs*, const char *zFilename);
1549   void (*xDlError)(sqlcipher3_vfs*, int nByte, char *zErrMsg);
1550   void (*(*xDlSym)(sqlcipher3_vfs*,void*, const char *zSymbol))(void);
1551   void (*xDlClose)(sqlcipher3_vfs*, void*);
1552   int (*xRandomness)(sqlcipher3_vfs*, int nByte, char *zOut);
1553   int (*xSleep)(sqlcipher3_vfs*, int microseconds);
1554   int (*xCurrentTime)(sqlcipher3_vfs*, double*);
1555   int (*xGetLastError)(sqlcipher3_vfs*, int, char *);
1556   /*
1557   ** The methods above are in version 1 of the sqlcipher_vfs object
1558   ** definition.  Those that follow are added in version 2 or later
1559   */
1560   int (*xCurrentTimeInt64)(sqlcipher3_vfs*, sqlcipher3_int64*);
1561   /*
1562   ** The methods above are in versions 1 and 2 of the sqlcipher_vfs object.
1563   ** Those below are for version 3 and greater.
1564   */
1565   int (*xSetSystemCall)(sqlcipher3_vfs*, const char *zName, sqlcipher3_syscall_ptr);
1566   sqlcipher3_syscall_ptr (*xGetSystemCall)(sqlcipher3_vfs*, const char *zName);
1567   const char *(*xNextSystemCall)(sqlcipher3_vfs*, const char *zName);
1568   /*
1569   ** The methods above are in versions 1 through 3 of the sqlcipher_vfs object.
1570   ** New fields may be appended in figure versions.  The iVersion
1571   ** value will increment whenever this happens. 
1572   */
1573 };
1574
1575 /*
1576 ** CAPI3REF: Flags for the xAccess VFS method
1577 **
1578 ** These integer constants can be used as the third parameter to
1579 ** the xAccess method of an [sqlcipher3_vfs] object.  They determine
1580 ** what kind of permissions the xAccess method is looking for.
1581 ** With SQLCIPHER_ACCESS_EXISTS, the xAccess method
1582 ** simply checks whether the file exists.
1583 ** With SQLCIPHER_ACCESS_READWRITE, the xAccess method
1584 ** checks whether the named directory is both readable and writable
1585 ** (in other words, if files can be added, removed, and renamed within
1586 ** the directory).
1587 ** The SQLCIPHER_ACCESS_READWRITE constant is currently used only by the
1588 ** [temp_store_directory pragma], though this could change in a future
1589 ** release of SQLite.
1590 ** With SQLCIPHER_ACCESS_READ, the xAccess method
1591 ** checks whether the file is readable.  The SQLCIPHER_ACCESS_READ constant is
1592 ** currently unused, though it might be used in a future release of
1593 ** SQLite.
1594 */
1595 #define SQLCIPHER_ACCESS_EXISTS    0
1596 #define SQLCIPHER_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1597 #define SQLCIPHER_ACCESS_READ      2   /* Unused */
1598
1599 /*
1600 ** CAPI3REF: Flags for the xShmLock VFS method
1601 **
1602 ** These integer constants define the various locking operations
1603 ** allowed by the xShmLock method of [sqlcipher3_io_methods].  The
1604 ** following are the only legal combinations of flags to the
1605 ** xShmLock method:
1606 **
1607 ** <ul>
1608 ** <li>  SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_SHARED
1609 ** <li>  SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_EXCLUSIVE
1610 ** <li>  SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_SHARED
1611 ** <li>  SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_EXCLUSIVE
1612 ** </ul>
1613 **
1614 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1615 ** was given no the corresponding lock.  
1616 **
1617 ** The xShmLock method can transition between unlocked and SHARED or
1618 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1619 ** and EXCLUSIVE.
1620 */
1621 #define SQLCIPHER_SHM_UNLOCK       1
1622 #define SQLCIPHER_SHM_LOCK         2
1623 #define SQLCIPHER_SHM_SHARED       4
1624 #define SQLCIPHER_SHM_EXCLUSIVE    8
1625
1626 /*
1627 ** CAPI3REF: Maximum xShmLock index
1628 **
1629 ** The xShmLock method on [sqlcipher3_io_methods] may use values
1630 ** between 0 and this upper bound as its "offset" argument.
1631 ** The SQLite core will never attempt to acquire or release a
1632 ** lock outside of this range
1633 */
1634 #define SQLCIPHER_SHM_NLOCK        8
1635
1636
1637 /*
1638 ** CAPI3REF: Initialize The SQLite Library
1639 **
1640 ** ^The sqlcipher3_initialize() routine initializes the
1641 ** SQLite library.  ^The sqlcipher3_shutdown() routine
1642 ** deallocates any resources that were allocated by sqlcipher3_initialize().
1643 ** These routines are designed to aid in process initialization and
1644 ** shutdown on embedded systems.  Workstation applications using
1645 ** SQLite normally do not need to invoke either of these routines.
1646 **
1647 ** A call to sqlcipher3_initialize() is an "effective" call if it is
1648 ** the first time sqlcipher3_initialize() is invoked during the lifetime of
1649 ** the process, or if it is the first time sqlcipher3_initialize() is invoked
1650 ** following a call to sqlcipher3_shutdown().  ^(Only an effective call
1651 ** of sqlcipher3_initialize() does any initialization.  All other calls
1652 ** are harmless no-ops.)^
1653 **
1654 ** A call to sqlcipher3_shutdown() is an "effective" call if it is the first
1655 ** call to sqlcipher3_shutdown() since the last sqlcipher3_initialize().  ^(Only
1656 ** an effective call to sqlcipher3_shutdown() does any deinitialization.
1657 ** All other valid calls to sqlcipher3_shutdown() are harmless no-ops.)^
1658 **
1659 ** The sqlcipher3_initialize() interface is threadsafe, but sqlcipher3_shutdown()
1660 ** is not.  The sqlcipher3_shutdown() interface must only be called from a
1661 ** single thread.  All open [database connections] must be closed and all
1662 ** other SQLite resources must be deallocated prior to invoking
1663 ** sqlcipher3_shutdown().
1664 **
1665 ** Among other things, ^sqlcipher3_initialize() will invoke
1666 ** sqlcipher3_os_init().  Similarly, ^sqlcipher3_shutdown()
1667 ** will invoke sqlcipher3_os_end().
1668 **
1669 ** ^The sqlcipher3_initialize() routine returns [SQLCIPHER_OK] on success.
1670 ** ^If for some reason, sqlcipher3_initialize() is unable to initialize
1671 ** the library (perhaps it is unable to allocate a needed resource such
1672 ** as a mutex) it returns an [error code] other than [SQLCIPHER_OK].
1673 **
1674 ** ^The sqlcipher3_initialize() routine is called internally by many other
1675 ** SQLite interfaces so that an application usually does not need to
1676 ** invoke sqlcipher3_initialize() directly.  For example, [sqlcipher3_open()]
1677 ** calls sqlcipher3_initialize() so the SQLite library will be automatically
1678 ** initialized when [sqlcipher3_open()] is called if it has not be initialized
1679 ** already.  ^However, if SQLite is compiled with the [SQLCIPHER_OMIT_AUTOINIT]
1680 ** compile-time option, then the automatic calls to sqlcipher3_initialize()
1681 ** are omitted and the application must call sqlcipher3_initialize() directly
1682 ** prior to using any other SQLite interface.  For maximum portability,
1683 ** it is recommended that applications always invoke sqlcipher3_initialize()
1684 ** directly prior to using any other SQLite interface.  Future releases
1685 ** of SQLite may require this.  In other words, the behavior exhibited
1686 ** when SQLite is compiled with [SQLCIPHER_OMIT_AUTOINIT] might become the
1687 ** default behavior in some future release of SQLite.
1688 **
1689 ** The sqlcipher3_os_init() routine does operating-system specific
1690 ** initialization of the SQLite library.  The sqlcipher3_os_end()
1691 ** routine undoes the effect of sqlcipher3_os_init().  Typical tasks
1692 ** performed by these routines include allocation or deallocation
1693 ** of static resources, initialization of global variables,
1694 ** setting up a default [sqlcipher3_vfs] module, or setting up
1695 ** a default configuration using [sqlcipher3_config()].
1696 **
1697 ** The application should never invoke either sqlcipher3_os_init()
1698 ** or sqlcipher3_os_end() directly.  The application should only invoke
1699 ** sqlcipher3_initialize() and sqlcipher3_shutdown().  The sqlcipher3_os_init()
1700 ** interface is called automatically by sqlcipher3_initialize() and
1701 ** sqlcipher3_os_end() is called by sqlcipher3_shutdown().  Appropriate
1702 ** implementations for sqlcipher3_os_init() and sqlcipher3_os_end()
1703 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1704 ** When [custom builds | built for other platforms]
1705 ** (using the [SQLCIPHER_OS_OTHER=1] compile-time
1706 ** option) the application must supply a suitable implementation for
1707 ** sqlcipher3_os_init() and sqlcipher3_os_end().  An application-supplied
1708 ** implementation of sqlcipher3_os_init() or sqlcipher3_os_end()
1709 ** must return [SQLCIPHER_OK] on success and some other [error code] upon
1710 ** failure.
1711 */
1712 SQLCIPHER_API int sqlcipher3_initialize(void);
1713 SQLCIPHER_API int sqlcipher3_shutdown(void);
1714 SQLCIPHER_API int sqlcipher3_os_init(void);
1715 SQLCIPHER_API int sqlcipher3_os_end(void);
1716
1717 /*
1718 ** CAPI3REF: Configuring The SQLite Library
1719 **
1720 ** The sqlcipher3_config() interface is used to make global configuration
1721 ** changes to SQLite in order to tune SQLite to the specific needs of
1722 ** the application.  The default configuration is recommended for most
1723 ** applications and so this routine is usually not necessary.  It is
1724 ** provided to support rare applications with unusual needs.
1725 **
1726 ** The sqlcipher3_config() interface is not threadsafe.  The application
1727 ** must insure that no other SQLite interfaces are invoked by other
1728 ** threads while sqlcipher3_config() is running.  Furthermore, sqlcipher3_config()
1729 ** may only be invoked prior to library initialization using
1730 ** [sqlcipher3_initialize()] or after shutdown by [sqlcipher3_shutdown()].
1731 ** ^If sqlcipher3_config() is called after [sqlcipher3_initialize()] and before
1732 ** [sqlcipher3_shutdown()] then it will return SQLCIPHER_MISUSE.
1733 ** Note, however, that ^sqlcipher3_config() can be called as part of the
1734 ** implementation of an application-defined [sqlcipher3_os_init()].
1735 **
1736 ** The first argument to sqlcipher3_config() is an integer
1737 ** [configuration option] that determines
1738 ** what property of SQLite is to be configured.  Subsequent arguments
1739 ** vary depending on the [configuration option]
1740 ** in the first argument.
1741 **
1742 ** ^When a configuration option is set, sqlcipher3_config() returns [SQLCIPHER_OK].
1743 ** ^If the option is unknown or SQLite is unable to set the option
1744 ** then this routine returns a non-zero [error code].
1745 */
1746 SQLCIPHER_API int sqlcipher3_config(int, ...);
1747
1748 /*
1749 ** CAPI3REF: Configure database connections
1750 **
1751 ** The sqlcipher3_db_config() interface is used to make configuration
1752 ** changes to a [database connection].  The interface is similar to
1753 ** [sqlcipher3_config()] except that the changes apply to a single
1754 ** [database connection] (specified in the first argument).
1755 **
1756 ** The second argument to sqlcipher3_db_config(D,V,...)  is the
1757 ** [SQLCIPHER_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
1758 ** that indicates what aspect of the [database connection] is being configured.
1759 ** Subsequent arguments vary depending on the configuration verb.
1760 **
1761 ** ^Calls to sqlcipher3_db_config() return SQLCIPHER_OK if and only if
1762 ** the call is considered successful.
1763 */
1764 SQLCIPHER_API int sqlcipher3_db_config(sqlcipher3*, int op, ...);
1765
1766 /*
1767 ** CAPI3REF: Memory Allocation Routines
1768 **
1769 ** An instance of this object defines the interface between SQLite
1770 ** and low-level memory allocation routines.
1771 **
1772 ** This object is used in only one place in the SQLite interface.
1773 ** A pointer to an instance of this object is the argument to
1774 ** [sqlcipher3_config()] when the configuration option is
1775 ** [SQLCIPHER_CONFIG_MALLOC] or [SQLCIPHER_CONFIG_GETMALLOC].  
1776 ** By creating an instance of this object
1777 ** and passing it to [sqlcipher3_config]([SQLCIPHER_CONFIG_MALLOC])
1778 ** during configuration, an application can specify an alternative
1779 ** memory allocation subsystem for SQLite to use for all of its
1780 ** dynamic memory needs.
1781 **
1782 ** Note that SQLite comes with several [built-in memory allocators]
1783 ** that are perfectly adequate for the overwhelming majority of applications
1784 ** and that this object is only useful to a tiny minority of applications
1785 ** with specialized memory allocation requirements.  This object is
1786 ** also used during testing of SQLite in order to specify an alternative
1787 ** memory allocator that simulates memory out-of-memory conditions in
1788 ** order to verify that SQLite recovers gracefully from such
1789 ** conditions.
1790 **
1791 ** The xMalloc, xRealloc, and xFree methods must work like the
1792 ** malloc(), realloc() and free() functions from the standard C library.
1793 ** ^SQLite guarantees that the second argument to
1794 ** xRealloc is always a value returned by a prior call to xRoundup.
1795 **
1796 ** xSize should return the allocated size of a memory allocation
1797 ** previously obtained from xMalloc or xRealloc.  The allocated size
1798 ** is always at least as big as the requested size but may be larger.
1799 **
1800 ** The xRoundup method returns what would be the allocated size of
1801 ** a memory allocation given a particular requested size.  Most memory
1802 ** allocators round up memory allocations at least to the next multiple
1803 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1804 ** Every memory allocation request coming in through [sqlcipher3_malloc()]
1805 ** or [sqlcipher3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1806 ** that causes the corresponding memory allocation to fail.
1807 **
1808 ** The xInit method initializes the memory allocator.  (For example,
1809 ** it might allocate any require mutexes or initialize internal data
1810 ** structures.  The xShutdown method is invoked (indirectly) by
1811 ** [sqlcipher3_shutdown()] and should deallocate any resources acquired
1812 ** by xInit.  The pAppData pointer is used as the only parameter to
1813 ** xInit and xShutdown.
1814 **
1815 ** SQLite holds the [SQLCIPHER_MUTEX_STATIC_MASTER] mutex when it invokes
1816 ** the xInit method, so the xInit method need not be threadsafe.  The
1817 ** xShutdown method is only called from [sqlcipher3_shutdown()] so it does
1818 ** not need to be threadsafe either.  For all other methods, SQLite
1819 ** holds the [SQLCIPHER_MUTEX_STATIC_MEM] mutex as long as the
1820 ** [SQLCIPHER_CONFIG_MEMSTATUS] configuration option is turned on (which
1821 ** it is by default) and so the methods are automatically serialized.
1822 ** However, if [SQLCIPHER_CONFIG_MEMSTATUS] is disabled, then the other
1823 ** methods must be threadsafe or else make their own arrangements for
1824 ** serialization.
1825 **
1826 ** SQLite will never invoke xInit() more than once without an intervening
1827 ** call to xShutdown().
1828 */
1829 typedef struct sqlcipher3_mem_methods sqlcipher3_mem_methods;
1830 struct sqlcipher3_mem_methods {
1831   void *(*xMalloc)(int);         /* Memory allocation function */
1832   void (*xFree)(void*);          /* Free a prior allocation */
1833   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1834   int (*xSize)(void*);           /* Return the size of an allocation */
1835   int (*xRoundup)(int);          /* Round up request size to allocation size */
1836   int (*xInit)(void*);           /* Initialize the memory allocator */
1837   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1838   void *pAppData;                /* Argument to xInit() and xShutdown() */
1839 };
1840
1841 /*
1842 ** CAPI3REF: Configuration Options
1843 ** KEYWORDS: {configuration option}
1844 **
1845 ** These constants are the available integer configuration options that
1846 ** can be passed as the first argument to the [sqlcipher3_config()] interface.
1847 **
1848 ** New configuration options may be added in future releases of SQLite.
1849 ** Existing configuration options might be discontinued.  Applications
1850 ** should check the return code from [sqlcipher3_config()] to make sure that
1851 ** the call worked.  The [sqlcipher3_config()] interface will return a
1852 ** non-zero [error code] if a discontinued or unsupported configuration option
1853 ** is invoked.
1854 **
1855 ** <dl>
1856 ** [[SQLCIPHER_CONFIG_SINGLETHREAD]] <dt>SQLCIPHER_CONFIG_SINGLETHREAD</dt>
1857 ** <dd>There are no arguments to this option.  ^This option sets the
1858 ** [threading mode] to Single-thread.  In other words, it disables
1859 ** all mutexing and puts SQLite into a mode where it can only be used
1860 ** by a single thread.   ^If SQLite is compiled with
1861 ** the [SQLCIPHER_THREADSAFE | SQLCIPHER_THREADSAFE=0] compile-time option then
1862 ** it is not possible to change the [threading mode] from its default
1863 ** value of Single-thread and so [sqlcipher3_config()] will return 
1864 ** [SQLCIPHER_ERROR] if called with the SQLCIPHER_CONFIG_SINGLETHREAD
1865 ** configuration option.</dd>
1866 **
1867 ** [[SQLCIPHER_CONFIG_MULTITHREAD]] <dt>SQLCIPHER_CONFIG_MULTITHREAD</dt>
1868 ** <dd>There are no arguments to this option.  ^This option sets the
1869 ** [threading mode] to Multi-thread.  In other words, it disables
1870 ** mutexing on [database connection] and [prepared statement] objects.
1871 ** The application is responsible for serializing access to
1872 ** [database connections] and [prepared statements].  But other mutexes
1873 ** are enabled so that SQLite will be safe to use in a multi-threaded
1874 ** environment as long as no two threads attempt to use the same
1875 ** [database connection] at the same time.  ^If SQLite is compiled with
1876 ** the [SQLCIPHER_THREADSAFE | SQLCIPHER_THREADSAFE=0] compile-time option then
1877 ** it is not possible to set the Multi-thread [threading mode] and
1878 ** [sqlcipher3_config()] will return [SQLCIPHER_ERROR] if called with the
1879 ** SQLCIPHER_CONFIG_MULTITHREAD configuration option.</dd>
1880 **
1881 ** [[SQLCIPHER_CONFIG_SERIALIZED]] <dt>SQLCIPHER_CONFIG_SERIALIZED</dt>
1882 ** <dd>There are no arguments to this option.  ^This option sets the
1883 ** [threading mode] to Serialized. In other words, this option enables
1884 ** all mutexes including the recursive
1885 ** mutexes on [database connection] and [prepared statement] objects.
1886 ** In this mode (which is the default when SQLite is compiled with
1887 ** [SQLCIPHER_THREADSAFE=1]) the SQLite library will itself serialize access
1888 ** to [database connections] and [prepared statements] so that the
1889 ** application is free to use the same [database connection] or the
1890 ** same [prepared statement] in different threads at the same time.
1891 ** ^If SQLite is compiled with
1892 ** the [SQLCIPHER_THREADSAFE | SQLCIPHER_THREADSAFE=0] compile-time option then
1893 ** it is not possible to set the Serialized [threading mode] and
1894 ** [sqlcipher3_config()] will return [SQLCIPHER_ERROR] if called with the
1895 ** SQLCIPHER_CONFIG_SERIALIZED configuration option.</dd>
1896 **
1897 ** [[SQLCIPHER_CONFIG_MALLOC]] <dt>SQLCIPHER_CONFIG_MALLOC</dt>
1898 ** <dd> ^(This option takes a single argument which is a pointer to an
1899 ** instance of the [sqlcipher3_mem_methods] structure.  The argument specifies
1900 ** alternative low-level memory allocation routines to be used in place of
1901 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1902 ** its own private copy of the content of the [sqlcipher3_mem_methods] structure
1903 ** before the [sqlcipher3_config()] call returns.</dd>
1904 **
1905 ** [[SQLCIPHER_CONFIG_GETMALLOC]] <dt>SQLCIPHER_CONFIG_GETMALLOC</dt>
1906 ** <dd> ^(This option takes a single argument which is a pointer to an
1907 ** instance of the [sqlcipher3_mem_methods] structure.  The [sqlcipher3_mem_methods]
1908 ** structure is filled with the currently defined memory allocation routines.)^
1909 ** This option can be used to overload the default memory allocation
1910 ** routines with a wrapper that simulations memory allocation failure or
1911 ** tracks memory usage, for example. </dd>
1912 **
1913 ** [[SQLCIPHER_CONFIG_MEMSTATUS]] <dt>SQLCIPHER_CONFIG_MEMSTATUS</dt>
1914 ** <dd> ^This option takes single argument of type int, interpreted as a 
1915 ** boolean, which enables or disables the collection of memory allocation 
1916 ** statistics. ^(When memory allocation statistics are disabled, the 
1917 ** following SQLite interfaces become non-operational:
1918 **   <ul>
1919 **   <li> [sqlcipher3_memory_used()]
1920 **   <li> [sqlcipher3_memory_highwater()]
1921 **   <li> [sqlcipher3_soft_heap_limit64()]
1922 **   <li> [sqlcipher3_status()]
1923 **   </ul>)^
1924 ** ^Memory allocation statistics are enabled by default unless SQLite is
1925 ** compiled with [SQLCIPHER_DEFAULT_MEMSTATUS]=0 in which case memory
1926 ** allocation statistics are disabled by default.
1927 ** </dd>
1928 **
1929 ** [[SQLCIPHER_CONFIG_SCRATCH]] <dt>SQLCIPHER_CONFIG_SCRATCH</dt>
1930 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1931 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1932 ** aligned memory buffer from which the scratch allocations will be
1933 ** drawn, the size of each scratch allocation (sz),
1934 ** and the maximum number of scratch allocations (N).  The sz
1935 ** argument must be a multiple of 16.
1936 ** The first argument must be a pointer to an 8-byte aligned buffer
1937 ** of at least sz*N bytes of memory.
1938 ** ^SQLite will use no more than two scratch buffers per thread.  So
1939 ** N should be set to twice the expected maximum number of threads.
1940 ** ^SQLite will never require a scratch buffer that is more than 6
1941 ** times the database page size. ^If SQLite needs needs additional
1942 ** scratch memory beyond what is provided by this configuration option, then 
1943 ** [sqlcipher3_malloc()] will be used to obtain the memory needed.</dd>
1944 **
1945 ** [[SQLCIPHER_CONFIG_PAGECACHE]] <dt>SQLCIPHER_CONFIG_PAGECACHE</dt>
1946 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1947 ** the database page cache with the default page cache implementation.  
1948 ** This configuration should not be used if an application-define page
1949 ** cache implementation is loaded using the SQLCIPHER_CONFIG_PCACHE option.
1950 ** There are three arguments to this option: A pointer to 8-byte aligned
1951 ** memory, the size of each page buffer (sz), and the number of pages (N).
1952 ** The sz argument should be the size of the largest database page
1953 ** (a power of two between 512 and 32768) plus a little extra for each
1954 ** page header.  ^The page header size is 20 to 40 bytes depending on
1955 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1956 ** to make sz a little too large.  The first
1957 ** argument should point to an allocation of at least sz*N bytes of memory.
1958 ** ^SQLite will use the memory provided by the first argument to satisfy its
1959 ** memory needs for the first N pages that it adds to cache.  ^If additional
1960 ** page cache memory is needed beyond what is provided by this option, then
1961 ** SQLite goes to [sqlcipher3_malloc()] for the additional storage space.
1962 ** The pointer in the first argument must
1963 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1964 ** will be undefined.</dd>
1965 **
1966 ** [[SQLCIPHER_CONFIG_HEAP]] <dt>SQLCIPHER_CONFIG_HEAP</dt>
1967 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1968 ** for all of its dynamic memory allocation needs beyond those provided
1969 ** for by [SQLCIPHER_CONFIG_SCRATCH] and [SQLCIPHER_CONFIG_PAGECACHE].
1970 ** There are three arguments: An 8-byte aligned pointer to the memory,
1971 ** the number of bytes in the memory buffer, and the minimum allocation size.
1972 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1973 ** to using its default memory allocator (the system malloc() implementation),
1974 ** undoing any prior invocation of [SQLCIPHER_CONFIG_MALLOC].  ^If the
1975 ** memory pointer is not NULL and either [SQLCIPHER_ENABLE_MEMSYS3] or
1976 ** [SQLCIPHER_ENABLE_MEMSYS5] are defined, then the alternative memory
1977 ** allocator is engaged to handle all of SQLites memory allocation needs.
1978 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1979 ** boundary or subsequent behavior of SQLite will be undefined.
1980 ** The minimum allocation size is capped at 2**12. Reasonable values
1981 ** for the minimum allocation size are 2**5 through 2**8.</dd>
1982 **
1983 ** [[SQLCIPHER_CONFIG_MUTEX]] <dt>SQLCIPHER_CONFIG_MUTEX</dt>
1984 ** <dd> ^(This option takes a single argument which is a pointer to an
1985 ** instance of the [sqlcipher3_mutex_methods] structure.  The argument specifies
1986 ** alternative low-level mutex routines to be used in place
1987 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1988 ** content of the [sqlcipher3_mutex_methods] structure before the call to
1989 ** [sqlcipher3_config()] returns. ^If SQLite is compiled with
1990 ** the [SQLCIPHER_THREADSAFE | SQLCIPHER_THREADSAFE=0] compile-time option then
1991 ** the entire mutexing subsystem is omitted from the build and hence calls to
1992 ** [sqlcipher3_config()] with the SQLCIPHER_CONFIG_MUTEX configuration option will
1993 ** return [SQLCIPHER_ERROR].</dd>
1994 **
1995 ** [[SQLCIPHER_CONFIG_GETMUTEX]] <dt>SQLCIPHER_CONFIG_GETMUTEX</dt>
1996 ** <dd> ^(This option takes a single argument which is a pointer to an
1997 ** instance of the [sqlcipher3_mutex_methods] structure.  The
1998 ** [sqlcipher3_mutex_methods]
1999 ** structure is filled with the currently defined mutex routines.)^
2000 ** This option can be used to overload the default mutex allocation
2001 ** routines with a wrapper used to track mutex usage for performance
2002 ** profiling or testing, for example.   ^If SQLite is compiled with
2003 ** the [SQLCIPHER_THREADSAFE | SQLCIPHER_THREADSAFE=0] compile-time option then
2004 ** the entire mutexing subsystem is omitted from the build and hence calls to
2005 ** [sqlcipher3_config()] with the SQLCIPHER_CONFIG_GETMUTEX configuration option will
2006 ** return [SQLCIPHER_ERROR].</dd>
2007 **
2008 ** [[SQLCIPHER_CONFIG_LOOKASIDE]] <dt>SQLCIPHER_CONFIG_LOOKASIDE</dt>
2009 ** <dd> ^(This option takes two arguments that determine the default
2010 ** memory allocation for the lookaside memory allocator on each
2011 ** [database connection].  The first argument is the
2012 ** size of each lookaside buffer slot and the second is the number of
2013 ** slots allocated to each database connection.)^  ^(This option sets the
2014 ** <i>default</i> lookaside size. The [SQLCIPHER_DBCONFIG_LOOKASIDE]
2015 ** verb to [sqlcipher3_db_config()] can be used to change the lookaside
2016 ** configuration on individual connections.)^ </dd>
2017 **
2018 ** [[SQLCIPHER_CONFIG_PCACHE]] <dt>SQLCIPHER_CONFIG_PCACHE</dt>
2019 ** <dd> ^(This option takes a single argument which is a pointer to
2020 ** an [sqlcipher3_pcache_methods] object.  This object specifies the interface
2021 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
2022 ** object and uses it for page cache memory allocations.</dd>
2023 **
2024 ** [[SQLCIPHER_CONFIG_GETPCACHE]] <dt>SQLCIPHER_CONFIG_GETPCACHE</dt>
2025 ** <dd> ^(This option takes a single argument which is a pointer to an
2026 ** [sqlcipher3_pcache_methods] object.  SQLite copies of the current
2027 ** page cache implementation into that object.)^ </dd>
2028 **
2029 ** [[SQLCIPHER_CONFIG_LOG]] <dt>SQLCIPHER_CONFIG_LOG</dt>
2030 ** <dd> ^The SQLCIPHER_CONFIG_LOG option takes two arguments: a pointer to a
2031 ** function with a call signature of void(*)(void*,int,const char*), 
2032 ** and a pointer to void. ^If the function pointer is not NULL, it is
2033 ** invoked by [sqlcipher3_log()] to process each logging event.  ^If the
2034 ** function pointer is NULL, the [sqlcipher3_log()] interface becomes a no-op.
2035 ** ^The void pointer that is the second argument to SQLCIPHER_CONFIG_LOG is
2036 ** passed through as the first parameter to the application-defined logger
2037 ** function whenever that function is invoked.  ^The second parameter to
2038 ** the logger function is a copy of the first parameter to the corresponding
2039 ** [sqlcipher3_log()] call and is intended to be a [result code] or an
2040 ** [extended result code].  ^The third parameter passed to the logger is
2041 ** log message after formatting via [sqlcipher3_snprintf()].
2042 ** The SQLite logging interface is not reentrant; the logger function
2043 ** supplied by the application must not invoke any SQLite interface.
2044 ** In a multi-threaded application, the application-defined logger
2045 ** function must be threadsafe. </dd>
2046 **
2047 ** [[SQLCIPHER_CONFIG_URI]] <dt>SQLCIPHER_CONFIG_URI
2048 ** <dd> This option takes a single argument of type int. If non-zero, then
2049 ** URI handling is globally enabled. If the parameter is zero, then URI handling
2050 ** is globally disabled. If URI handling is globally enabled, all filenames
2051 ** passed to [sqlcipher3_open()], [sqlcipher3_open_v2()], [sqlcipher3_open16()] or
2052 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2053 ** of whether or not the [SQLCIPHER_OPEN_URI] flag is set when the database
2054 ** connection is opened. If it is globally disabled, filenames are
2055 ** only interpreted as URIs if the SQLCIPHER_OPEN_URI flag is set when the
2056 ** database connection is opened. By default, URI handling is globally
2057 ** disabled. The default value may be changed by compiling with the
2058 ** [SQLCIPHER_USE_URI] symbol defined.
2059 ** </dl>
2060 */
2061 #define SQLCIPHER_CONFIG_SINGLETHREAD  1  /* nil */
2062 #define SQLCIPHER_CONFIG_MULTITHREAD   2  /* nil */
2063 #define SQLCIPHER_CONFIG_SERIALIZED    3  /* nil */
2064 #define SQLCIPHER_CONFIG_MALLOC        4  /* sqlcipher3_mem_methods* */
2065 #define SQLCIPHER_CONFIG_GETMALLOC     5  /* sqlcipher3_mem_methods* */
2066 #define SQLCIPHER_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2067 #define SQLCIPHER_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2068 #define SQLCIPHER_CONFIG_HEAP          8  /* void*, int nByte, int min */
2069 #define SQLCIPHER_CONFIG_MEMSTATUS     9  /* boolean */
2070 #define SQLCIPHER_CONFIG_MUTEX        10  /* sqlcipher3_mutex_methods* */
2071 #define SQLCIPHER_CONFIG_GETMUTEX     11  /* sqlcipher3_mutex_methods* */
2072 /* previously SQLCIPHER_CONFIG_CHUNKALLOC 12 which is now unused. */ 
2073 #define SQLCIPHER_CONFIG_LOOKASIDE    13  /* int int */
2074 #define SQLCIPHER_CONFIG_PCACHE       14  /* sqlcipher3_pcache_methods* */
2075 #define SQLCIPHER_CONFIG_GETPCACHE    15  /* sqlcipher3_pcache_methods* */
2076 #define SQLCIPHER_CONFIG_LOG          16  /* xFunc, void* */
2077 #define SQLCIPHER_CONFIG_URI          17  /* int */
2078
2079 /*
2080 ** CAPI3REF: Database Connection Configuration Options
2081 **
2082 ** These constants are the available integer configuration options that
2083 ** can be passed as the second argument to the [sqlcipher3_db_config()] interface.
2084 **
2085 ** New configuration options may be added in future releases of SQLite.
2086 ** Existing configuration options might be discontinued.  Applications
2087 ** should check the return code from [sqlcipher3_db_config()] to make sure that
2088 ** the call worked.  ^The [sqlcipher3_db_config()] interface will return a
2089 ** non-zero [error code] if a discontinued or unsupported configuration option
2090 ** is invoked.
2091 **
2092 ** <dl>
2093 ** <dt>SQLCIPHER_DBCONFIG_LOOKASIDE</dt>
2094 ** <dd> ^This option takes three additional arguments that determine the 
2095 ** [lookaside memory allocator] configuration for the [database connection].
2096 ** ^The first argument (the third parameter to [sqlcipher3_db_config()] is a
2097 ** pointer to a memory buffer to use for lookaside memory.
2098 ** ^The first argument after the SQLCIPHER_DBCONFIG_LOOKASIDE verb
2099 ** may be NULL in which case SQLite will allocate the
2100 ** lookaside buffer itself using [sqlcipher3_malloc()]. ^The second argument is the
2101 ** size of each lookaside buffer slot.  ^The third argument is the number of
2102 ** slots.  The size of the buffer in the first argument must be greater than
2103 ** or equal to the product of the second and third arguments.  The buffer
2104 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2105 ** SQLCIPHER_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2106 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2107 ** configuration for a database connection can only be changed when that
2108 ** connection is not currently using lookaside memory, or in other words
2109 ** when the "current value" returned by
2110 ** [sqlcipher3_db_status](D,[SQLCIPHER_CONFIG_LOOKASIDE],...) is zero.
2111 ** Any attempt to change the lookaside memory configuration when lookaside
2112 ** memory is in use leaves the configuration unchanged and returns 
2113 ** [SQLCIPHER_BUSY].)^</dd>
2114 **
2115 ** <dt>SQLCIPHER_DBCONFIG_ENABLE_FKEY</dt>
2116 ** <dd> ^This option is used to enable or disable the enforcement of
2117 ** [foreign key constraints].  There should be two additional arguments.
2118 ** The first argument is an integer which is 0 to disable FK enforcement,
2119 ** positive to enable FK enforcement or negative to leave FK enforcement
2120 ** unchanged.  The second parameter is a pointer to an integer into which
2121 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2122 ** following this call.  The second parameter may be a NULL pointer, in
2123 ** which case the FK enforcement setting is not reported back. </dd>
2124 **
2125 ** <dt>SQLCIPHER_DBCONFIG_ENABLE_TRIGGER</dt>
2126 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2127 ** There should be two additional arguments.
2128 ** The first argument is an integer which is 0 to disable triggers,
2129 ** positive to enable triggers or negative to leave the setting unchanged.
2130 ** The second parameter is a pointer to an integer into which
2131 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2132 ** following this call.  The second parameter may be a NULL pointer, in
2133 ** which case the trigger setting is not reported back. </dd>
2134 **
2135 ** </dl>
2136 */
2137 #define SQLCIPHER_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2138 #define SQLCIPHER_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2139 #define SQLCIPHER_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2140
2141
2142 /*
2143 ** CAPI3REF: Enable Or Disable Extended Result Codes
2144 **
2145 ** ^The sqlcipher3_extended_result_codes() routine enables or disables the
2146 ** [extended result codes] feature of SQLite. ^The extended result
2147 ** codes are disabled by default for historical compatibility.
2148 */
2149 SQLCIPHER_API int sqlcipher3_extended_result_codes(sqlcipher3*, int onoff);
2150
2151 /*
2152 ** CAPI3REF: Last Insert Rowid
2153 **
2154 ** ^Each entry in an SQLite table has a unique 64-bit signed
2155 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2156 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2157 ** names are not also used by explicitly declared columns. ^If
2158 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2159 ** is another alias for the rowid.
2160 **
2161 ** ^This routine returns the [rowid] of the most recent
2162 ** successful [INSERT] into the database from the [database connection]
2163 ** in the first argument.  ^As of SQLite version 3.7.7, this routines
2164 ** records the last insert rowid of both ordinary tables and [virtual tables].
2165 ** ^If no successful [INSERT]s
2166 ** have ever occurred on that database connection, zero is returned.
2167 **
2168 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2169 ** method, then this routine will return the [rowid] of the inserted
2170 ** row as long as the trigger or virtual table method is running.
2171 ** But once the trigger or virtual table method ends, the value returned 
2172 ** by this routine reverts to what it was before the trigger or virtual
2173 ** table method began.)^
2174 **
2175 ** ^An [INSERT] that fails due to a constraint violation is not a
2176 ** successful [INSERT] and does not change the value returned by this
2177 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2178 ** and INSERT OR ABORT make no changes to the return value of this
2179 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2180 ** encounters a constraint violation, it does not fail.  The
2181 ** INSERT continues to completion after deleting rows that caused
2182 ** the constraint problem so INSERT OR REPLACE will always change
2183 ** the return value of this interface.)^
2184 **
2185 ** ^For the purposes of this routine, an [INSERT] is considered to
2186 ** be successful even if it is subsequently rolled back.
2187 **
2188 ** This function is accessible to SQL statements via the
2189 ** [last_insert_rowid() SQL function].
2190 **
2191 ** If a separate thread performs a new [INSERT] on the same
2192 ** database connection while the [sqlcipher3_last_insert_rowid()]
2193 ** function is running and thus changes the last insert [rowid],
2194 ** then the value returned by [sqlcipher3_last_insert_rowid()] is
2195 ** unpredictable and might not equal either the old or the new
2196 ** last insert [rowid].
2197 */
2198 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_last_insert_rowid(sqlcipher3*);
2199
2200 /*
2201 ** CAPI3REF: Count The Number Of Rows Modified
2202 **
2203 ** ^This function returns the number of database rows that were changed
2204 ** or inserted or deleted by the most recently completed SQL statement
2205 ** on the [database connection] specified by the first parameter.
2206 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2207 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2208 ** triggers or [foreign key actions] are not counted.)^ Use the
2209 ** [sqlcipher3_total_changes()] function to find the total number of changes
2210 ** including changes caused by triggers and foreign key actions.
2211 **
2212 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2213 ** are not counted.  Only real table changes are counted.
2214 **
2215 ** ^(A "row change" is a change to a single row of a single table
2216 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2217 ** are changed as side effects of [REPLACE] constraint resolution,
2218 ** rollback, ABORT processing, [DROP TABLE], or by any other
2219 ** mechanisms do not count as direct row changes.)^
2220 **
2221 ** A "trigger context" is a scope of execution that begins and
2222 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2223 ** Most SQL statements are
2224 ** evaluated outside of any trigger.  This is the "top level"
2225 ** trigger context.  If a trigger fires from the top level, a
2226 ** new trigger context is entered for the duration of that one
2227 ** trigger.  Subtriggers create subcontexts for their duration.
2228 **
2229 ** ^Calling [sqlcipher3_exec()] or [sqlcipher3_step()] recursively does
2230 ** not create a new trigger context.
2231 **
2232 ** ^This function returns the number of direct row changes in the
2233 ** most recent INSERT, UPDATE, or DELETE statement within the same
2234 ** trigger context.
2235 **
2236 ** ^Thus, when called from the top level, this function returns the
2237 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2238 ** that also occurred at the top level.  ^(Within the body of a trigger,
2239 ** the sqlcipher3_changes() interface can be called to find the number of
2240 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2241 ** statement within the body of the same trigger.
2242 ** However, the number returned does not include changes
2243 ** caused by subtriggers since those have their own context.)^
2244 **
2245 ** See also the [sqlcipher3_total_changes()] interface, the
2246 ** [count_changes pragma], and the [changes() SQL function].
2247 **
2248 ** If a separate thread makes changes on the same database connection
2249 ** while [sqlcipher3_changes()] is running then the value returned
2250 ** is unpredictable and not meaningful.
2251 */
2252 SQLCIPHER_API int sqlcipher3_changes(sqlcipher3*);
2253
2254 /*
2255 ** CAPI3REF: Total Number Of Rows Modified
2256 **
2257 ** ^This function returns the number of row changes caused by [INSERT],
2258 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2259 ** ^(The count returned by sqlcipher3_total_changes() includes all changes
2260 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2261 ** [foreign key actions]. However,
2262 ** the count does not include changes used to implement [REPLACE] constraints,
2263 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2264 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2265 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2266 ** are counted.)^
2267 ** ^The sqlcipher3_total_changes() function counts the changes as soon as
2268 ** the statement that makes them is completed (when the statement handle
2269 ** is passed to [sqlcipher3_reset()] or [sqlcipher3_finalize()]).
2270 **
2271 ** See also the [sqlcipher3_changes()] interface, the
2272 ** [count_changes pragma], and the [total_changes() SQL function].
2273 **
2274 ** If a separate thread makes changes on the same database connection
2275 ** while [sqlcipher3_total_changes()] is running then the value
2276 ** returned is unpredictable and not meaningful.
2277 */
2278 SQLCIPHER_API int sqlcipher3_total_changes(sqlcipher3*);
2279
2280 /*
2281 ** CAPI3REF: Interrupt A Long-Running Query
2282 **
2283 ** ^This function causes any pending database operation to abort and
2284 ** return at its earliest opportunity. This routine is typically
2285 ** called in response to a user action such as pressing "Cancel"
2286 ** or Ctrl-C where the user wants a long query operation to halt
2287 ** immediately.
2288 **
2289 ** ^It is safe to call this routine from a thread different from the
2290 ** thread that is currently running the database operation.  But it
2291 ** is not safe to call this routine with a [database connection] that
2292 ** is closed or might close before sqlcipher3_interrupt() returns.
2293 **
2294 ** ^If an SQL operation is very nearly finished at the time when
2295 ** sqlcipher3_interrupt() is called, then it might not have an opportunity
2296 ** to be interrupted and might continue to completion.
2297 **
2298 ** ^An SQL operation that is interrupted will return [SQLCIPHER_INTERRUPT].
2299 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2300 ** that is inside an explicit transaction, then the entire transaction
2301 ** will be rolled back automatically.
2302 **
2303 ** ^The sqlcipher3_interrupt(D) call is in effect until all currently running
2304 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2305 ** that are started after the sqlcipher3_interrupt() call and before the 
2306 ** running statements reaches zero are interrupted as if they had been
2307 ** running prior to the sqlcipher3_interrupt() call.  ^New SQL statements
2308 ** that are started after the running statement count reaches zero are
2309 ** not effected by the sqlcipher3_interrupt().
2310 ** ^A call to sqlcipher3_interrupt(D) that occurs when there are no running
2311 ** SQL statements is a no-op and has no effect on SQL statements
2312 ** that are started after the sqlcipher3_interrupt() call returns.
2313 **
2314 ** If the database connection closes while [sqlcipher3_interrupt()]
2315 ** is running then bad things will likely happen.
2316 */
2317 SQLCIPHER_API void sqlcipher3_interrupt(sqlcipher3*);
2318
2319 /*
2320 ** CAPI3REF: Determine If An SQL Statement Is Complete
2321 **
2322 ** These routines are useful during command-line input to determine if the
2323 ** currently entered text seems to form a complete SQL statement or
2324 ** if additional input is needed before sending the text into
2325 ** SQLite for parsing.  ^These routines return 1 if the input string
2326 ** appears to be a complete SQL statement.  ^A statement is judged to be
2327 ** complete if it ends with a semicolon token and is not a prefix of a
2328 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2329 ** string literals or quoted identifier names or comments are not
2330 ** independent tokens (they are part of the token in which they are
2331 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2332 ** and comments that follow the final semicolon are ignored.
2333 **
2334 ** ^These routines return 0 if the statement is incomplete.  ^If a
2335 ** memory allocation fails, then SQLCIPHER_NOMEM is returned.
2336 **
2337 ** ^These routines do not parse the SQL statements thus
2338 ** will not detect syntactically incorrect SQL.
2339 **
2340 ** ^(If SQLite has not been initialized using [sqlcipher3_initialize()] prior 
2341 ** to invoking sqlcipher3_complete16() then sqlcipher3_initialize() is invoked
2342 ** automatically by sqlcipher3_complete16().  If that initialization fails,
2343 ** then the return value from sqlcipher3_complete16() will be non-zero
2344 ** regardless of whether or not the input SQL is complete.)^
2345 **
2346 ** The input to [sqlcipher3_complete()] must be a zero-terminated
2347 ** UTF-8 string.
2348 **
2349 ** The input to [sqlcipher3_complete16()] must be a zero-terminated
2350 ** UTF-16 string in native byte order.
2351 */
2352 SQLCIPHER_API int sqlcipher3_complete(const char *sql);
2353 SQLCIPHER_API int sqlcipher3_complete16(const void *sql);
2354
2355 /*
2356 ** CAPI3REF: Register A Callback To Handle SQLCIPHER_BUSY Errors
2357 **
2358 ** ^This routine sets a callback function that might be invoked whenever
2359 ** an attempt is made to open a database table that another thread
2360 ** or process has locked.
2361 **
2362 ** ^If the busy callback is NULL, then [SQLCIPHER_BUSY] or [SQLCIPHER_IOERR_BLOCKED]
2363 ** is returned immediately upon encountering the lock.  ^If the busy callback
2364 ** is not NULL, then the callback might be invoked with two arguments.
2365 **
2366 ** ^The first argument to the busy handler is a copy of the void* pointer which
2367 ** is the third argument to sqlcipher3_busy_handler().  ^The second argument to
2368 ** the busy handler callback is the number of times that the busy handler has
2369 ** been invoked for this locking event.  ^If the
2370 ** busy callback returns 0, then no additional attempts are made to
2371 ** access the database and [SQLCIPHER_BUSY] or [SQLCIPHER_IOERR_BLOCKED] is returned.
2372 ** ^If the callback returns non-zero, then another attempt
2373 ** is made to open the database for reading and the cycle repeats.
2374 **
2375 ** The presence of a busy handler does not guarantee that it will be invoked
2376 ** when there is lock contention. ^If SQLite determines that invoking the busy
2377 ** handler could result in a deadlock, it will go ahead and return [SQLCIPHER_BUSY]
2378 ** or [SQLCIPHER_IOERR_BLOCKED] instead of invoking the busy handler.
2379 ** Consider a scenario where one process is holding a read lock that
2380 ** it is trying to promote to a reserved lock and
2381 ** a second process is holding a reserved lock that it is trying
2382 ** to promote to an exclusive lock.  The first process cannot proceed
2383 ** because it is blocked by the second and the second process cannot
2384 ** proceed because it is blocked by the first.  If both processes
2385 ** invoke the busy handlers, neither will make any progress.  Therefore,
2386 ** SQLite returns [SQLCIPHER_BUSY] for the first process, hoping that this
2387 ** will induce the first process to release its read lock and allow
2388 ** the second process to proceed.
2389 **
2390 ** ^The default busy callback is NULL.
2391 **
2392 ** ^The [SQLCIPHER_BUSY] error is converted to [SQLCIPHER_IOERR_BLOCKED]
2393 ** when SQLite is in the middle of a large transaction where all the
2394 ** changes will not fit into the in-memory cache.  SQLite will
2395 ** already hold a RESERVED lock on the database file, but it needs
2396 ** to promote this lock to EXCLUSIVE so that it can spill cache
2397 ** pages into the database file without harm to concurrent
2398 ** readers.  ^If it is unable to promote the lock, then the in-memory
2399 ** cache will be left in an inconsistent state and so the error
2400 ** code is promoted from the relatively benign [SQLCIPHER_BUSY] to
2401 ** the more severe [SQLCIPHER_IOERR_BLOCKED].  ^This error code promotion
2402 ** forces an automatic rollback of the changes.  See the
2403 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2404 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2405 ** this is important.
2406 **
2407 ** ^(There can only be a single busy handler defined for each
2408 ** [database connection].  Setting a new busy handler clears any
2409 ** previously set handler.)^  ^Note that calling [sqlcipher3_busy_timeout()]
2410 ** will also set or clear the busy handler.
2411 **
2412 ** The busy callback should not take any actions which modify the
2413 ** database connection that invoked the busy handler.  Any such actions
2414 ** result in undefined behavior.
2415 ** 
2416 ** A busy handler must not close the database connection
2417 ** or [prepared statement] that invoked the busy handler.
2418 */
2419 SQLCIPHER_API int sqlcipher3_busy_handler(sqlcipher3*, int(*)(void*,int), void*);
2420
2421 /*
2422 ** CAPI3REF: Set A Busy Timeout
2423 **
2424 ** ^This routine sets a [sqlcipher3_busy_handler | busy handler] that sleeps
2425 ** for a specified amount of time when a table is locked.  ^The handler
2426 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2427 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2428 ** the handler returns 0 which causes [sqlcipher3_step()] to return
2429 ** [SQLCIPHER_BUSY] or [SQLCIPHER_IOERR_BLOCKED].
2430 **
2431 ** ^Calling this routine with an argument less than or equal to zero
2432 ** turns off all busy handlers.
2433 **
2434 ** ^(There can only be a single busy handler for a particular
2435 ** [database connection] any any given moment.  If another busy handler
2436 ** was defined  (using [sqlcipher3_busy_handler()]) prior to calling
2437 ** this routine, that other busy handler is cleared.)^
2438 */
2439 SQLCIPHER_API int sqlcipher3_busy_timeout(sqlcipher3*, int ms);
2440
2441 /*
2442 ** CAPI3REF: Convenience Routines For Running Queries
2443 **
2444 ** This is a legacy interface that is preserved for backwards compatibility.
2445 ** Use of this interface is not recommended.
2446 **
2447 ** Definition: A <b>result table</b> is memory data structure created by the
2448 ** [sqlcipher3_get_table()] interface.  A result table records the
2449 ** complete query results from one or more queries.
2450 **
2451 ** The table conceptually has a number of rows and columns.  But
2452 ** these numbers are not part of the result table itself.  These
2453 ** numbers are obtained separately.  Let N be the number of rows
2454 ** and M be the number of columns.
2455 **
2456 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2457 ** There are (N+1)*M elements in the array.  The first M pointers point
2458 ** to zero-terminated strings that  contain the names of the columns.
2459 ** The remaining entries all point to query results.  NULL values result
2460 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2461 ** string representation as returned by [sqlcipher3_column_text()].
2462 **
2463 ** A result table might consist of one or more memory allocations.
2464 ** It is not safe to pass a result table directly to [sqlcipher3_free()].
2465 ** A result table should be deallocated using [sqlcipher3_free_table()].
2466 **
2467 ** ^(As an example of the result table format, suppose a query result
2468 ** is as follows:
2469 **
2470 ** <blockquote><pre>
2471 **        Name        | Age
2472 **        -----------------------
2473 **        Alice       | 43
2474 **        Bob         | 28
2475 **        Cindy       | 21
2476 ** </pre></blockquote>
2477 **
2478 ** There are two column (M==2) and three rows (N==3).  Thus the
2479 ** result table has 8 entries.  Suppose the result table is stored
2480 ** in an array names azResult.  Then azResult holds this content:
2481 **
2482 ** <blockquote><pre>
2483 **        azResult&#91;0] = "Name";
2484 **        azResult&#91;1] = "Age";
2485 **        azResult&#91;2] = "Alice";
2486 **        azResult&#91;3] = "43";
2487 **        azResult&#91;4] = "Bob";
2488 **        azResult&#91;5] = "28";
2489 **        azResult&#91;6] = "Cindy";
2490 **        azResult&#91;7] = "21";
2491 ** </pre></blockquote>)^
2492 **
2493 ** ^The sqlcipher3_get_table() function evaluates one or more
2494 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2495 ** string of its 2nd parameter and returns a result table to the
2496 ** pointer given in its 3rd parameter.
2497 **
2498 ** After the application has finished with the result from sqlcipher3_get_table(),
2499 ** it must pass the result table pointer to sqlcipher3_free_table() in order to
2500 ** release the memory that was malloced.  Because of the way the
2501 ** [sqlcipher3_malloc()] happens within sqlcipher3_get_table(), the calling
2502 ** function must not try to call [sqlcipher3_free()] directly.  Only
2503 ** [sqlcipher3_free_table()] is able to release the memory properly and safely.
2504 **
2505 ** The sqlcipher3_get_table() interface is implemented as a wrapper around
2506 ** [sqlcipher3_exec()].  The sqlcipher3_get_table() routine does not have access
2507 ** to any internal data structures of SQLite.  It uses only the public
2508 ** interface defined here.  As a consequence, errors that occur in the
2509 ** wrapper layer outside of the internal [sqlcipher3_exec()] call are not
2510 ** reflected in subsequent calls to [sqlcipher3_errcode()] or
2511 ** [sqlcipher3_errmsg()].
2512 */
2513 SQLCIPHER_API int sqlcipher3_get_table(
2514   sqlcipher3 *db,          /* An open database */
2515   const char *zSql,     /* SQL to be evaluated */
2516   char ***pazResult,    /* Results of the query */
2517   int *pnRow,           /* Number of result rows written here */
2518   int *pnColumn,        /* Number of result columns written here */
2519   char **pzErrmsg       /* Error msg written here */
2520 );
2521 SQLCIPHER_API void sqlcipher3_free_table(char **result);
2522
2523 /*
2524 ** CAPI3REF: Formatted String Printing Functions
2525 **
2526 ** These routines are work-alikes of the "printf()" family of functions
2527 ** from the standard C library.
2528 **
2529 ** ^The sqlcipher3_mprintf() and sqlcipher3_vmprintf() routines write their
2530 ** results into memory obtained from [sqlcipher3_malloc()].
2531 ** The strings returned by these two routines should be
2532 ** released by [sqlcipher3_free()].  ^Both routines return a
2533 ** NULL pointer if [sqlcipher3_malloc()] is unable to allocate enough
2534 ** memory to hold the resulting string.
2535 **
2536 ** ^(The sqlcipher3_snprintf() routine is similar to "snprintf()" from
2537 ** the standard C library.  The result is written into the
2538 ** buffer supplied as the second parameter whose size is given by
2539 ** the first parameter. Note that the order of the
2540 ** first two parameters is reversed from snprintf().)^  This is an
2541 ** historical accident that cannot be fixed without breaking
2542 ** backwards compatibility.  ^(Note also that sqlcipher3_snprintf()
2543 ** returns a pointer to its buffer instead of the number of
2544 ** characters actually written into the buffer.)^  We admit that
2545 ** the number of characters written would be a more useful return
2546 ** value but we cannot change the implementation of sqlcipher3_snprintf()
2547 ** now without breaking compatibility.
2548 **
2549 ** ^As long as the buffer size is greater than zero, sqlcipher3_snprintf()
2550 ** guarantees that the buffer is always zero-terminated.  ^The first
2551 ** parameter "n" is the total size of the buffer, including space for
2552 ** the zero terminator.  So the longest string that can be completely
2553 ** written will be n-1 characters.
2554 **
2555 ** ^The sqlcipher3_vsnprintf() routine is a varargs version of sqlcipher3_snprintf().
2556 **
2557 ** These routines all implement some additional formatting
2558 ** options that are useful for constructing SQL statements.
2559 ** All of the usual printf() formatting options apply.  In addition, there
2560 ** is are "%q", "%Q", and "%z" options.
2561 **
2562 ** ^(The %q option works like %s in that it substitutes a null-terminated
2563 ** string from the argument list.  But %q also doubles every '\'' character.
2564 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2565 ** character it escapes that character and allows it to be inserted into
2566 ** the string.
2567 **
2568 ** For example, assume the string variable zText contains text as follows:
2569 **
2570 ** <blockquote><pre>
2571 **  char *zText = "It's a happy day!";
2572 ** </pre></blockquote>
2573 **
2574 ** One can use this text in an SQL statement as follows:
2575 **
2576 ** <blockquote><pre>
2577 **  char *zSQL = sqlcipher3_mprintf("INSERT INTO table VALUES('%q')", zText);
2578 **  sqlcipher3_exec(db, zSQL, 0, 0, 0);
2579 **  sqlcipher3_free(zSQL);
2580 ** </pre></blockquote>
2581 **
2582 ** Because the %q format string is used, the '\'' character in zText
2583 ** is escaped and the SQL generated is as follows:
2584 **
2585 ** <blockquote><pre>
2586 **  INSERT INTO table1 VALUES('It''s a happy day!')
2587 ** </pre></blockquote>
2588 **
2589 ** This is correct.  Had we used %s instead of %q, the generated SQL
2590 ** would have looked like this:
2591 **
2592 ** <blockquote><pre>
2593 **  INSERT INTO table1 VALUES('It's a happy day!');
2594 ** </pre></blockquote>
2595 **
2596 ** This second example is an SQL syntax error.  As a general rule you should
2597 ** always use %q instead of %s when inserting text into a string literal.
2598 **
2599 ** ^(The %Q option works like %q except it also adds single quotes around
2600 ** the outside of the total string.  Additionally, if the parameter in the
2601 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2602 ** single quotes).)^  So, for example, one could say:
2603 **
2604 ** <blockquote><pre>
2605 **  char *zSQL = sqlcipher3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2606 **  sqlcipher3_exec(db, zSQL, 0, 0, 0);
2607 **  sqlcipher3_free(zSQL);
2608 ** </pre></blockquote>
2609 **
2610 ** The code above will render a correct SQL statement in the zSQL
2611 ** variable even if the zText variable is a NULL pointer.
2612 **
2613 ** ^(The "%z" formatting option works like "%s" but with the
2614 ** addition that after the string has been read and copied into
2615 ** the result, [sqlcipher3_free()] is called on the input string.)^
2616 */
2617 SQLCIPHER_API char *sqlcipher3_mprintf(const char*,...);
2618 SQLCIPHER_API char *sqlcipher3_vmprintf(const char*, va_list);
2619 SQLCIPHER_API char *sqlcipher3_snprintf(int,char*,const char*, ...);
2620 SQLCIPHER_API char *sqlcipher3_vsnprintf(int,char*,const char*, va_list);
2621
2622 /*
2623 ** CAPI3REF: Memory Allocation Subsystem
2624 **
2625 ** The SQLite core uses these three routines for all of its own
2626 ** internal memory allocation needs. "Core" in the previous sentence
2627 ** does not include operating-system specific VFS implementation.  The
2628 ** Windows VFS uses native malloc() and free() for some operations.
2629 **
2630 ** ^The sqlcipher3_malloc() routine returns a pointer to a block
2631 ** of memory at least N bytes in length, where N is the parameter.
2632 ** ^If sqlcipher3_malloc() is unable to obtain sufficient free
2633 ** memory, it returns a NULL pointer.  ^If the parameter N to
2634 ** sqlcipher3_malloc() is zero or negative then sqlcipher3_malloc() returns
2635 ** a NULL pointer.
2636 **
2637 ** ^Calling sqlcipher3_free() with a pointer previously returned
2638 ** by sqlcipher3_malloc() or sqlcipher3_realloc() releases that memory so
2639 ** that it might be reused.  ^The sqlcipher3_free() routine is
2640 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2641 ** to sqlcipher3_free() is harmless.  After being freed, memory
2642 ** should neither be read nor written.  Even reading previously freed
2643 ** memory might result in a segmentation fault or other severe error.
2644 ** Memory corruption, a segmentation fault, or other severe error
2645 ** might result if sqlcipher3_free() is called with a non-NULL pointer that
2646 ** was not obtained from sqlcipher3_malloc() or sqlcipher3_realloc().
2647 **
2648 ** ^(The sqlcipher3_realloc() interface attempts to resize a
2649 ** prior memory allocation to be at least N bytes, where N is the
2650 ** second parameter.  The memory allocation to be resized is the first
2651 ** parameter.)^ ^ If the first parameter to sqlcipher3_realloc()
2652 ** is a NULL pointer then its behavior is identical to calling
2653 ** sqlcipher3_malloc(N) where N is the second parameter to sqlcipher3_realloc().
2654 ** ^If the second parameter to sqlcipher3_realloc() is zero or
2655 ** negative then the behavior is exactly the same as calling
2656 ** sqlcipher3_free(P) where P is the first parameter to sqlcipher3_realloc().
2657 ** ^sqlcipher3_realloc() returns a pointer to a memory allocation
2658 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2659 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2660 ** of the prior allocation are copied into the beginning of buffer returned
2661 ** by sqlcipher3_realloc() and the prior allocation is freed.
2662 ** ^If sqlcipher3_realloc() returns NULL, then the prior allocation
2663 ** is not freed.
2664 **
2665 ** ^The memory returned by sqlcipher3_malloc() and sqlcipher3_realloc()
2666 ** is always aligned to at least an 8 byte boundary, or to a
2667 ** 4 byte boundary if the [SQLCIPHER_4_BYTE_ALIGNED_MALLOC] compile-time
2668 ** option is used.
2669 **
2670 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2671 ** the SQLCIPHER_OMIT_MEMORY_ALLOCATION which would cause the built-in
2672 ** implementation of these routines to be omitted.  That capability
2673 ** is no longer provided.  Only built-in memory allocators can be used.
2674 **
2675 ** The Windows OS interface layer calls
2676 ** the system malloc() and free() directly when converting
2677 ** filenames between the UTF-8 encoding used by SQLite
2678 ** and whatever filename encoding is used by the particular Windows
2679 ** installation.  Memory allocation errors are detected, but
2680 ** they are reported back as [SQLCIPHER_CANTOPEN] or
2681 ** [SQLCIPHER_IOERR] rather than [SQLCIPHER_NOMEM].
2682 **
2683 ** The pointer arguments to [sqlcipher3_free()] and [sqlcipher3_realloc()]
2684 ** must be either NULL or else pointers obtained from a prior
2685 ** invocation of [sqlcipher3_malloc()] or [sqlcipher3_realloc()] that have
2686 ** not yet been released.
2687 **
2688 ** The application must not read or write any part of
2689 ** a block of memory after it has been released using
2690 ** [sqlcipher3_free()] or [sqlcipher3_realloc()].
2691 */
2692 SQLCIPHER_API void *sqlcipher3_malloc(int);
2693 SQLCIPHER_API void *sqlcipher3_realloc(void*, int);
2694 SQLCIPHER_API void sqlcipher3_free(void*);
2695
2696 /*
2697 ** CAPI3REF: Memory Allocator Statistics
2698 **
2699 ** SQLite provides these two interfaces for reporting on the status
2700 ** of the [sqlcipher3_malloc()], [sqlcipher3_free()], and [sqlcipher3_realloc()]
2701 ** routines, which form the built-in memory allocation subsystem.
2702 **
2703 ** ^The [sqlcipher3_memory_used()] routine returns the number of bytes
2704 ** of memory currently outstanding (malloced but not freed).
2705 ** ^The [sqlcipher3_memory_highwater()] routine returns the maximum
2706 ** value of [sqlcipher3_memory_used()] since the high-water mark
2707 ** was last reset.  ^The values returned by [sqlcipher3_memory_used()] and
2708 ** [sqlcipher3_memory_highwater()] include any overhead
2709 ** added by SQLite in its implementation of [sqlcipher3_malloc()],
2710 ** but not overhead added by the any underlying system library
2711 ** routines that [sqlcipher3_malloc()] may call.
2712 **
2713 ** ^The memory high-water mark is reset to the current value of
2714 ** [sqlcipher3_memory_used()] if and only if the parameter to
2715 ** [sqlcipher3_memory_highwater()] is true.  ^The value returned
2716 ** by [sqlcipher3_memory_highwater(1)] is the high-water mark
2717 ** prior to the reset.
2718 */
2719 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_memory_used(void);
2720 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_memory_highwater(int resetFlag);
2721
2722 /*
2723 ** CAPI3REF: Pseudo-Random Number Generator
2724 **
2725 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2726 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2727 ** already uses the largest possible [ROWID].  The PRNG is also used for
2728 ** the build-in random() and randomblob() SQL functions.  This interface allows
2729 ** applications to access the same PRNG for other purposes.
2730 **
2731 ** ^A call to this routine stores N bytes of randomness into buffer P.
2732 **
2733 ** ^The first time this routine is invoked (either internally or by
2734 ** the application) the PRNG is seeded using randomness obtained
2735 ** from the xRandomness method of the default [sqlcipher3_vfs] object.
2736 ** ^On all subsequent invocations, the pseudo-randomness is generated
2737 ** internally and without recourse to the [sqlcipher3_vfs] xRandomness
2738 ** method.
2739 */
2740 SQLCIPHER_API void sqlcipher3_randomness(int N, void *P);
2741
2742 /*
2743 ** CAPI3REF: Compile-Time Authorization Callbacks
2744 **
2745 ** ^This routine registers an authorizer callback with a particular
2746 ** [database connection], supplied in the first argument.
2747 ** ^The authorizer callback is invoked as SQL statements are being compiled
2748 ** by [sqlcipher3_prepare()] or its variants [sqlcipher3_prepare_v2()],
2749 ** [sqlcipher3_prepare16()] and [sqlcipher3_prepare16_v2()].  ^At various
2750 ** points during the compilation process, as logic is being created
2751 ** to perform various actions, the authorizer callback is invoked to
2752 ** see if those actions are allowed.  ^The authorizer callback should
2753 ** return [SQLCIPHER_OK] to allow the action, [SQLCIPHER_IGNORE] to disallow the
2754 ** specific action but allow the SQL statement to continue to be
2755 ** compiled, or [SQLCIPHER_DENY] to cause the entire SQL statement to be
2756 ** rejected with an error.  ^If the authorizer callback returns
2757 ** any value other than [SQLCIPHER_IGNORE], [SQLCIPHER_OK], or [SQLCIPHER_DENY]
2758 ** then the [sqlcipher3_prepare_v2()] or equivalent call that triggered
2759 ** the authorizer will fail with an error message.
2760 **
2761 ** When the callback returns [SQLCIPHER_OK], that means the operation
2762 ** requested is ok.  ^When the callback returns [SQLCIPHER_DENY], the
2763 ** [sqlcipher3_prepare_v2()] or equivalent call that triggered the
2764 ** authorizer will fail with an error message explaining that
2765 ** access is denied. 
2766 **
2767 ** ^The first parameter to the authorizer callback is a copy of the third
2768 ** parameter to the sqlcipher3_set_authorizer() interface. ^The second parameter
2769 ** to the callback is an integer [SQLCIPHER_COPY | action code] that specifies
2770 ** the particular action to be authorized. ^The third through sixth parameters
2771 ** to the callback are zero-terminated strings that contain additional
2772 ** details about the action to be authorized.
2773 **
2774 ** ^If the action code is [SQLCIPHER_READ]
2775 ** and the callback returns [SQLCIPHER_IGNORE] then the
2776 ** [prepared statement] statement is constructed to substitute
2777 ** a NULL value in place of the table column that would have
2778 ** been read if [SQLCIPHER_OK] had been returned.  The [SQLCIPHER_IGNORE]
2779 ** return can be used to deny an untrusted user access to individual
2780 ** columns of a table.
2781 ** ^If the action code is [SQLCIPHER_DELETE] and the callback returns
2782 ** [SQLCIPHER_IGNORE] then the [DELETE] operation proceeds but the
2783 ** [truncate optimization] is disabled and all rows are deleted individually.
2784 **
2785 ** An authorizer is used when [sqlcipher3_prepare | preparing]
2786 ** SQL statements from an untrusted source, to ensure that the SQL statements
2787 ** do not try to access data they are not allowed to see, or that they do not
2788 ** try to execute malicious statements that damage the database.  For
2789 ** example, an application may allow a user to enter arbitrary
2790 ** SQL queries for evaluation by a database.  But the application does
2791 ** not want the user to be able to make arbitrary changes to the
2792 ** database.  An authorizer could then be put in place while the
2793 ** user-entered SQL is being [sqlcipher3_prepare | prepared] that
2794 ** disallows everything except [SELECT] statements.
2795 **
2796 ** Applications that need to process SQL from untrusted sources
2797 ** might also consider lowering resource limits using [sqlcipher3_limit()]
2798 ** and limiting database size using the [max_page_count] [PRAGMA]
2799 ** in addition to using an authorizer.
2800 **
2801 ** ^(Only a single authorizer can be in place on a database connection
2802 ** at a time.  Each call to sqlcipher3_set_authorizer overrides the
2803 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2804 ** The authorizer is disabled by default.
2805 **
2806 ** The authorizer callback must not do anything that will modify
2807 ** the database connection that invoked the authorizer callback.
2808 ** Note that [sqlcipher3_prepare_v2()] and [sqlcipher3_step()] both modify their
2809 ** database connections for the meaning of "modify" in this paragraph.
2810 **
2811 ** ^When [sqlcipher3_prepare_v2()] is used to prepare a statement, the
2812 ** statement might be re-prepared during [sqlcipher3_step()] due to a 
2813 ** schema change.  Hence, the application should ensure that the
2814 ** correct authorizer callback remains in place during the [sqlcipher3_step()].
2815 **
2816 ** ^Note that the authorizer callback is invoked only during
2817 ** [sqlcipher3_prepare()] or its variants.  Authorization is not
2818 ** performed during statement evaluation in [sqlcipher3_step()], unless
2819 ** as stated in the previous paragraph, sqlcipher3_step() invokes
2820 ** sqlcipher3_prepare_v2() to reprepare a statement after a schema change.
2821 */
2822 SQLCIPHER_API int sqlcipher3_set_authorizer(
2823   sqlcipher3*,
2824   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2825   void *pUserData
2826 );
2827
2828 /*
2829 ** CAPI3REF: Authorizer Return Codes
2830 **
2831 ** The [sqlcipher3_set_authorizer | authorizer callback function] must
2832 ** return either [SQLCIPHER_OK] or one of these two constants in order
2833 ** to signal SQLite whether or not the action is permitted.  See the
2834 ** [sqlcipher3_set_authorizer | authorizer documentation] for additional
2835 ** information.
2836 **
2837 ** Note that SQLCIPHER_IGNORE is also used as a [SQLCIPHER_ROLLBACK | return code]
2838 ** from the [sqlcipher3_vtab_on_conflict()] interface.
2839 */
2840 #define SQLCIPHER_DENY   1   /* Abort the SQL statement with an error */
2841 #define SQLCIPHER_IGNORE 2   /* Don't allow access, but don't generate an error */
2842
2843 /*
2844 ** CAPI3REF: Authorizer Action Codes
2845 **
2846 ** The [sqlcipher3_set_authorizer()] interface registers a callback function
2847 ** that is invoked to authorize certain SQL statement actions.  The
2848 ** second parameter to the callback is an integer code that specifies
2849 ** what action is being authorized.  These are the integer action codes that
2850 ** the authorizer callback may be passed.
2851 **
2852 ** These action code values signify what kind of operation is to be
2853 ** authorized.  The 3rd and 4th parameters to the authorization
2854 ** callback function will be parameters or NULL depending on which of these
2855 ** codes is used as the second parameter.  ^(The 5th parameter to the
2856 ** authorizer callback is the name of the database ("main", "temp",
2857 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2858 ** is the name of the inner-most trigger or view that is responsible for
2859 ** the access attempt or NULL if this access attempt is directly from
2860 ** top-level SQL code.
2861 */
2862 /******************************************* 3rd ************ 4th ***********/
2863 #define SQLCIPHER_CREATE_INDEX          1   /* Index Name      Table Name      */
2864 #define SQLCIPHER_CREATE_TABLE          2   /* Table Name      NULL            */
2865 #define SQLCIPHER_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2866 #define SQLCIPHER_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2867 #define SQLCIPHER_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2868 #define SQLCIPHER_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2869 #define SQLCIPHER_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2870 #define SQLCIPHER_CREATE_VIEW           8   /* View Name       NULL            */
2871 #define SQLCIPHER_DELETE                9   /* Table Name      NULL            */
2872 #define SQLCIPHER_DROP_INDEX           10   /* Index Name      Table Name      */
2873 #define SQLCIPHER_DROP_TABLE           11   /* Table Name      NULL            */
2874 #define SQLCIPHER_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2875 #define SQLCIPHER_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2876 #define SQLCIPHER_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2877 #define SQLCIPHER_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2878 #define SQLCIPHER_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2879 #define SQLCIPHER_DROP_VIEW            17   /* View Name       NULL            */
2880 #define SQLCIPHER_INSERT               18   /* Table Name      NULL            */
2881 #define SQLCIPHER_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2882 #define SQLCIPHER_READ                 20   /* Table Name      Column Name     */
2883 #define SQLCIPHER_SELECT               21   /* NULL            NULL            */
2884 #define SQLCIPHER_TRANSACTION          22   /* Operation       NULL            */
2885 #define SQLCIPHER_UPDATE               23   /* Table Name      Column Name     */
2886 #define SQLCIPHER_ATTACH               24   /* Filename        NULL            */
2887 #define SQLCIPHER_DETACH               25   /* Database Name   NULL            */
2888 #define SQLCIPHER_ALTER_TABLE          26   /* Database Name   Table Name      */
2889 #define SQLCIPHER_REINDEX              27   /* Index Name      NULL            */
2890 #define SQLCIPHER_ANALYZE              28   /* Table Name      NULL            */
2891 #define SQLCIPHER_CREATE_VTABLE        29   /* Table Name      Module Name     */
2892 #define SQLCIPHER_DROP_VTABLE          30   /* Table Name      Module Name     */
2893 #define SQLCIPHER_FUNCTION             31   /* NULL            Function Name   */
2894 #define SQLCIPHER_SAVEPOINT            32   /* Operation       Savepoint Name  */
2895 #define SQLCIPHER_COPY                  0   /* No longer used */
2896
2897 /*
2898 ** CAPI3REF: Tracing And Profiling Functions
2899 **
2900 ** These routines register callback functions that can be used for
2901 ** tracing and profiling the execution of SQL statements.
2902 **
2903 ** ^The callback function registered by sqlcipher3_trace() is invoked at
2904 ** various times when an SQL statement is being run by [sqlcipher3_step()].
2905 ** ^The sqlcipher3_trace() callback is invoked with a UTF-8 rendering of the
2906 ** SQL statement text as the statement first begins executing.
2907 ** ^(Additional sqlcipher3_trace() callbacks might occur
2908 ** as each triggered subprogram is entered.  The callbacks for triggers
2909 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2910 **
2911 ** ^The callback function registered by sqlcipher3_profile() is invoked
2912 ** as each SQL statement finishes.  ^The profile callback contains
2913 ** the original statement text and an estimate of wall-clock time
2914 ** of how long that statement took to run.  ^The profile callback
2915 ** time is in units of nanoseconds, however the current implementation
2916 ** is only capable of millisecond resolution so the six least significant
2917 ** digits in the time are meaningless.  Future versions of SQLite
2918 ** might provide greater resolution on the profiler callback.  The
2919 ** sqlcipher3_profile() function is considered experimental and is
2920 ** subject to change in future versions of SQLite.
2921 */
2922 SQLCIPHER_API void *sqlcipher3_trace(sqlcipher3*, void(*xTrace)(void*,const char*), void*);
2923 SQLCIPHER_API SQLCIPHER_EXPERIMENTAL void *sqlcipher3_profile(sqlcipher3*,
2924    void(*xProfile)(void*,const char*,sqlcipher3_uint64), void*);
2925
2926 /*
2927 ** CAPI3REF: Query Progress Callbacks
2928 **
2929 ** ^The sqlcipher3_progress_handler(D,N,X,P) interface causes the callback
2930 ** function X to be invoked periodically during long running calls to
2931 ** [sqlcipher3_exec()], [sqlcipher3_step()] and [sqlcipher3_get_table()] for
2932 ** database connection D.  An example use for this
2933 ** interface is to keep a GUI updated during a large query.
2934 **
2935 ** ^The parameter P is passed through as the only parameter to the 
2936 ** callback function X.  ^The parameter N is the number of 
2937 ** [virtual machine instructions] that are evaluated between successive
2938 ** invocations of the callback X.
2939 **
2940 ** ^Only a single progress handler may be defined at one time per
2941 ** [database connection]; setting a new progress handler cancels the
2942 ** old one.  ^Setting parameter X to NULL disables the progress handler.
2943 ** ^The progress handler is also disabled by setting N to a value less
2944 ** than 1.
2945 **
2946 ** ^If the progress callback returns non-zero, the operation is
2947 ** interrupted.  This feature can be used to implement a
2948 ** "Cancel" button on a GUI progress dialog box.
2949 **
2950 ** The progress handler callback must not do anything that will modify
2951 ** the database connection that invoked the progress handler.
2952 ** Note that [sqlcipher3_prepare_v2()] and [sqlcipher3_step()] both modify their
2953 ** database connections for the meaning of "modify" in this paragraph.
2954 **
2955 */
2956 SQLCIPHER_API void sqlcipher3_progress_handler(sqlcipher3*, int, int(*)(void*), void*);
2957
2958 /*
2959 ** CAPI3REF: Opening A New Database Connection
2960 **
2961 ** ^These routines open an SQLite database file as specified by the 
2962 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2963 ** sqlcipher3_open() and sqlcipher3_open_v2() and as UTF-16 in the native byte
2964 ** order for sqlcipher3_open16(). ^(A [database connection] handle is usually
2965 ** returned in *ppDb, even if an error occurs.  The only exception is that
2966 ** if SQLite is unable to allocate memory to hold the [sqlcipher3] object,
2967 ** a NULL will be written into *ppDb instead of a pointer to the [sqlcipher3]
2968 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2969 ** [SQLCIPHER_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2970 ** [sqlcipher3_errmsg()] or [sqlcipher3_errmsg16()] routines can be used to obtain
2971 ** an English language description of the error following a failure of any
2972 ** of the sqlcipher3_open() routines.
2973 **
2974 ** ^The default encoding for the database will be UTF-8 if
2975 ** sqlcipher3_open() or sqlcipher3_open_v2() is called and
2976 ** UTF-16 in the native byte order if sqlcipher3_open16() is used.
2977 **
2978 ** Whether or not an error occurs when it is opened, resources
2979 ** associated with the [database connection] handle should be released by
2980 ** passing it to [sqlcipher3_close()] when it is no longer required.
2981 **
2982 ** The sqlcipher3_open_v2() interface works like sqlcipher3_open()
2983 ** except that it accepts two additional parameters for additional control
2984 ** over the new database connection.  ^(The flags parameter to
2985 ** sqlcipher3_open_v2() can take one of
2986 ** the following three values, optionally combined with the 
2987 ** [SQLCIPHER_OPEN_NOMUTEX], [SQLCIPHER_OPEN_FULLMUTEX], [SQLCIPHER_OPEN_SHAREDCACHE],
2988 ** [SQLCIPHER_OPEN_PRIVATECACHE], and/or [SQLCIPHER_OPEN_URI] flags:)^
2989 **
2990 ** <dl>
2991 ** ^(<dt>[SQLCIPHER_OPEN_READONLY]</dt>
2992 ** <dd>The database is opened in read-only mode.  If the database does not
2993 ** already exist, an error is returned.</dd>)^
2994 **
2995 ** ^(<dt>[SQLCIPHER_OPEN_READWRITE]</dt>
2996 ** <dd>The database is opened for reading and writing if possible, or reading
2997 ** only if the file is write protected by the operating system.  In either
2998 ** case the database must already exist, otherwise an error is returned.</dd>)^
2999 **
3000 ** ^(<dt>[SQLCIPHER_OPEN_READWRITE] | [SQLCIPHER_OPEN_CREATE]</dt>
3001 ** <dd>The database is opened for reading and writing, and is created if
3002 ** it does not already exist. This is the behavior that is always used for
3003 ** sqlcipher3_open() and sqlcipher3_open16().</dd>)^
3004 ** </dl>
3005 **
3006 ** If the 3rd parameter to sqlcipher3_open_v2() is not one of the
3007 ** combinations shown above optionally combined with other
3008 ** [SQLCIPHER_OPEN_READONLY | SQLCIPHER_OPEN_* bits]
3009 ** then the behavior is undefined.
3010 **
3011 ** ^If the [SQLCIPHER_OPEN_NOMUTEX] flag is set, then the database connection
3012 ** opens in the multi-thread [threading mode] as long as the single-thread
3013 ** mode has not been set at compile-time or start-time.  ^If the
3014 ** [SQLCIPHER_OPEN_FULLMUTEX] flag is set then the database connection opens
3015 ** in the serialized [threading mode] unless single-thread was
3016 ** previously selected at compile-time or start-time.
3017 ** ^The [SQLCIPHER_OPEN_SHAREDCACHE] flag causes the database connection to be
3018 ** eligible to use [shared cache mode], regardless of whether or not shared
3019 ** cache is enabled using [sqlcipher3_enable_shared_cache()].  ^The
3020 ** [SQLCIPHER_OPEN_PRIVATECACHE] flag causes the database connection to not
3021 ** participate in [shared cache mode] even if it is enabled.
3022 **
3023 ** ^The fourth parameter to sqlcipher3_open_v2() is the name of the
3024 ** [sqlcipher3_vfs] object that defines the operating system interface that
3025 ** the new database connection should use.  ^If the fourth parameter is
3026 ** a NULL pointer then the default [sqlcipher3_vfs] object is used.
3027 **
3028 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3029 ** is created for the connection.  ^This in-memory database will vanish when
3030 ** the database connection is closed.  Future versions of SQLite might
3031 ** make use of additional special filenames that begin with the ":" character.
3032 ** It is recommended that when a database filename actually does begin with
3033 ** a ":" character you should prefix the filename with a pathname such as
3034 ** "./" to avoid ambiguity.
3035 **
3036 ** ^If the filename is an empty string, then a private, temporary
3037 ** on-disk database will be created.  ^This private database will be
3038 ** automatically deleted as soon as the database connection is closed.
3039 **
3040 ** [[URI filenames in sqlcipher3_open()]] <h3>URI Filenames</h3>
3041 **
3042 ** ^If [URI filename] interpretation is enabled, and the filename argument
3043 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3044 ** filename interpretation is enabled if the [SQLCIPHER_OPEN_URI] flag is
3045 ** set in the fourth argument to sqlcipher3_open_v2(), or if it has
3046 ** been enabled globally using the [SQLCIPHER_CONFIG_URI] option with the
3047 ** [sqlcipher3_config()] method or by the [SQLCIPHER_USE_URI] compile-time option.
3048 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3049 ** by default, but future releases of SQLite might enable URI filename
3050 ** interpretation by default.  See "[URI filenames]" for additional
3051 ** information.
3052 **
3053 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3054 ** authority, then it must be either an empty string or the string 
3055 ** "localhost". ^If the authority is not an empty string or "localhost", an 
3056 ** error is returned to the caller. ^The fragment component of a URI, if 
3057 ** present, is ignored.
3058 **
3059 ** ^SQLite uses the path component of the URI as the name of the disk file
3060 ** which contains the database. ^If the path begins with a '/' character, 
3061 ** then it is interpreted as an absolute path. ^If the path does not begin 
3062 ** with a '/' (meaning that the authority section is omitted from the URI)
3063 ** then the path is interpreted as a relative path. 
3064 ** ^On windows, the first component of an absolute path 
3065 ** is a drive specification (e.g. "C:").
3066 **
3067 ** [[core URI query parameters]]
3068 ** The query component of a URI may contain parameters that are interpreted
3069 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3070 ** SQLite interprets the following three query parameters:
3071 **
3072 ** <ul>
3073 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3074 **     a VFS object that provides the operating system interface that should
3075 **     be used to access the database file on disk. ^If this option is set to
3076 **     an empty string the default VFS object is used. ^Specifying an unknown
3077 **     VFS is an error. ^If sqlcipher3_open_v2() is used and the vfs option is
3078 **     present, then the VFS specified by the option takes precedence over
3079 **     the value passed as the fourth parameter to sqlcipher3_open_v2().
3080 **
3081 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw" or
3082 **     "rwc". Attempting to set it to any other value is an error)^. 
3083 **     ^If "ro" is specified, then the database is opened for read-only 
3084 **     access, just as if the [SQLCIPHER_OPEN_READONLY] flag had been set in the 
3085 **     third argument to sqlcipher3_prepare_v2(). ^If the mode option is set to 
3086 **     "rw", then the database is opened for read-write (but not create) 
3087 **     access, as if SQLCIPHER_OPEN_READWRITE (but not SQLCIPHER_OPEN_CREATE) had 
3088 **     been set. ^Value "rwc" is equivalent to setting both 
3089 **     SQLCIPHER_OPEN_READWRITE and SQLCIPHER_OPEN_CREATE. ^If sqlcipher3_open_v2() is 
3090 **     used, it is an error to specify a value for the mode parameter that is 
3091 **     less restrictive than that specified by the flags passed as the third 
3092 **     parameter.
3093 **
3094 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3095 **     "private". ^Setting it to "shared" is equivalent to setting the
3096 **     SQLCIPHER_OPEN_SHAREDCACHE bit in the flags argument passed to
3097 **     sqlcipher3_open_v2(). ^Setting the cache parameter to "private" is 
3098 **     equivalent to setting the SQLCIPHER_OPEN_PRIVATECACHE bit.
3099 **     ^If sqlcipher3_open_v2() is used and the "cache" parameter is present in
3100 **     a URI filename, its value overrides any behaviour requested by setting
3101 **     SQLCIPHER_OPEN_PRIVATECACHE or SQLCIPHER_OPEN_SHAREDCACHE flag.
3102 ** </ul>
3103 **
3104 ** ^Specifying an unknown parameter in the query component of a URI is not an
3105 ** error.  Future versions of SQLite might understand additional query
3106 ** parameters.  See "[query parameters with special meaning to SQLite]" for
3107 ** additional information.
3108 **
3109 ** [[URI filename examples]] <h3>URI filename examples</h3>
3110 **
3111 ** <table border="1" align=center cellpadding=5>
3112 ** <tr><th> URI filenames <th> Results
3113 ** <tr><td> file:data.db <td> 
3114 **          Open the file "data.db" in the current directory.
3115 ** <tr><td> file:/home/fred/data.db<br>
3116 **          file:///home/fred/data.db <br> 
3117 **          file://localhost/home/fred/data.db <br> <td> 
3118 **          Open the database file "/home/fred/data.db".
3119 ** <tr><td> file://darkstar/home/fred/data.db <td> 
3120 **          An error. "darkstar" is not a recognized authority.
3121 ** <tr><td style="white-space:nowrap"> 
3122 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3123 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3124 **          C:. Note that the %20 escaping in this example is not strictly 
3125 **          necessary - space characters can be used literally
3126 **          in URI filenames.
3127 ** <tr><td> file:data.db?mode=ro&cache=private <td> 
3128 **          Open file "data.db" in the current directory for read-only access.
3129 **          Regardless of whether or not shared-cache mode is enabled by
3130 **          default, use a private cache.
3131 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3132 **          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3133 ** <tr><td> file:data.db?mode=readonly <td> 
3134 **          An error. "readonly" is not a valid option for the "mode" parameter.
3135 ** </table>
3136 **
3137 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3138 ** query components of a URI. A hexadecimal escape sequence consists of a
3139 ** percent sign - "%" - followed by exactly two hexadecimal digits 
3140 ** specifying an octet value. ^Before the path or query components of a
3141 ** URI filename are interpreted, they are encoded using UTF-8 and all 
3142 ** hexadecimal escape sequences replaced by a single byte containing the
3143 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3144 ** the results are undefined.
3145 **
3146 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3147 ** of sqlcipher3_open() and sqlcipher3_open_v2() must be UTF-8, not whatever
3148 ** codepage is currently defined.  Filenames containing international
3149 ** characters must be converted to UTF-8 prior to passing them into
3150 ** sqlcipher3_open() or sqlcipher3_open_v2().
3151 */
3152 SQLCIPHER_API int sqlcipher3_open(
3153   const char *filename,   /* Database filename (UTF-8) */
3154   sqlcipher3 **ppDb          /* OUT: SQLite db handle */
3155 );
3156 SQLCIPHER_API int sqlcipher3_open16(
3157   const void *filename,   /* Database filename (UTF-16) */
3158   sqlcipher3 **ppDb          /* OUT: SQLite db handle */
3159 );
3160 SQLCIPHER_API int sqlcipher3_open_v2(
3161   const char *filename,   /* Database filename (UTF-8) */
3162   sqlcipher3 **ppDb,         /* OUT: SQLite db handle */
3163   int flags,              /* Flags */
3164   const char *zVfs        /* Name of VFS module to use */
3165 );
3166
3167 /*
3168 ** CAPI3REF: Obtain Values For URI Parameters
3169 **
3170 ** This is a utility routine, useful to VFS implementations, that checks
3171 ** to see if a database file was a URI that contained a specific query 
3172 ** parameter, and if so obtains the value of the query parameter.
3173 **
3174 ** The zFilename argument is the filename pointer passed into the xOpen()
3175 ** method of a VFS implementation.  The zParam argument is the name of the
3176 ** query parameter we seek.  This routine returns the value of the zParam
3177 ** parameter if it exists.  If the parameter does not exist, this routine
3178 ** returns a NULL pointer.
3179 **
3180 ** If the zFilename argument to this function is not a pointer that SQLite
3181 ** passed into the xOpen VFS method, then the behavior of this routine
3182 ** is undefined and probably undesirable.
3183 */
3184 SQLCIPHER_API const char *sqlcipher3_uri_parameter(const char *zFilename, const char *zParam);
3185
3186
3187 /*
3188 ** CAPI3REF: Error Codes And Messages
3189 **
3190 ** ^The sqlcipher3_errcode() interface returns the numeric [result code] or
3191 ** [extended result code] for the most recent failed sqlcipher3_* API call
3192 ** associated with a [database connection]. If a prior API call failed
3193 ** but the most recent API call succeeded, the return value from
3194 ** sqlcipher3_errcode() is undefined.  ^The sqlcipher3_extended_errcode()
3195 ** interface is the same except that it always returns the 
3196 ** [extended result code] even when extended result codes are
3197 ** disabled.
3198 **
3199 ** ^The sqlcipher3_errmsg() and sqlcipher3_errmsg16() return English-language
3200 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3201 ** ^(Memory to hold the error message string is managed internally.
3202 ** The application does not need to worry about freeing the result.
3203 ** However, the error string might be overwritten or deallocated by
3204 ** subsequent calls to other SQLite interface functions.)^
3205 **
3206 ** When the serialized [threading mode] is in use, it might be the
3207 ** case that a second error occurs on a separate thread in between
3208 ** the time of the first error and the call to these interfaces.
3209 ** When that happens, the second error will be reported since these
3210 ** interfaces always report the most recent result.  To avoid
3211 ** this, each thread can obtain exclusive use of the [database connection] D
3212 ** by invoking [sqlcipher3_mutex_enter]([sqlcipher3_db_mutex](D)) before beginning
3213 ** to use D and invoking [sqlcipher3_mutex_leave]([sqlcipher3_db_mutex](D)) after
3214 ** all calls to the interfaces listed here are completed.
3215 **
3216 ** If an interface fails with SQLCIPHER_MISUSE, that means the interface
3217 ** was invoked incorrectly by the application.  In that case, the
3218 ** error code and message may or may not be set.
3219 */
3220 SQLCIPHER_API int sqlcipher3_errcode(sqlcipher3 *db);
3221 SQLCIPHER_API int sqlcipher3_extended_errcode(sqlcipher3 *db);
3222 SQLCIPHER_API const char *sqlcipher3_errmsg(sqlcipher3*);
3223 SQLCIPHER_API const void *sqlcipher3_errmsg16(sqlcipher3*);
3224
3225 /*
3226 ** CAPI3REF: SQL Statement Object
3227 ** KEYWORDS: {prepared statement} {prepared statements}
3228 **
3229 ** An instance of this object represents a single SQL statement.
3230 ** This object is variously known as a "prepared statement" or a
3231 ** "compiled SQL statement" or simply as a "statement".
3232 **
3233 ** The life of a statement object goes something like this:
3234 **
3235 ** <ol>
3236 ** <li> Create the object using [sqlcipher3_prepare_v2()] or a related
3237 **      function.
3238 ** <li> Bind values to [host parameters] using the sqlcipher3_bind_*()
3239 **      interfaces.
3240 ** <li> Run the SQL by calling [sqlcipher3_step()] one or more times.
3241 ** <li> Reset the statement using [sqlcipher3_reset()] then go back
3242 **      to step 2.  Do this zero or more times.
3243 ** <li> Destroy the object using [sqlcipher3_finalize()].
3244 ** </ol>
3245 **
3246 ** Refer to documentation on individual methods above for additional
3247 ** information.
3248 */
3249 typedef struct sqlcipher3_stmt sqlcipher3_stmt;
3250
3251 /*
3252 ** CAPI3REF: Run-time Limits
3253 **
3254 ** ^(This interface allows the size of various constructs to be limited
3255 ** on a connection by connection basis.  The first parameter is the
3256 ** [database connection] whose limit is to be set or queried.  The
3257 ** second parameter is one of the [limit categories] that define a
3258 ** class of constructs to be size limited.  The third parameter is the
3259 ** new limit for that construct.)^
3260 **
3261 ** ^If the new limit is a negative number, the limit is unchanged.
3262 ** ^(For each limit category SQLCIPHER_LIMIT_<i>NAME</i> there is a 
3263 ** [limits | hard upper bound]
3264 ** set at compile-time by a C preprocessor macro called
3265 ** [limits | SQLCIPHER_MAX_<i>NAME</i>].
3266 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3267 ** ^Attempts to increase a limit above its hard upper bound are
3268 ** silently truncated to the hard upper bound.
3269 **
3270 ** ^Regardless of whether or not the limit was changed, the 
3271 ** [sqlcipher3_limit()] interface returns the prior value of the limit.
3272 ** ^Hence, to find the current value of a limit without changing it,
3273 ** simply invoke this interface with the third parameter set to -1.
3274 **
3275 ** Run-time limits are intended for use in applications that manage
3276 ** both their own internal database and also databases that are controlled
3277 ** by untrusted external sources.  An example application might be a
3278 ** web browser that has its own databases for storing history and
3279 ** separate databases controlled by JavaScript applications downloaded
3280 ** off the Internet.  The internal databases can be given the
3281 ** large, default limits.  Databases managed by external sources can
3282 ** be given much smaller limits designed to prevent a denial of service
3283 ** attack.  Developers might also want to use the [sqlcipher3_set_authorizer()]
3284 ** interface to further control untrusted SQL.  The size of the database
3285 ** created by an untrusted script can be contained using the
3286 ** [max_page_count] [PRAGMA].
3287 **
3288 ** New run-time limit categories may be added in future releases.
3289 */
3290 SQLCIPHER_API int sqlcipher3_limit(sqlcipher3*, int id, int newVal);
3291
3292 /*
3293 ** CAPI3REF: Run-Time Limit Categories
3294 ** KEYWORDS: {limit category} {*limit categories}
3295 **
3296 ** These constants define various performance limits
3297 ** that can be lowered at run-time using [sqlcipher3_limit()].
3298 ** The synopsis of the meanings of the various limits is shown below.
3299 ** Additional information is available at [limits | Limits in SQLite].
3300 **
3301 ** <dl>
3302 ** [[SQLCIPHER_LIMIT_LENGTH]] ^(<dt>SQLCIPHER_LIMIT_LENGTH</dt>
3303 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3304 **
3305 ** [[SQLCIPHER_LIMIT_SQL_LENGTH]] ^(<dt>SQLCIPHER_LIMIT_SQL_LENGTH</dt>
3306 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3307 **
3308 ** [[SQLCIPHER_LIMIT_COLUMN]] ^(<dt>SQLCIPHER_LIMIT_COLUMN</dt>
3309 ** <dd>The maximum number of columns in a table definition or in the
3310 ** result set of a [SELECT] or the maximum number of columns in an index
3311 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3312 **
3313 ** [[SQLCIPHER_LIMIT_EXPR_DEPTH]] ^(<dt>SQLCIPHER_LIMIT_EXPR_DEPTH</dt>
3314 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3315 **
3316 ** [[SQLCIPHER_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLCIPHER_LIMIT_COMPOUND_SELECT</dt>
3317 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3318 **
3319 ** [[SQLCIPHER_LIMIT_VDBE_OP]] ^(<dt>SQLCIPHER_LIMIT_VDBE_OP</dt>
3320 ** <dd>The maximum number of instructions in a virtual machine program
3321 ** used to implement an SQL statement.  This limit is not currently
3322 ** enforced, though that might be added in some future release of
3323 ** SQLite.</dd>)^
3324 **
3325 ** [[SQLCIPHER_LIMIT_FUNCTION_ARG]] ^(<dt>SQLCIPHER_LIMIT_FUNCTION_ARG</dt>
3326 ** <dd>The maximum number of arguments on a function.</dd>)^
3327 **
3328 ** [[SQLCIPHER_LIMIT_ATTACHED]] ^(<dt>SQLCIPHER_LIMIT_ATTACHED</dt>
3329 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3330 **
3331 ** [[SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH]]
3332 ** ^(<dt>SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH</dt>
3333 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3334 ** [GLOB] operators.</dd>)^
3335 **
3336 ** [[SQLCIPHER_LIMIT_VARIABLE_NUMBER]]
3337 ** ^(<dt>SQLCIPHER_LIMIT_VARIABLE_NUMBER</dt>
3338 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3339 **
3340 ** [[SQLCIPHER_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLCIPHER_LIMIT_TRIGGER_DEPTH</dt>
3341 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3342 ** </dl>
3343 */
3344 #define SQLCIPHER_LIMIT_LENGTH                    0
3345 #define SQLCIPHER_LIMIT_SQL_LENGTH                1
3346 #define SQLCIPHER_LIMIT_COLUMN                    2
3347 #define SQLCIPHER_LIMIT_EXPR_DEPTH                3
3348 #define SQLCIPHER_LIMIT_COMPOUND_SELECT           4
3349 #define SQLCIPHER_LIMIT_VDBE_OP                   5
3350 #define SQLCIPHER_LIMIT_FUNCTION_ARG              6
3351 #define SQLCIPHER_LIMIT_ATTACHED                  7
3352 #define SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH       8
3353 #define SQLCIPHER_LIMIT_VARIABLE_NUMBER           9
3354 #define SQLCIPHER_LIMIT_TRIGGER_DEPTH            10
3355
3356 /*
3357 ** CAPI3REF: Compiling An SQL Statement
3358 ** KEYWORDS: {SQL statement compiler}
3359 **
3360 ** To execute an SQL query, it must first be compiled into a byte-code
3361 ** program using one of these routines.
3362 **
3363 ** The first argument, "db", is a [database connection] obtained from a
3364 ** prior successful call to [sqlcipher3_open()], [sqlcipher3_open_v2()] or
3365 ** [sqlcipher3_open16()].  The database connection must not have been closed.
3366 **
3367 ** The second argument, "zSql", is the statement to be compiled, encoded
3368 ** as either UTF-8 or UTF-16.  The sqlcipher3_prepare() and sqlcipher3_prepare_v2()
3369 ** interfaces use UTF-8, and sqlcipher3_prepare16() and sqlcipher3_prepare16_v2()
3370 ** use UTF-16.
3371 **
3372 ** ^If the nByte argument is less than zero, then zSql is read up to the
3373 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3374 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3375 ** zSql string ends at either the first '\000' or '\u0000' character or
3376 ** the nByte-th byte, whichever comes first. If the caller knows
3377 ** that the supplied string is nul-terminated, then there is a small
3378 ** performance advantage to be gained by passing an nByte parameter that
3379 ** is equal to the number of bytes in the input string <i>including</i>
3380 ** the nul-terminator bytes as this saves SQLite from having to
3381 ** make a copy of the input string.
3382 **
3383 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3384 ** past the end of the first SQL statement in zSql.  These routines only
3385 ** compile the first statement in zSql, so *pzTail is left pointing to
3386 ** what remains uncompiled.
3387 **
3388 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3389 ** executed using [sqlcipher3_step()].  ^If there is an error, *ppStmt is set
3390 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3391 ** string or a comment) then *ppStmt is set to NULL.
3392 ** The calling procedure is responsible for deleting the compiled
3393 ** SQL statement using [sqlcipher3_finalize()] after it has finished with it.
3394 ** ppStmt may not be NULL.
3395 **
3396 ** ^On success, the sqlcipher3_prepare() family of routines return [SQLCIPHER_OK];
3397 ** otherwise an [error code] is returned.
3398 **
3399 ** The sqlcipher3_prepare_v2() and sqlcipher3_prepare16_v2() interfaces are
3400 ** recommended for all new programs. The two older interfaces are retained
3401 ** for backwards compatibility, but their use is discouraged.
3402 ** ^In the "v2" interfaces, the prepared statement
3403 ** that is returned (the [sqlcipher3_stmt] object) contains a copy of the
3404 ** original SQL text. This causes the [sqlcipher3_step()] interface to
3405 ** behave differently in three ways:
3406 **
3407 ** <ol>
3408 ** <li>
3409 ** ^If the database schema changes, instead of returning [SQLCIPHER_SCHEMA] as it
3410 ** always used to do, [sqlcipher3_step()] will automatically recompile the SQL
3411 ** statement and try to run it again.
3412 ** </li>
3413 **
3414 ** <li>
3415 ** ^When an error occurs, [sqlcipher3_step()] will return one of the detailed
3416 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3417 ** [sqlcipher3_step()] would only return a generic [SQLCIPHER_ERROR] result code
3418 ** and the application would have to make a second call to [sqlcipher3_reset()]
3419 ** in order to find the underlying cause of the problem. With the "v2" prepare
3420 ** interfaces, the underlying reason for the error is returned immediately.
3421 ** </li>
3422 **
3423 ** <li>
3424 ** ^If the specific value bound to [parameter | host parameter] in the 
3425 ** WHERE clause might influence the choice of query plan for a statement,
3426 ** then the statement will be automatically recompiled, as if there had been 
3427 ** a schema change, on the first  [sqlcipher3_step()] call following any change
3428 ** to the [sqlcipher3_bind_text | bindings] of that [parameter]. 
3429 ** ^The specific value of WHERE-clause [parameter] might influence the 
3430 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3431 ** or [GLOB] operator or if the parameter is compared to an indexed column
3432 ** and the [SQLCIPHER_ENABLE_STAT3] compile-time option is enabled.
3433 ** the 
3434 ** </li>
3435 ** </ol>
3436 */
3437 SQLCIPHER_API int sqlcipher3_prepare(
3438   sqlcipher3 *db,            /* Database handle */
3439   const char *zSql,       /* SQL statement, UTF-8 encoded */
3440   int nByte,              /* Maximum length of zSql in bytes. */
3441   sqlcipher3_stmt **ppStmt,  /* OUT: Statement handle */
3442   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3443 );
3444 SQLCIPHER_API int sqlcipher3_prepare_v2(
3445   sqlcipher3 *db,            /* Database handle */
3446   const char *zSql,       /* SQL statement, UTF-8 encoded */
3447   int nByte,              /* Maximum length of zSql in bytes. */
3448   sqlcipher3_stmt **ppStmt,  /* OUT: Statement handle */
3449   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3450 );
3451 SQLCIPHER_API int sqlcipher3_prepare16(
3452   sqlcipher3 *db,            /* Database handle */
3453   const void *zSql,       /* SQL statement, UTF-16 encoded */
3454   int nByte,              /* Maximum length of zSql in bytes. */
3455   sqlcipher3_stmt **ppStmt,  /* OUT: Statement handle */
3456   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3457 );
3458 SQLCIPHER_API int sqlcipher3_prepare16_v2(
3459   sqlcipher3 *db,            /* Database handle */
3460   const void *zSql,       /* SQL statement, UTF-16 encoded */
3461   int nByte,              /* Maximum length of zSql in bytes. */
3462   sqlcipher3_stmt **ppStmt,  /* OUT: Statement handle */
3463   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3464 );
3465
3466 /*
3467 ** CAPI3REF: Retrieving Statement SQL
3468 **
3469 ** ^This interface can be used to retrieve a saved copy of the original
3470 ** SQL text used to create a [prepared statement] if that statement was
3471 ** compiled using either [sqlcipher3_prepare_v2()] or [sqlcipher3_prepare16_v2()].
3472 */
3473 SQLCIPHER_API const char *sqlcipher3_sql(sqlcipher3_stmt *pStmt);
3474
3475 /*
3476 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3477 **
3478 ** ^The sqlcipher3_stmt_readonly(X) interface returns true (non-zero) if
3479 ** and only if the [prepared statement] X makes no direct changes to
3480 ** the content of the database file.
3481 **
3482 ** Note that [application-defined SQL functions] or
3483 ** [virtual tables] might change the database indirectly as a side effect.  
3484 ** ^(For example, if an application defines a function "eval()" that 
3485 ** calls [sqlcipher3_exec()], then the following SQL statement would
3486 ** change the database file through side-effects:
3487 **
3488 ** <blockquote><pre>
3489 **    SELECT eval('DELETE FROM t1') FROM t2;
3490 ** </pre></blockquote>
3491 **
3492 ** But because the [SELECT] statement does not change the database file
3493 ** directly, sqlcipher3_stmt_readonly() would still return true.)^
3494 **
3495 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3496 ** [SAVEPOINT], and [RELEASE] cause sqlcipher3_stmt_readonly() to return true,
3497 ** since the statements themselves do not actually modify the database but
3498 ** rather they control the timing of when other statements modify the 
3499 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3500 ** sqlcipher3_stmt_readonly() to return true since, while those statements
3501 ** change the configuration of a database connection, they do not make 
3502 ** changes to the content of the database files on disk.
3503 */
3504 SQLCIPHER_API int sqlcipher3_stmt_readonly(sqlcipher3_stmt *pStmt);
3505
3506 /*
3507 ** CAPI3REF: Dynamically Typed Value Object
3508 ** KEYWORDS: {protected sqlcipher3_value} {unprotected sqlcipher3_value}
3509 **
3510 ** SQLite uses the sqlcipher3_value object to represent all values
3511 ** that can be stored in a database table. SQLite uses dynamic typing
3512 ** for the values it stores.  ^Values stored in sqlcipher3_value objects
3513 ** can be integers, floating point values, strings, BLOBs, or NULL.
3514 **
3515 ** An sqlcipher3_value object may be either "protected" or "unprotected".
3516 ** Some interfaces require a protected sqlcipher3_value.  Other interfaces
3517 ** will accept either a protected or an unprotected sqlcipher3_value.
3518 ** Every interface that accepts sqlcipher3_value arguments specifies
3519 ** whether or not it requires a protected sqlcipher3_value.
3520 **
3521 ** The terms "protected" and "unprotected" refer to whether or not
3522 ** a mutex is held.  An internal mutex is held for a protected
3523 ** sqlcipher3_value object but no mutex is held for an unprotected
3524 ** sqlcipher3_value object.  If SQLite is compiled to be single-threaded
3525 ** (with [SQLCIPHER_THREADSAFE=0] and with [sqlcipher3_threadsafe()] returning 0)
3526 ** or if SQLite is run in one of reduced mutex modes 
3527 ** [SQLCIPHER_CONFIG_SINGLETHREAD] or [SQLCIPHER_CONFIG_MULTITHREAD]
3528 ** then there is no distinction between protected and unprotected
3529 ** sqlcipher3_value objects and they can be used interchangeably.  However,
3530 ** for maximum code portability it is recommended that applications
3531 ** still make the distinction between protected and unprotected
3532 ** sqlcipher3_value objects even when not strictly required.
3533 **
3534 ** ^The sqlcipher3_value objects that are passed as parameters into the
3535 ** implementation of [application-defined SQL functions] are protected.
3536 ** ^The sqlcipher3_value object returned by
3537 ** [sqlcipher3_column_value()] is unprotected.
3538 ** Unprotected sqlcipher3_value objects may only be used with
3539 ** [sqlcipher3_result_value()] and [sqlcipher3_bind_value()].
3540 ** The [sqlcipher3_value_blob | sqlcipher3_value_type()] family of
3541 ** interfaces require protected sqlcipher3_value objects.
3542 */
3543 typedef struct Mem sqlcipher3_value;
3544
3545 /*
3546 ** CAPI3REF: SQL Function Context Object
3547 **
3548 ** The context in which an SQL function executes is stored in an
3549 ** sqlcipher3_context object.  ^A pointer to an sqlcipher3_context object
3550 ** is always first parameter to [application-defined SQL functions].
3551 ** The application-defined SQL function implementation will pass this
3552 ** pointer through into calls to [sqlcipher3_result_int | sqlcipher3_result()],
3553 ** [sqlcipher3_aggregate_context()], [sqlcipher3_user_data()],
3554 ** [sqlcipher3_context_db_handle()], [sqlcipher3_get_auxdata()],
3555 ** and/or [sqlcipher3_set_auxdata()].
3556 */
3557 typedef struct sqlcipher3_context sqlcipher3_context;
3558
3559 /*
3560 ** CAPI3REF: Binding Values To Prepared Statements
3561 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3562 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3563 **
3564 ** ^(In the SQL statement text input to [sqlcipher3_prepare_v2()] and its variants,
3565 ** literals may be replaced by a [parameter] that matches one of following
3566 ** templates:
3567 **
3568 ** <ul>
3569 ** <li>  ?
3570 ** <li>  ?NNN
3571 ** <li>  :VVV
3572 ** <li>  @VVV
3573 ** <li>  $VVV
3574 ** </ul>
3575 **
3576 ** In the templates above, NNN represents an integer literal,
3577 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3578 ** parameters (also called "host parameter names" or "SQL parameters")
3579 ** can be set using the sqlcipher3_bind_*() routines defined here.
3580 **
3581 ** ^The first argument to the sqlcipher3_bind_*() routines is always
3582 ** a pointer to the [sqlcipher3_stmt] object returned from
3583 ** [sqlcipher3_prepare_v2()] or its variants.
3584 **
3585 ** ^The second argument is the index of the SQL parameter to be set.
3586 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3587 ** SQL parameter is used more than once, second and subsequent
3588 ** occurrences have the same index as the first occurrence.
3589 ** ^The index for named parameters can be looked up using the
3590 ** [sqlcipher3_bind_parameter_index()] API if desired.  ^The index
3591 ** for "?NNN" parameters is the value of NNN.
3592 ** ^The NNN value must be between 1 and the [sqlcipher3_limit()]
3593 ** parameter [SQLCIPHER_LIMIT_VARIABLE_NUMBER] (default value: 999).
3594 **
3595 ** ^The third argument is the value to bind to the parameter.
3596 **
3597 ** ^(In those routines that have a fourth argument, its value is the
3598 ** number of bytes in the parameter.  To be clear: the value is the
3599 ** number of <u>bytes</u> in the value, not the number of characters.)^
3600 ** ^If the fourth parameter is negative, the length of the string is
3601 ** the number of bytes up to the first zero terminator.
3602 ** If a non-negative fourth parameter is provided to sqlcipher3_bind_text()
3603 ** or sqlcipher3_bind_text16() then that parameter must be the byte offset
3604 ** where the NUL terminator would occur assuming the string were NUL
3605 ** terminated.  If any NUL characters occur at byte offsets less than 
3606 ** the value of the fourth parameter then the resulting string value will
3607 ** contain embedded NULs.  The result of expressions involving strings
3608 ** with embedded NULs is undefined.
3609 **
3610 ** ^The fifth argument to sqlcipher3_bind_blob(), sqlcipher3_bind_text(), and
3611 ** sqlcipher3_bind_text16() is a destructor used to dispose of the BLOB or
3612 ** string after SQLite has finished with it.  ^The destructor is called
3613 ** to dispose of the BLOB or string even if the call to sqlcipher3_bind_blob(),
3614 ** sqlcipher3_bind_text(), or sqlcipher3_bind_text16() fails.  
3615 ** ^If the fifth argument is
3616 ** the special value [SQLCIPHER_STATIC], then SQLite assumes that the
3617 ** information is in static, unmanaged space and does not need to be freed.
3618 ** ^If the fifth argument has the value [SQLCIPHER_TRANSIENT], then
3619 ** SQLite makes its own private copy of the data immediately, before
3620 ** the sqlcipher3_bind_*() routine returns.
3621 **
3622 ** ^The sqlcipher3_bind_zeroblob() routine binds a BLOB of length N that
3623 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3624 ** (just an integer to hold its size) while it is being processed.
3625 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3626 ** content is later written using
3627 ** [sqlcipher3_blob_open | incremental BLOB I/O] routines.
3628 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3629 **
3630 ** ^If any of the sqlcipher3_bind_*() routines are called with a NULL pointer
3631 ** for the [prepared statement] or with a prepared statement for which
3632 ** [sqlcipher3_step()] has been called more recently than [sqlcipher3_reset()],
3633 ** then the call will return [SQLCIPHER_MISUSE].  If any sqlcipher3_bind_()
3634 ** routine is passed a [prepared statement] that has been finalized, the
3635 ** result is undefined and probably harmful.
3636 **
3637 ** ^Bindings are not cleared by the [sqlcipher3_reset()] routine.
3638 ** ^Unbound parameters are interpreted as NULL.
3639 **
3640 ** ^The sqlcipher3_bind_* routines return [SQLCIPHER_OK] on success or an
3641 ** [error code] if anything goes wrong.
3642 ** ^[SQLCIPHER_RANGE] is returned if the parameter
3643 ** index is out of range.  ^[SQLCIPHER_NOMEM] is returned if malloc() fails.
3644 **
3645 ** See also: [sqlcipher3_bind_parameter_count()],
3646 ** [sqlcipher3_bind_parameter_name()], and [sqlcipher3_bind_parameter_index()].
3647 */
3648 SQLCIPHER_API int sqlcipher3_bind_blob(sqlcipher3_stmt*, int, const void*, int n, void(*)(void*));
3649 SQLCIPHER_API int sqlcipher3_bind_double(sqlcipher3_stmt*, int, double);
3650 SQLCIPHER_API int sqlcipher3_bind_int(sqlcipher3_stmt*, int, int);
3651 SQLCIPHER_API int sqlcipher3_bind_int64(sqlcipher3_stmt*, int, sqlcipher3_int64);
3652 SQLCIPHER_API int sqlcipher3_bind_null(sqlcipher3_stmt*, int);
3653 SQLCIPHER_API int sqlcipher3_bind_text(sqlcipher3_stmt*, int, const char*, int n, void(*)(void*));
3654 SQLCIPHER_API int sqlcipher3_bind_text16(sqlcipher3_stmt*, int, const void*, int, void(*)(void*));
3655 SQLCIPHER_API int sqlcipher3_bind_value(sqlcipher3_stmt*, int, const sqlcipher3_value*);
3656 SQLCIPHER_API int sqlcipher3_bind_zeroblob(sqlcipher3_stmt*, int, int n);
3657
3658 /*
3659 ** CAPI3REF: Number Of SQL Parameters
3660 **
3661 ** ^This routine can be used to find the number of [SQL parameters]
3662 ** in a [prepared statement].  SQL parameters are tokens of the
3663 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3664 ** placeholders for values that are [sqlcipher3_bind_blob | bound]
3665 ** to the parameters at a later time.
3666 **
3667 ** ^(This routine actually returns the index of the largest (rightmost)
3668 ** parameter. For all forms except ?NNN, this will correspond to the
3669 ** number of unique parameters.  If parameters of the ?NNN form are used,
3670 ** there may be gaps in the list.)^
3671 **
3672 ** See also: [sqlcipher3_bind_blob|sqlcipher3_bind()],
3673 ** [sqlcipher3_bind_parameter_name()], and
3674 ** [sqlcipher3_bind_parameter_index()].
3675 */
3676 SQLCIPHER_API int sqlcipher3_bind_parameter_count(sqlcipher3_stmt*);
3677
3678 /*
3679 ** CAPI3REF: Name Of A Host Parameter
3680 **
3681 ** ^The sqlcipher3_bind_parameter_name(P,N) interface returns
3682 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3683 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3684 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3685 ** respectively.
3686 ** In other words, the initial ":" or "$" or "@" or "?"
3687 ** is included as part of the name.)^
3688 ** ^Parameters of the form "?" without a following integer have no name
3689 ** and are referred to as "nameless" or "anonymous parameters".
3690 **
3691 ** ^The first host parameter has an index of 1, not 0.
3692 **
3693 ** ^If the value N is out of range or if the N-th parameter is
3694 ** nameless, then NULL is returned.  ^The returned string is
3695 ** always in UTF-8 encoding even if the named parameter was
3696 ** originally specified as UTF-16 in [sqlcipher3_prepare16()] or
3697 ** [sqlcipher3_prepare16_v2()].
3698 **
3699 ** See also: [sqlcipher3_bind_blob|sqlcipher3_bind()],
3700 ** [sqlcipher3_bind_parameter_count()], and
3701 ** [sqlcipher3_bind_parameter_index()].
3702 */
3703 SQLCIPHER_API const char *sqlcipher3_bind_parameter_name(sqlcipher3_stmt*, int);
3704
3705 /*
3706 ** CAPI3REF: Index Of A Parameter With A Given Name
3707 **
3708 ** ^Return the index of an SQL parameter given its name.  ^The
3709 ** index value returned is suitable for use as the second
3710 ** parameter to [sqlcipher3_bind_blob|sqlcipher3_bind()].  ^A zero
3711 ** is returned if no matching parameter is found.  ^The parameter
3712 ** name must be given in UTF-8 even if the original statement
3713 ** was prepared from UTF-16 text using [sqlcipher3_prepare16_v2()].
3714 **
3715 ** See also: [sqlcipher3_bind_blob|sqlcipher3_bind()],
3716 ** [sqlcipher3_bind_parameter_count()], and
3717 ** [sqlcipher3_bind_parameter_index()].
3718 */
3719 SQLCIPHER_API int sqlcipher3_bind_parameter_index(sqlcipher3_stmt*, const char *zName);
3720
3721 /*
3722 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3723 **
3724 ** ^Contrary to the intuition of many, [sqlcipher3_reset()] does not reset
3725 ** the [sqlcipher3_bind_blob | bindings] on a [prepared statement].
3726 ** ^Use this routine to reset all host parameters to NULL.
3727 */
3728 SQLCIPHER_API int sqlcipher3_clear_bindings(sqlcipher3_stmt*);
3729
3730 /*
3731 ** CAPI3REF: Number Of Columns In A Result Set
3732 **
3733 ** ^Return the number of columns in the result set returned by the
3734 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3735 ** statement that does not return data (for example an [UPDATE]).
3736 **
3737 ** See also: [sqlcipher3_data_count()]
3738 */
3739 SQLCIPHER_API int sqlcipher3_column_count(sqlcipher3_stmt *pStmt);
3740
3741 /*
3742 ** CAPI3REF: Column Names In A Result Set
3743 **
3744 ** ^These routines return the name assigned to a particular column
3745 ** in the result set of a [SELECT] statement.  ^The sqlcipher3_column_name()
3746 ** interface returns a pointer to a zero-terminated UTF-8 string
3747 ** and sqlcipher3_column_name16() returns a pointer to a zero-terminated
3748 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3749 ** that implements the [SELECT] statement. ^The second parameter is the
3750 ** column number.  ^The leftmost column is number 0.
3751 **
3752 ** ^The returned string pointer is valid until either the [prepared statement]
3753 ** is destroyed by [sqlcipher3_finalize()] or until the statement is automatically
3754 ** reprepared by the first call to [sqlcipher3_step()] for a particular run
3755 ** or until the next call to
3756 ** sqlcipher3_column_name() or sqlcipher3_column_name16() on the same column.
3757 **
3758 ** ^If sqlcipher3_malloc() fails during the processing of either routine
3759 ** (for example during a conversion from UTF-8 to UTF-16) then a
3760 ** NULL pointer is returned.
3761 **
3762 ** ^The name of a result column is the value of the "AS" clause for
3763 ** that column, if there is an AS clause.  If there is no AS clause
3764 ** then the name of the column is unspecified and may change from
3765 ** one release of SQLite to the next.
3766 */
3767 SQLCIPHER_API const char *sqlcipher3_column_name(sqlcipher3_stmt*, int N);
3768 SQLCIPHER_API const void *sqlcipher3_column_name16(sqlcipher3_stmt*, int N);
3769
3770 /*
3771 ** CAPI3REF: Source Of Data In A Query Result
3772 **
3773 ** ^These routines provide a means to determine the database, table, and
3774 ** table column that is the origin of a particular result column in
3775 ** [SELECT] statement.
3776 ** ^The name of the database or table or column can be returned as
3777 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3778 ** the database name, the _table_ routines return the table name, and
3779 ** the origin_ routines return the column name.
3780 ** ^The returned string is valid until the [prepared statement] is destroyed
3781 ** using [sqlcipher3_finalize()] or until the statement is automatically
3782 ** reprepared by the first call to [sqlcipher3_step()] for a particular run
3783 ** or until the same information is requested
3784 ** again in a different encoding.
3785 **
3786 ** ^The names returned are the original un-aliased names of the
3787 ** database, table, and column.
3788 **
3789 ** ^The first argument to these interfaces is a [prepared statement].
3790 ** ^These functions return information about the Nth result column returned by
3791 ** the statement, where N is the second function argument.
3792 ** ^The left-most column is column 0 for these routines.
3793 **
3794 ** ^If the Nth column returned by the statement is an expression or
3795 ** subquery and is not a column value, then all of these functions return
3796 ** NULL.  ^These routine might also return NULL if a memory allocation error
3797 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3798 ** or column that query result column was extracted from.
3799 **
3800 ** ^As with all other SQLite APIs, those whose names end with "16" return
3801 ** UTF-16 encoded strings and the other functions return UTF-8.
3802 **
3803 ** ^These APIs are only available if the library was compiled with the
3804 ** [SQLCIPHER_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3805 **
3806 ** If two or more threads call one or more of these routines against the same
3807 ** prepared statement and column at the same time then the results are
3808 ** undefined.
3809 **
3810 ** If two or more threads call one or more
3811 ** [sqlcipher3_column_database_name | column metadata interfaces]
3812 ** for the same [prepared statement] and result column
3813 ** at the same time then the results are undefined.
3814 */
3815 SQLCIPHER_API const char *sqlcipher3_column_database_name(sqlcipher3_stmt*,int);
3816 SQLCIPHER_API const void *sqlcipher3_column_database_name16(sqlcipher3_stmt*,int);
3817 SQLCIPHER_API const char *sqlcipher3_column_table_name(sqlcipher3_stmt*,int);
3818 SQLCIPHER_API const void *sqlcipher3_column_table_name16(sqlcipher3_stmt*,int);
3819 SQLCIPHER_API const char *sqlcipher3_column_origin_name(sqlcipher3_stmt*,int);
3820 SQLCIPHER_API const void *sqlcipher3_column_origin_name16(sqlcipher3_stmt*,int);
3821
3822 /*
3823 ** CAPI3REF: Declared Datatype Of A Query Result
3824 **
3825 ** ^(The first parameter is a [prepared statement].
3826 ** If this statement is a [SELECT] statement and the Nth column of the
3827 ** returned result set of that [SELECT] is a table column (not an
3828 ** expression or subquery) then the declared type of the table
3829 ** column is returned.)^  ^If the Nth column of the result set is an
3830 ** expression or subquery, then a NULL pointer is returned.
3831 ** ^The returned string is always UTF-8 encoded.
3832 **
3833 ** ^(For example, given the database schema:
3834 **
3835 ** CREATE TABLE t1(c1 VARIANT);
3836 **
3837 ** and the following statement to be compiled:
3838 **
3839 ** SELECT c1 + 1, c1 FROM t1;
3840 **
3841 ** this routine would return the string "VARIANT" for the second result
3842 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3843 **
3844 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3845 ** is declared to contain a particular type does not mean that the
3846 ** data stored in that column is of the declared type.  SQLite is
3847 ** strongly typed, but the typing is dynamic not static.  ^Type
3848 ** is associated with individual values, not with the containers
3849 ** used to hold those values.
3850 */
3851 SQLCIPHER_API const char *sqlcipher3_column_decltype(sqlcipher3_stmt*,int);
3852 SQLCIPHER_API const void *sqlcipher3_column_decltype16(sqlcipher3_stmt*,int);
3853
3854 /*
3855 ** CAPI3REF: Evaluate An SQL Statement
3856 **
3857 ** After a [prepared statement] has been prepared using either
3858 ** [sqlcipher3_prepare_v2()] or [sqlcipher3_prepare16_v2()] or one of the legacy
3859 ** interfaces [sqlcipher3_prepare()] or [sqlcipher3_prepare16()], this function
3860 ** must be called one or more times to evaluate the statement.
3861 **
3862 ** The details of the behavior of the sqlcipher3_step() interface depend
3863 ** on whether the statement was prepared using the newer "v2" interface
3864 ** [sqlcipher3_prepare_v2()] and [sqlcipher3_prepare16_v2()] or the older legacy
3865 ** interface [sqlcipher3_prepare()] and [sqlcipher3_prepare16()].  The use of the
3866 ** new "v2" interface is recommended for new applications but the legacy
3867 ** interface will continue to be supported.
3868 **
3869 ** ^In the legacy interface, the return value will be either [SQLCIPHER_BUSY],
3870 ** [SQLCIPHER_DONE], [SQLCIPHER_ROW], [SQLCIPHER_ERROR], or [SQLCIPHER_MISUSE].
3871 ** ^With the "v2" interface, any of the other [result codes] or
3872 ** [extended result codes] might be returned as well.
3873 **
3874 ** ^[SQLCIPHER_BUSY] means that the database engine was unable to acquire the
3875 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3876 ** or occurs outside of an explicit transaction, then you can retry the
3877 ** statement.  If the statement is not a [COMMIT] and occurs within an
3878 ** explicit transaction then you should rollback the transaction before
3879 ** continuing.
3880 **
3881 ** ^[SQLCIPHER_DONE] means that the statement has finished executing
3882 ** successfully.  sqlcipher3_step() should not be called again on this virtual
3883 ** machine without first calling [sqlcipher3_reset()] to reset the virtual
3884 ** machine back to its initial state.
3885 **
3886 ** ^If the SQL statement being executed returns any data, then [SQLCIPHER_ROW]
3887 ** is returned each time a new row of data is ready for processing by the
3888 ** caller. The values may be accessed using the [column access functions].
3889 ** sqlcipher3_step() is called again to retrieve the next row of data.
3890 **
3891 ** ^[SQLCIPHER_ERROR] means that a run-time error (such as a constraint
3892 ** violation) has occurred.  sqlcipher3_step() should not be called again on
3893 ** the VM. More information may be found by calling [sqlcipher3_errmsg()].
3894 ** ^With the legacy interface, a more specific error code (for example,
3895 ** [SQLCIPHER_INTERRUPT], [SQLCIPHER_SCHEMA], [SQLCIPHER_CORRUPT], and so forth)
3896 ** can be obtained by calling [sqlcipher3_reset()] on the
3897 ** [prepared statement].  ^In the "v2" interface,
3898 ** the more specific error code is returned directly by sqlcipher3_step().
3899 **
3900 ** [SQLCIPHER_MISUSE] means that the this routine was called inappropriately.
3901 ** Perhaps it was called on a [prepared statement] that has
3902 ** already been [sqlcipher3_finalize | finalized] or on one that had
3903 ** previously returned [SQLCIPHER_ERROR] or [SQLCIPHER_DONE].  Or it could
3904 ** be the case that the same database connection is being used by two or
3905 ** more threads at the same moment in time.
3906 **
3907 ** For all versions of SQLite up to and including 3.6.23.1, a call to
3908 ** [sqlcipher3_reset()] was required after sqlcipher3_step() returned anything
3909 ** other than [SQLCIPHER_ROW] before any subsequent invocation of
3910 ** sqlcipher3_step().  Failure to reset the prepared statement using 
3911 ** [sqlcipher3_reset()] would result in an [SQLCIPHER_MISUSE] return from
3912 ** sqlcipher3_step().  But after version 3.6.23.1, sqlcipher3_step() began
3913 ** calling [sqlcipher3_reset()] automatically in this circumstance rather
3914 ** than returning [SQLCIPHER_MISUSE].  This is not considered a compatibility
3915 ** break because any application that ever receives an SQLCIPHER_MISUSE error
3916 ** is broken by definition.  The [SQLCIPHER_OMIT_AUTORESET] compile-time option
3917 ** can be used to restore the legacy behavior.
3918 **
3919 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlcipher3_step()
3920 ** API always returns a generic error code, [SQLCIPHER_ERROR], following any
3921 ** error other than [SQLCIPHER_BUSY] and [SQLCIPHER_MISUSE].  You must call
3922 ** [sqlcipher3_reset()] or [sqlcipher3_finalize()] in order to find one of the
3923 ** specific [error codes] that better describes the error.
3924 ** We admit that this is a goofy design.  The problem has been fixed
3925 ** with the "v2" interface.  If you prepare all of your SQL statements
3926 ** using either [sqlcipher3_prepare_v2()] or [sqlcipher3_prepare16_v2()] instead
3927 ** of the legacy [sqlcipher3_prepare()] and [sqlcipher3_prepare16()] interfaces,
3928 ** then the more specific [error codes] are returned directly
3929 ** by sqlcipher3_step().  The use of the "v2" interface is recommended.
3930 */
3931 SQLCIPHER_API int sqlcipher3_step(sqlcipher3_stmt*);
3932
3933 /*
3934 ** CAPI3REF: Number of columns in a result set
3935 **
3936 ** ^The sqlcipher3_data_count(P) interface returns the number of columns in the
3937 ** current row of the result set of [prepared statement] P.
3938 ** ^If prepared statement P does not have results ready to return
3939 ** (via calls to the [sqlcipher3_column_int | sqlcipher3_column_*()] of
3940 ** interfaces) then sqlcipher3_data_count(P) returns 0.
3941 ** ^The sqlcipher3_data_count(P) routine also returns 0 if P is a NULL pointer.
3942 ** ^The sqlcipher3_data_count(P) routine returns 0 if the previous call to
3943 ** [sqlcipher3_step](P) returned [SQLCIPHER_DONE].  ^The sqlcipher3_data_count(P)
3944 ** will return non-zero if previous call to [sqlcipher3_step](P) returned
3945 ** [SQLCIPHER_ROW], except in the case of the [PRAGMA incremental_vacuum]
3946 ** where it always returns zero since each step of that multi-step
3947 ** pragma returns 0 columns of data.
3948 **
3949 ** See also: [sqlcipher3_column_count()]
3950 */
3951 SQLCIPHER_API int sqlcipher3_data_count(sqlcipher3_stmt *pStmt);
3952
3953 /*
3954 ** CAPI3REF: Fundamental Datatypes
3955 ** KEYWORDS: SQLCIPHER_TEXT
3956 **
3957 ** ^(Every value in SQLite has one of five fundamental datatypes:
3958 **
3959 ** <ul>
3960 ** <li> 64-bit signed integer
3961 ** <li> 64-bit IEEE floating point number
3962 ** <li> string
3963 ** <li> BLOB
3964 ** <li> NULL
3965 ** </ul>)^
3966 **
3967 ** These constants are codes for each of those types.
3968 **
3969 ** Note that the SQLCIPHER_TEXT constant was also used in SQLite version 2
3970 ** for a completely different meaning.  Software that links against both
3971 ** SQLite version 2 and SQLite version 3 should use SQLCIPHER3_TEXT, not
3972 ** SQLCIPHER_TEXT.
3973 */
3974 #define SQLCIPHER_INTEGER  1
3975 #define SQLCIPHER_FLOAT    2
3976 #define SQLCIPHER_BLOB     4
3977 #define SQLCIPHER_NULL     5
3978 #ifdef SQLCIPHER_TEXT
3979 # undef SQLCIPHER_TEXT
3980 #else
3981 # define SQLCIPHER_TEXT     3
3982 #endif
3983 #define SQLCIPHER3_TEXT     3
3984
3985 /*
3986 ** CAPI3REF: Result Values From A Query
3987 ** KEYWORDS: {column access functions}
3988 **
3989 ** These routines form the "result set" interface.
3990 **
3991 ** ^These routines return information about a single column of the current
3992 ** result row of a query.  ^In every case the first argument is a pointer
3993 ** to the [prepared statement] that is being evaluated (the [sqlcipher3_stmt*]
3994 ** that was returned from [sqlcipher3_prepare_v2()] or one of its variants)
3995 ** and the second argument is the index of the column for which information
3996 ** should be returned. ^The leftmost column of the result set has the index 0.
3997 ** ^The number of columns in the result can be determined using
3998 ** [sqlcipher3_column_count()].
3999 **
4000 ** If the SQL statement does not currently point to a valid row, or if the
4001 ** column index is out of range, the result is undefined.
4002 ** These routines may only be called when the most recent call to
4003 ** [sqlcipher3_step()] has returned [SQLCIPHER_ROW] and neither
4004 ** [sqlcipher3_reset()] nor [sqlcipher3_finalize()] have been called subsequently.
4005 ** If any of these routines are called after [sqlcipher3_reset()] or
4006 ** [sqlcipher3_finalize()] or after [sqlcipher3_step()] has returned
4007 ** something other than [SQLCIPHER_ROW], the results are undefined.
4008 ** If [sqlcipher3_step()] or [sqlcipher3_reset()] or [sqlcipher3_finalize()]
4009 ** are called from a different thread while any of these routines
4010 ** are pending, then the results are undefined.
4011 **
4012 ** ^The sqlcipher3_column_type() routine returns the
4013 ** [SQLCIPHER_INTEGER | datatype code] for the initial data type
4014 ** of the result column.  ^The returned value is one of [SQLCIPHER_INTEGER],
4015 ** [SQLCIPHER_FLOAT], [SQLCIPHER_TEXT], [SQLCIPHER_BLOB], or [SQLCIPHER_NULL].  The value
4016 ** returned by sqlcipher3_column_type() is only meaningful if no type
4017 ** conversions have occurred as described below.  After a type conversion,
4018 ** the value returned by sqlcipher3_column_type() is undefined.  Future
4019 ** versions of SQLite may change the behavior of sqlcipher3_column_type()
4020 ** following a type conversion.
4021 **
4022 ** ^If the result is a BLOB or UTF-8 string then the sqlcipher3_column_bytes()
4023 ** routine returns the number of bytes in that BLOB or string.
4024 ** ^If the result is a UTF-16 string, then sqlcipher3_column_bytes() converts
4025 ** the string to UTF-8 and then returns the number of bytes.
4026 ** ^If the result is a numeric value then sqlcipher3_column_bytes() uses
4027 ** [sqlcipher3_snprintf()] to convert that value to a UTF-8 string and returns
4028 ** the number of bytes in that string.
4029 ** ^If the result is NULL, then sqlcipher3_column_bytes() returns zero.
4030 **
4031 ** ^If the result is a BLOB or UTF-16 string then the sqlcipher3_column_bytes16()
4032 ** routine returns the number of bytes in that BLOB or string.
4033 ** ^If the result is a UTF-8 string, then sqlcipher3_column_bytes16() converts
4034 ** the string to UTF-16 and then returns the number of bytes.
4035 ** ^If the result is a numeric value then sqlcipher3_column_bytes16() uses
4036 ** [sqlcipher3_snprintf()] to convert that value to a UTF-16 string and returns
4037 ** the number of bytes in that string.
4038 ** ^If the result is NULL, then sqlcipher3_column_bytes16() returns zero.
4039 **
4040 ** ^The values returned by [sqlcipher3_column_bytes()] and 
4041 ** [sqlcipher3_column_bytes16()] do not include the zero terminators at the end
4042 ** of the string.  ^For clarity: the values returned by
4043 ** [sqlcipher3_column_bytes()] and [sqlcipher3_column_bytes16()] are the number of
4044 ** bytes in the string, not the number of characters.
4045 **
4046 ** ^Strings returned by sqlcipher3_column_text() and sqlcipher3_column_text16(),
4047 ** even empty strings, are always zero terminated.  ^The return
4048 ** value from sqlcipher3_column_blob() for a zero-length BLOB is a NULL pointer.
4049 **
4050 ** ^The object returned by [sqlcipher3_column_value()] is an
4051 ** [unprotected sqlcipher3_value] object.  An unprotected sqlcipher3_value object
4052 ** may only be used with [sqlcipher3_bind_value()] and [sqlcipher3_result_value()].
4053 ** If the [unprotected sqlcipher3_value] object returned by
4054 ** [sqlcipher3_column_value()] is used in any other way, including calls
4055 ** to routines like [sqlcipher3_value_int()], [sqlcipher3_value_text()],
4056 ** or [sqlcipher3_value_bytes()], then the behavior is undefined.
4057 **
4058 ** These routines attempt to convert the value where appropriate.  ^For
4059 ** example, if the internal representation is FLOAT and a text result
4060 ** is requested, [sqlcipher3_snprintf()] is used internally to perform the
4061 ** conversion automatically.  ^(The following table details the conversions
4062 ** that are applied:
4063 **
4064 ** <blockquote>
4065 ** <table border="1">
4066 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4067 **
4068 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4069 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4070 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4071 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4072 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4073 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4074 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4075 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4076 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4077 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4078 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4079 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4080 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4081 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4082 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4083 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4084 ** </table>
4085 ** </blockquote>)^
4086 **
4087 ** The table above makes reference to standard C library functions atoi()
4088 ** and atof().  SQLite does not really use these functions.  It has its
4089 ** own equivalent internal routines.  The atoi() and atof() names are
4090 ** used in the table for brevity and because they are familiar to most
4091 ** C programmers.
4092 **
4093 ** Note that when type conversions occur, pointers returned by prior
4094 ** calls to sqlcipher3_column_blob(), sqlcipher3_column_text(), and/or
4095 ** sqlcipher3_column_text16() may be invalidated.
4096 ** Type conversions and pointer invalidations might occur
4097 ** in the following cases:
4098 **
4099 ** <ul>
4100 ** <li> The initial content is a BLOB and sqlcipher3_column_text() or
4101 **      sqlcipher3_column_text16() is called.  A zero-terminator might
4102 **      need to be added to the string.</li>
4103 ** <li> The initial content is UTF-8 text and sqlcipher3_column_bytes16() or
4104 **      sqlcipher3_column_text16() is called.  The content must be converted
4105 **      to UTF-16.</li>
4106 ** <li> The initial content is UTF-16 text and sqlcipher3_column_bytes() or
4107 **      sqlcipher3_column_text() is called.  The content must be converted
4108 **      to UTF-8.</li>
4109 ** </ul>
4110 **
4111 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4112 ** not invalidate a prior pointer, though of course the content of the buffer
4113 ** that the prior pointer references will have been modified.  Other kinds
4114 ** of conversion are done in place when it is possible, but sometimes they
4115 ** are not possible and in those cases prior pointers are invalidated.
4116 **
4117 ** The safest and easiest to remember policy is to invoke these routines
4118 ** in one of the following ways:
4119 **
4120 ** <ul>
4121 **  <li>sqlcipher3_column_text() followed by sqlcipher3_column_bytes()</li>
4122 **  <li>sqlcipher3_column_blob() followed by sqlcipher3_column_bytes()</li>
4123 **  <li>sqlcipher3_column_text16() followed by sqlcipher3_column_bytes16()</li>
4124 ** </ul>
4125 **
4126 ** In other words, you should call sqlcipher3_column_text(),
4127 ** sqlcipher3_column_blob(), or sqlcipher3_column_text16() first to force the result
4128 ** into the desired format, then invoke sqlcipher3_column_bytes() or
4129 ** sqlcipher3_column_bytes16() to find the size of the result.  Do not mix calls
4130 ** to sqlcipher3_column_text() or sqlcipher3_column_blob() with calls to
4131 ** sqlcipher3_column_bytes16(), and do not mix calls to sqlcipher3_column_text16()
4132 ** with calls to sqlcipher3_column_bytes().
4133 **
4134 ** ^The pointers returned are valid until a type conversion occurs as
4135 ** described above, or until [sqlcipher3_step()] or [sqlcipher3_reset()] or
4136 ** [sqlcipher3_finalize()] is called.  ^The memory space used to hold strings
4137 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4138 ** [sqlcipher3_column_blob()], [sqlcipher3_column_text()], etc. into
4139 ** [sqlcipher3_free()].
4140 **
4141 ** ^(If a memory allocation error occurs during the evaluation of any
4142 ** of these routines, a default value is returned.  The default value
4143 ** is either the integer 0, the floating point number 0.0, or a NULL
4144 ** pointer.  Subsequent calls to [sqlcipher3_errcode()] will return
4145 ** [SQLCIPHER_NOMEM].)^
4146 */
4147 SQLCIPHER_API const void *sqlcipher3_column_blob(sqlcipher3_stmt*, int iCol);
4148 SQLCIPHER_API int sqlcipher3_column_bytes(sqlcipher3_stmt*, int iCol);
4149 SQLCIPHER_API int sqlcipher3_column_bytes16(sqlcipher3_stmt*, int iCol);
4150 SQLCIPHER_API double sqlcipher3_column_double(sqlcipher3_stmt*, int iCol);
4151 SQLCIPHER_API int sqlcipher3_column_int(sqlcipher3_stmt*, int iCol);
4152 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_column_int64(sqlcipher3_stmt*, int iCol);
4153 SQLCIPHER_API const unsigned char *sqlcipher3_column_text(sqlcipher3_stmt*, int iCol);
4154 SQLCIPHER_API const void *sqlcipher3_column_text16(sqlcipher3_stmt*, int iCol);
4155 SQLCIPHER_API int sqlcipher3_column_type(sqlcipher3_stmt*, int iCol);
4156 SQLCIPHER_API sqlcipher3_value *sqlcipher3_column_value(sqlcipher3_stmt*, int iCol);
4157
4158 /*
4159 ** CAPI3REF: Destroy A Prepared Statement Object
4160 **
4161 ** ^The sqlcipher3_finalize() function is called to delete a [prepared statement].
4162 ** ^If the most recent evaluation of the statement encountered no errors
4163 ** or if the statement is never been evaluated, then sqlcipher3_finalize() returns
4164 ** SQLCIPHER_OK.  ^If the most recent evaluation of statement S failed, then
4165 ** sqlcipher3_finalize(S) returns the appropriate [error code] or
4166 ** [extended error code].
4167 **
4168 ** ^The sqlcipher3_finalize(S) routine can be called at any point during
4169 ** the life cycle of [prepared statement] S:
4170 ** before statement S is ever evaluated, after
4171 ** one or more calls to [sqlcipher3_reset()], or after any call
4172 ** to [sqlcipher3_step()] regardless of whether or not the statement has
4173 ** completed execution.
4174 **
4175 ** ^Invoking sqlcipher3_finalize() on a NULL pointer is a harmless no-op.
4176 **
4177 ** The application must finalize every [prepared statement] in order to avoid
4178 ** resource leaks.  It is a grievous error for the application to try to use
4179 ** a prepared statement after it has been finalized.  Any use of a prepared
4180 ** statement after it has been finalized can result in undefined and
4181 ** undesirable behavior such as segfaults and heap corruption.
4182 */
4183 SQLCIPHER_API int sqlcipher3_finalize(sqlcipher3_stmt *pStmt);
4184
4185 /*
4186 ** CAPI3REF: Reset A Prepared Statement Object
4187 **
4188 ** The sqlcipher3_reset() function is called to reset a [prepared statement]
4189 ** object back to its initial state, ready to be re-executed.
4190 ** ^Any SQL statement variables that had values bound to them using
4191 ** the [sqlcipher3_bind_blob | sqlcipher3_bind_*() API] retain their values.
4192 ** Use [sqlcipher3_clear_bindings()] to reset the bindings.
4193 **
4194 ** ^The [sqlcipher3_reset(S)] interface resets the [prepared statement] S
4195 ** back to the beginning of its program.
4196 **
4197 ** ^If the most recent call to [sqlcipher3_step(S)] for the
4198 ** [prepared statement] S returned [SQLCIPHER_ROW] or [SQLCIPHER_DONE],
4199 ** or if [sqlcipher3_step(S)] has never before been called on S,
4200 ** then [sqlcipher3_reset(S)] returns [SQLCIPHER_OK].
4201 **
4202 ** ^If the most recent call to [sqlcipher3_step(S)] for the
4203 ** [prepared statement] S indicated an error, then
4204 ** [sqlcipher3_reset(S)] returns an appropriate [error code].
4205 **
4206 ** ^The [sqlcipher3_reset(S)] interface does not change the values
4207 ** of any [sqlcipher3_bind_blob|bindings] on the [prepared statement] S.
4208 */
4209 SQLCIPHER_API int sqlcipher3_reset(sqlcipher3_stmt *pStmt);
4210
4211 /*
4212 ** CAPI3REF: Create Or Redefine SQL Functions
4213 ** KEYWORDS: {function creation routines}
4214 ** KEYWORDS: {application-defined SQL function}
4215 ** KEYWORDS: {application-defined SQL functions}
4216 **
4217 ** ^These functions (collectively known as "function creation routines")
4218 ** are used to add SQL functions or aggregates or to redefine the behavior
4219 ** of existing SQL functions or aggregates.  The only differences between
4220 ** these routines are the text encoding expected for
4221 ** the second parameter (the name of the function being created)
4222 ** and the presence or absence of a destructor callback for
4223 ** the application data pointer.
4224 **
4225 ** ^The first parameter is the [database connection] to which the SQL
4226 ** function is to be added.  ^If an application uses more than one database
4227 ** connection then application-defined SQL functions must be added
4228 ** to each database connection separately.
4229 **
4230 ** ^The second parameter is the name of the SQL function to be created or
4231 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4232 ** representation, exclusive of the zero-terminator.  ^Note that the name
4233 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
4234 ** ^Any attempt to create a function with a longer name
4235 ** will result in [SQLCIPHER_MISUSE] being returned.
4236 **
4237 ** ^The third parameter (nArg)
4238 ** is the number of arguments that the SQL function or
4239 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4240 ** aggregate may take any number of arguments between 0 and the limit
4241 ** set by [sqlcipher3_limit]([SQLCIPHER_LIMIT_FUNCTION_ARG]).  If the third
4242 ** parameter is less than -1 or greater than 127 then the behavior is
4243 ** undefined.
4244 **
4245 ** ^The fourth parameter, eTextRep, specifies what
4246 ** [SQLCIPHER_UTF8 | text encoding] this SQL function prefers for
4247 ** its parameters.  Every SQL function implementation must be able to work
4248 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4249 ** more efficient with one encoding than another.  ^An application may
4250 ** invoke sqlcipher3_create_function() or sqlcipher3_create_function16() multiple
4251 ** times with the same function but with different values of eTextRep.
4252 ** ^When multiple implementations of the same function are available, SQLite
4253 ** will pick the one that involves the least amount of data conversion.
4254 ** If there is only a single implementation which does not care what text
4255 ** encoding is used, then the fourth argument should be [SQLCIPHER_ANY].
4256 **
4257 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4258 ** function can gain access to this pointer using [sqlcipher3_user_data()].)^
4259 **
4260 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4261 ** pointers to C-language functions that implement the SQL function or
4262 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4263 ** callback only; NULL pointers must be passed as the xStep and xFinal
4264 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4265 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4266 ** SQL function or aggregate, pass NULL pointers for all three function
4267 ** callbacks.
4268 **
4269 ** ^(If the ninth parameter to sqlcipher3_create_function_v2() is not NULL,
4270 ** then it is destructor for the application data pointer. 
4271 ** The destructor is invoked when the function is deleted, either by being
4272 ** overloaded or when the database connection closes.)^
4273 ** ^The destructor is also invoked if the call to
4274 ** sqlcipher3_create_function_v2() fails.
4275 ** ^When the destructor callback of the tenth parameter is invoked, it
4276 ** is passed a single argument which is a copy of the application data 
4277 ** pointer which was the fifth parameter to sqlcipher3_create_function_v2().
4278 **
4279 ** ^It is permitted to register multiple implementations of the same
4280 ** functions with the same name but with either differing numbers of
4281 ** arguments or differing preferred text encodings.  ^SQLite will use
4282 ** the implementation that most closely matches the way in which the
4283 ** SQL function is used.  ^A function implementation with a non-negative
4284 ** nArg parameter is a better match than a function implementation with
4285 ** a negative nArg.  ^A function where the preferred text encoding
4286 ** matches the database encoding is a better
4287 ** match than a function where the encoding is different.  
4288 ** ^A function where the encoding difference is between UTF16le and UTF16be
4289 ** is a closer match than a function where the encoding difference is
4290 ** between UTF8 and UTF16.
4291 **
4292 ** ^Built-in functions may be overloaded by new application-defined functions.
4293 **
4294 ** ^An application-defined function is permitted to call other
4295 ** SQLite interfaces.  However, such calls must not
4296 ** close the database connection nor finalize or reset the prepared
4297 ** statement in which the function is running.
4298 */
4299 SQLCIPHER_API int sqlcipher3_create_function(
4300   sqlcipher3 *db,
4301   const char *zFunctionName,
4302   int nArg,
4303   int eTextRep,
4304   void *pApp,
4305   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
4306   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
4307   void (*xFinal)(sqlcipher3_context*)
4308 );
4309 SQLCIPHER_API int sqlcipher3_create_function16(
4310   sqlcipher3 *db,
4311   const void *zFunctionName,
4312   int nArg,
4313   int eTextRep,
4314   void *pApp,
4315   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
4316   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
4317   void (*xFinal)(sqlcipher3_context*)
4318 );
4319 SQLCIPHER_API int sqlcipher3_create_function_v2(
4320   sqlcipher3 *db,
4321   const char *zFunctionName,
4322   int nArg,
4323   int eTextRep,
4324   void *pApp,
4325   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
4326   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
4327   void (*xFinal)(sqlcipher3_context*),
4328   void(*xDestroy)(void*)
4329 );
4330
4331 /*
4332 ** CAPI3REF: Text Encodings
4333 **
4334 ** These constant define integer codes that represent the various
4335 ** text encodings supported by SQLite.
4336 */
4337 #define SQLCIPHER_UTF8           1
4338 #define SQLCIPHER_UTF16LE        2
4339 #define SQLCIPHER_UTF16BE        3
4340 #define SQLCIPHER_UTF16          4    /* Use native byte order */
4341 #define SQLCIPHER_ANY            5    /* sqlcipher3_create_function only */
4342 #define SQLCIPHER_UTF16_ALIGNED  8    /* sqlcipher3_create_collation only */
4343
4344 /*
4345 ** CAPI3REF: Deprecated Functions
4346 ** DEPRECATED
4347 **
4348 ** These functions are [deprecated].  In order to maintain
4349 ** backwards compatibility with older code, these functions continue 
4350 ** to be supported.  However, new applications should avoid
4351 ** the use of these functions.  To help encourage people to avoid
4352 ** using these functions, we are not going to tell you what they do.
4353 */
4354 #ifndef SQLCIPHER_OMIT_DEPRECATED
4355 SQLCIPHER_API SQLCIPHER_DEPRECATED int sqlcipher3_aggregate_count(sqlcipher3_context*);
4356 SQLCIPHER_API SQLCIPHER_DEPRECATED int sqlcipher3_expired(sqlcipher3_stmt*);
4357 SQLCIPHER_API SQLCIPHER_DEPRECATED int sqlcipher3_transfer_bindings(sqlcipher3_stmt*, sqlcipher3_stmt*);
4358 SQLCIPHER_API SQLCIPHER_DEPRECATED int sqlcipher3_global_recover(void);
4359 SQLCIPHER_API SQLCIPHER_DEPRECATED void sqlcipher3_thread_cleanup(void);
4360 SQLCIPHER_API SQLCIPHER_DEPRECATED int sqlcipher3_memory_alarm(void(*)(void*,sqlcipher3_int64,int),void*,sqlcipher3_int64);
4361 #endif
4362
4363 /*
4364 ** CAPI3REF: Obtaining SQL Function Parameter Values
4365 **
4366 ** The C-language implementation of SQL functions and aggregates uses
4367 ** this set of interface routines to access the parameter values on
4368 ** the function or aggregate.
4369 **
4370 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4371 ** to [sqlcipher3_create_function()] and [sqlcipher3_create_function16()]
4372 ** define callbacks that implement the SQL functions and aggregates.
4373 ** The 3rd parameter to these callbacks is an array of pointers to
4374 ** [protected sqlcipher3_value] objects.  There is one [sqlcipher3_value] object for
4375 ** each parameter to the SQL function.  These routines are used to
4376 ** extract values from the [sqlcipher3_value] objects.
4377 **
4378 ** These routines work only with [protected sqlcipher3_value] objects.
4379 ** Any attempt to use these routines on an [unprotected sqlcipher3_value]
4380 ** object results in undefined behavior.
4381 **
4382 ** ^These routines work just like the corresponding [column access functions]
4383 ** except that  these routines take a single [protected sqlcipher3_value] object
4384 ** pointer instead of a [sqlcipher3_stmt*] pointer and an integer column number.
4385 **
4386 ** ^The sqlcipher3_value_text16() interface extracts a UTF-16 string
4387 ** in the native byte-order of the host machine.  ^The
4388 ** sqlcipher3_value_text16be() and sqlcipher3_value_text16le() interfaces
4389 ** extract UTF-16 strings as big-endian and little-endian respectively.
4390 **
4391 ** ^(The sqlcipher3_value_numeric_type() interface attempts to apply
4392 ** numeric affinity to the value.  This means that an attempt is
4393 ** made to convert the value to an integer or floating point.  If
4394 ** such a conversion is possible without loss of information (in other
4395 ** words, if the value is a string that looks like a number)
4396 ** then the conversion is performed.  Otherwise no conversion occurs.
4397 ** The [SQLCIPHER_INTEGER | datatype] after conversion is returned.)^
4398 **
4399 ** Please pay particular attention to the fact that the pointer returned
4400 ** from [sqlcipher3_value_blob()], [sqlcipher3_value_text()], or
4401 ** [sqlcipher3_value_text16()] can be invalidated by a subsequent call to
4402 ** [sqlcipher3_value_bytes()], [sqlcipher3_value_bytes16()], [sqlcipher3_value_text()],
4403 ** or [sqlcipher3_value_text16()].
4404 **
4405 ** These routines must be called from the same thread as
4406 ** the SQL function that supplied the [sqlcipher3_value*] parameters.
4407 */
4408 SQLCIPHER_API const void *sqlcipher3_value_blob(sqlcipher3_value*);
4409 SQLCIPHER_API int sqlcipher3_value_bytes(sqlcipher3_value*);
4410 SQLCIPHER_API int sqlcipher3_value_bytes16(sqlcipher3_value*);
4411 SQLCIPHER_API double sqlcipher3_value_double(sqlcipher3_value*);
4412 SQLCIPHER_API int sqlcipher3_value_int(sqlcipher3_value*);
4413 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_value_int64(sqlcipher3_value*);
4414 SQLCIPHER_API const unsigned char *sqlcipher3_value_text(sqlcipher3_value*);
4415 SQLCIPHER_API const void *sqlcipher3_value_text16(sqlcipher3_value*);
4416 SQLCIPHER_API const void *sqlcipher3_value_text16le(sqlcipher3_value*);
4417 SQLCIPHER_API const void *sqlcipher3_value_text16be(sqlcipher3_value*);
4418 SQLCIPHER_API int sqlcipher3_value_type(sqlcipher3_value*);
4419 SQLCIPHER_API int sqlcipher3_value_numeric_type(sqlcipher3_value*);
4420
4421 /*
4422 ** CAPI3REF: Obtain Aggregate Function Context
4423 **
4424 ** Implementations of aggregate SQL functions use this
4425 ** routine to allocate memory for storing their state.
4426 **
4427 ** ^The first time the sqlcipher3_aggregate_context(C,N) routine is called 
4428 ** for a particular aggregate function, SQLite
4429 ** allocates N of memory, zeroes out that memory, and returns a pointer
4430 ** to the new memory. ^On second and subsequent calls to
4431 ** sqlcipher3_aggregate_context() for the same aggregate function instance,
4432 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4433 ** called once for each invocation of the xStep callback and then one
4434 ** last time when the xFinal callback is invoked.  ^(When no rows match
4435 ** an aggregate query, the xStep() callback of the aggregate function
4436 ** implementation is never called and xFinal() is called exactly once.
4437 ** In those cases, sqlcipher3_aggregate_context() might be called for the
4438 ** first time from within xFinal().)^
4439 **
4440 ** ^The sqlcipher3_aggregate_context(C,N) routine returns a NULL pointer if N is
4441 ** less than or equal to zero or if a memory allocate error occurs.
4442 **
4443 ** ^(The amount of space allocated by sqlcipher3_aggregate_context(C,N) is
4444 ** determined by the N parameter on first successful call.  Changing the
4445 ** value of N in subsequent call to sqlcipher3_aggregate_context() within
4446 ** the same aggregate function instance will not resize the memory
4447 ** allocation.)^
4448 **
4449 ** ^SQLite automatically frees the memory allocated by 
4450 ** sqlcipher3_aggregate_context() when the aggregate query concludes.
4451 **
4452 ** The first parameter must be a copy of the
4453 ** [sqlcipher3_context | SQL function context] that is the first parameter
4454 ** to the xStep or xFinal callback routine that implements the aggregate
4455 ** function.
4456 **
4457 ** This routine must be called from the same thread in which
4458 ** the aggregate SQL function is running.
4459 */
4460 SQLCIPHER_API void *sqlcipher3_aggregate_context(sqlcipher3_context*, int nBytes);
4461
4462 /*
4463 ** CAPI3REF: User Data For Functions
4464 **
4465 ** ^The sqlcipher3_user_data() interface returns a copy of
4466 ** the pointer that was the pUserData parameter (the 5th parameter)
4467 ** of the [sqlcipher3_create_function()]
4468 ** and [sqlcipher3_create_function16()] routines that originally
4469 ** registered the application defined function.
4470 **
4471 ** This routine must be called from the same thread in which
4472 ** the application-defined function is running.
4473 */
4474 SQLCIPHER_API void *sqlcipher3_user_data(sqlcipher3_context*);
4475
4476 /*
4477 ** CAPI3REF: Database Connection For Functions
4478 **
4479 ** ^The sqlcipher3_context_db_handle() interface returns a copy of
4480 ** the pointer to the [database connection] (the 1st parameter)
4481 ** of the [sqlcipher3_create_function()]
4482 ** and [sqlcipher3_create_function16()] routines that originally
4483 ** registered the application defined function.
4484 */
4485 SQLCIPHER_API sqlcipher3 *sqlcipher3_context_db_handle(sqlcipher3_context*);
4486
4487 /*
4488 ** CAPI3REF: Function Auxiliary Data
4489 **
4490 ** The following two functions may be used by scalar SQL functions to
4491 ** associate metadata with argument values. If the same value is passed to
4492 ** multiple invocations of the same SQL function during query execution, under
4493 ** some circumstances the associated metadata may be preserved. This may
4494 ** be used, for example, to add a regular-expression matching scalar
4495 ** function. The compiled version of the regular expression is stored as
4496 ** metadata associated with the SQL value passed as the regular expression
4497 ** pattern.  The compiled regular expression can be reused on multiple
4498 ** invocations of the same function so that the original pattern string
4499 ** does not need to be recompiled on each invocation.
4500 **
4501 ** ^The sqlcipher3_get_auxdata() interface returns a pointer to the metadata
4502 ** associated by the sqlcipher3_set_auxdata() function with the Nth argument
4503 ** value to the application-defined function. ^If no metadata has been ever
4504 ** been set for the Nth argument of the function, or if the corresponding
4505 ** function parameter has changed since the meta-data was set,
4506 ** then sqlcipher3_get_auxdata() returns a NULL pointer.
4507 **
4508 ** ^The sqlcipher3_set_auxdata() interface saves the metadata
4509 ** pointed to by its 3rd parameter as the metadata for the N-th
4510 ** argument of the application-defined function.  Subsequent
4511 ** calls to sqlcipher3_get_auxdata() might return this data, if it has
4512 ** not been destroyed.
4513 ** ^If it is not NULL, SQLite will invoke the destructor
4514 ** function given by the 4th parameter to sqlcipher3_set_auxdata() on
4515 ** the metadata when the corresponding function parameter changes
4516 ** or when the SQL statement completes, whichever comes first.
4517 **
4518 ** SQLite is free to call the destructor and drop metadata on any
4519 ** parameter of any function at any time.  ^The only guarantee is that
4520 ** the destructor will be called before the metadata is dropped.
4521 **
4522 ** ^(In practice, metadata is preserved between function calls for
4523 ** expressions that are constant at compile time. This includes literal
4524 ** values and [parameters].)^
4525 **
4526 ** These routines must be called from the same thread in which
4527 ** the SQL function is running.
4528 */
4529 SQLCIPHER_API void *sqlcipher3_get_auxdata(sqlcipher3_context*, int N);
4530 SQLCIPHER_API void sqlcipher3_set_auxdata(sqlcipher3_context*, int N, void*, void (*)(void*));
4531
4532
4533 /*
4534 ** CAPI3REF: Constants Defining Special Destructor Behavior
4535 **
4536 ** These are special values for the destructor that is passed in as the
4537 ** final argument to routines like [sqlcipher3_result_blob()].  ^If the destructor
4538 ** argument is SQLCIPHER_STATIC, it means that the content pointer is constant
4539 ** and will never change.  It does not need to be destroyed.  ^The
4540 ** SQLCIPHER_TRANSIENT value means that the content will likely change in
4541 ** the near future and that SQLite should make its own private copy of
4542 ** the content before returning.
4543 **
4544 ** The typedef is necessary to work around problems in certain
4545 ** C++ compilers.  See ticket #2191.
4546 */
4547 typedef void (*sqlcipher3_destructor_type)(void*);
4548 #define SQLCIPHER_STATIC      ((sqlcipher3_destructor_type)0)
4549 #define SQLCIPHER_TRANSIENT   ((sqlcipher3_destructor_type)-1)
4550
4551 /*
4552 ** CAPI3REF: Setting The Result Of An SQL Function
4553 **
4554 ** These routines are used by the xFunc or xFinal callbacks that
4555 ** implement SQL functions and aggregates.  See
4556 ** [sqlcipher3_create_function()] and [sqlcipher3_create_function16()]
4557 ** for additional information.
4558 **
4559 ** These functions work very much like the [parameter binding] family of
4560 ** functions used to bind values to host parameters in prepared statements.
4561 ** Refer to the [SQL parameter] documentation for additional information.
4562 **
4563 ** ^The sqlcipher3_result_blob() interface sets the result from
4564 ** an application-defined function to be the BLOB whose content is pointed
4565 ** to by the second parameter and which is N bytes long where N is the
4566 ** third parameter.
4567 **
4568 ** ^The sqlcipher3_result_zeroblob() interfaces set the result of
4569 ** the application-defined function to be a BLOB containing all zero
4570 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4571 **
4572 ** ^The sqlcipher3_result_double() interface sets the result from
4573 ** an application-defined function to be a floating point value specified
4574 ** by its 2nd argument.
4575 **
4576 ** ^The sqlcipher3_result_error() and sqlcipher3_result_error16() functions
4577 ** cause the implemented SQL function to throw an exception.
4578 ** ^SQLite uses the string pointed to by the
4579 ** 2nd parameter of sqlcipher3_result_error() or sqlcipher3_result_error16()
4580 ** as the text of an error message.  ^SQLite interprets the error
4581 ** message string from sqlcipher3_result_error() as UTF-8. ^SQLite
4582 ** interprets the string from sqlcipher3_result_error16() as UTF-16 in native
4583 ** byte order.  ^If the third parameter to sqlcipher3_result_error()
4584 ** or sqlcipher3_result_error16() is negative then SQLite takes as the error
4585 ** message all text up through the first zero character.
4586 ** ^If the third parameter to sqlcipher3_result_error() or
4587 ** sqlcipher3_result_error16() is non-negative then SQLite takes that many
4588 ** bytes (not characters) from the 2nd parameter as the error message.
4589 ** ^The sqlcipher3_result_error() and sqlcipher3_result_error16()
4590 ** routines make a private copy of the error message text before
4591 ** they return.  Hence, the calling function can deallocate or
4592 ** modify the text after they return without harm.
4593 ** ^The sqlcipher3_result_error_code() function changes the error code
4594 ** returned by SQLite as a result of an error in a function.  ^By default,
4595 ** the error code is SQLCIPHER_ERROR.  ^A subsequent call to sqlcipher3_result_error()
4596 ** or sqlcipher3_result_error16() resets the error code to SQLCIPHER_ERROR.
4597 **
4598 ** ^The sqlcipher3_result_toobig() interface causes SQLite to throw an error
4599 ** indicating that a string or BLOB is too long to represent.
4600 **
4601 ** ^The sqlcipher3_result_nomem() interface causes SQLite to throw an error
4602 ** indicating that a memory allocation failed.
4603 **
4604 ** ^The sqlcipher3_result_int() interface sets the return value
4605 ** of the application-defined function to be the 32-bit signed integer
4606 ** value given in the 2nd argument.
4607 ** ^The sqlcipher3_result_int64() interface sets the return value
4608 ** of the application-defined function to be the 64-bit signed integer
4609 ** value given in the 2nd argument.
4610 **
4611 ** ^The sqlcipher3_result_null() interface sets the return value
4612 ** of the application-defined function to be NULL.
4613 **
4614 ** ^The sqlcipher3_result_text(), sqlcipher3_result_text16(),
4615 ** sqlcipher3_result_text16le(), and sqlcipher3_result_text16be() interfaces
4616 ** set the return value of the application-defined function to be
4617 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4618 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4619 ** ^SQLite takes the text result from the application from
4620 ** the 2nd parameter of the sqlcipher3_result_text* interfaces.
4621 ** ^If the 3rd parameter to the sqlcipher3_result_text* interfaces
4622 ** is negative, then SQLite takes result text from the 2nd parameter
4623 ** through the first zero character.
4624 ** ^If the 3rd parameter to the sqlcipher3_result_text* interfaces
4625 ** is non-negative, then as many bytes (not characters) of the text
4626 ** pointed to by the 2nd parameter are taken as the application-defined
4627 ** function result.  If the 3rd parameter is non-negative, then it
4628 ** must be the byte offset into the string where the NUL terminator would
4629 ** appear if the string where NUL terminated.  If any NUL characters occur
4630 ** in the string at a byte offset that is less than the value of the 3rd
4631 ** parameter, then the resulting string will contain embedded NULs and the
4632 ** result of expressions operating on strings with embedded NULs is undefined.
4633 ** ^If the 4th parameter to the sqlcipher3_result_text* interfaces
4634 ** or sqlcipher3_result_blob is a non-NULL pointer, then SQLite calls that
4635 ** function as the destructor on the text or BLOB result when it has
4636 ** finished using that result.
4637 ** ^If the 4th parameter to the sqlcipher3_result_text* interfaces or to
4638 ** sqlcipher3_result_blob is the special constant SQLCIPHER_STATIC, then SQLite
4639 ** assumes that the text or BLOB result is in constant space and does not
4640 ** copy the content of the parameter nor call a destructor on the content
4641 ** when it has finished using that result.
4642 ** ^If the 4th parameter to the sqlcipher3_result_text* interfaces
4643 ** or sqlcipher3_result_blob is the special constant SQLCIPHER_TRANSIENT
4644 ** then SQLite makes a copy of the result into space obtained from
4645 ** from [sqlcipher3_malloc()] before it returns.
4646 **
4647 ** ^The sqlcipher3_result_value() interface sets the result of
4648 ** the application-defined function to be a copy the
4649 ** [unprotected sqlcipher3_value] object specified by the 2nd parameter.  ^The
4650 ** sqlcipher3_result_value() interface makes a copy of the [sqlcipher3_value]
4651 ** so that the [sqlcipher3_value] specified in the parameter may change or
4652 ** be deallocated after sqlcipher3_result_value() returns without harm.
4653 ** ^A [protected sqlcipher3_value] object may always be used where an
4654 ** [unprotected sqlcipher3_value] object is required, so either
4655 ** kind of [sqlcipher3_value] object can be used with this interface.
4656 **
4657 ** If these routines are called from within the different thread
4658 ** than the one containing the application-defined function that received
4659 ** the [sqlcipher3_context] pointer, the results are undefined.
4660 */
4661 SQLCIPHER_API void sqlcipher3_result_blob(sqlcipher3_context*, const void*, int, void(*)(void*));
4662 SQLCIPHER_API void sqlcipher3_result_double(sqlcipher3_context*, double);
4663 SQLCIPHER_API void sqlcipher3_result_error(sqlcipher3_context*, const char*, int);
4664 SQLCIPHER_API void sqlcipher3_result_error16(sqlcipher3_context*, const void*, int);
4665 SQLCIPHER_API void sqlcipher3_result_error_toobig(sqlcipher3_context*);
4666 SQLCIPHER_API void sqlcipher3_result_error_nomem(sqlcipher3_context*);
4667 SQLCIPHER_API void sqlcipher3_result_error_code(sqlcipher3_context*, int);
4668 SQLCIPHER_API void sqlcipher3_result_int(sqlcipher3_context*, int);
4669 SQLCIPHER_API void sqlcipher3_result_int64(sqlcipher3_context*, sqlcipher3_int64);
4670 SQLCIPHER_API void sqlcipher3_result_null(sqlcipher3_context*);
4671 SQLCIPHER_API void sqlcipher3_result_text(sqlcipher3_context*, const char*, int, void(*)(void*));
4672 SQLCIPHER_API void sqlcipher3_result_text16(sqlcipher3_context*, const void*, int, void(*)(void*));
4673 SQLCIPHER_API void sqlcipher3_result_text16le(sqlcipher3_context*, const void*, int,void(*)(void*));
4674 SQLCIPHER_API void sqlcipher3_result_text16be(sqlcipher3_context*, const void*, int,void(*)(void*));
4675 SQLCIPHER_API void sqlcipher3_result_value(sqlcipher3_context*, sqlcipher3_value*);
4676 SQLCIPHER_API void sqlcipher3_result_zeroblob(sqlcipher3_context*, int n);
4677
4678 /*
4679 ** CAPI3REF: Define New Collating Sequences
4680 **
4681 ** ^These functions add, remove, or modify a [collation] associated
4682 ** with the [database connection] specified as the first argument.
4683 **
4684 ** ^The name of the collation is a UTF-8 string
4685 ** for sqlcipher3_create_collation() and sqlcipher3_create_collation_v2()
4686 ** and a UTF-16 string in native byte order for sqlcipher3_create_collation16().
4687 ** ^Collation names that compare equal according to [sqlcipher3_strnicmp()] are
4688 ** considered to be the same name.
4689 **
4690 ** ^(The third argument (eTextRep) must be one of the constants:
4691 ** <ul>
4692 ** <li> [SQLCIPHER_UTF8],
4693 ** <li> [SQLCIPHER_UTF16LE],
4694 ** <li> [SQLCIPHER_UTF16BE],
4695 ** <li> [SQLCIPHER_UTF16], or
4696 ** <li> [SQLCIPHER_UTF16_ALIGNED].
4697 ** </ul>)^
4698 ** ^The eTextRep argument determines the encoding of strings passed
4699 ** to the collating function callback, xCallback.
4700 ** ^The [SQLCIPHER_UTF16] and [SQLCIPHER_UTF16_ALIGNED] values for eTextRep
4701 ** force strings to be UTF16 with native byte order.
4702 ** ^The [SQLCIPHER_UTF16_ALIGNED] value for eTextRep forces strings to begin
4703 ** on an even byte address.
4704 **
4705 ** ^The fourth argument, pArg, is an application data pointer that is passed
4706 ** through as the first argument to the collating function callback.
4707 **
4708 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4709 ** ^Multiple collating functions can be registered using the same name but
4710 ** with different eTextRep parameters and SQLite will use whichever
4711 ** function requires the least amount of data transformation.
4712 ** ^If the xCallback argument is NULL then the collating function is
4713 ** deleted.  ^When all collating functions having the same name are deleted,
4714 ** that collation is no longer usable.
4715 **
4716 ** ^The collating function callback is invoked with a copy of the pArg 
4717 ** application data pointer and with two strings in the encoding specified
4718 ** by the eTextRep argument.  The collating function must return an
4719 ** integer that is negative, zero, or positive
4720 ** if the first string is less than, equal to, or greater than the second,
4721 ** respectively.  A collating function must always return the same answer
4722 ** given the same inputs.  If two or more collating functions are registered
4723 ** to the same collation name (using different eTextRep values) then all
4724 ** must give an equivalent answer when invoked with equivalent strings.
4725 ** The collating function must obey the following properties for all
4726 ** strings A, B, and C:
4727 **
4728 ** <ol>
4729 ** <li> If A==B then B==A.
4730 ** <li> If A==B and B==C then A==C.
4731 ** <li> If A&lt;B THEN B&gt;A.
4732 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4733 ** </ol>
4734 **
4735 ** If a collating function fails any of the above constraints and that
4736 ** collating function is  registered and used, then the behavior of SQLite
4737 ** is undefined.
4738 **
4739 ** ^The sqlcipher3_create_collation_v2() works like sqlcipher3_create_collation()
4740 ** with the addition that the xDestroy callback is invoked on pArg when
4741 ** the collating function is deleted.
4742 ** ^Collating functions are deleted when they are overridden by later
4743 ** calls to the collation creation functions or when the
4744 ** [database connection] is closed using [sqlcipher3_close()].
4745 **
4746 ** ^The xDestroy callback is <u>not</u> called if the 
4747 ** sqlcipher3_create_collation_v2() function fails.  Applications that invoke
4748 ** sqlcipher3_create_collation_v2() with a non-NULL xDestroy argument should 
4749 ** check the return code and dispose of the application data pointer
4750 ** themselves rather than expecting SQLite to deal with it for them.
4751 ** This is different from every other SQLite interface.  The inconsistency 
4752 ** is unfortunate but cannot be changed without breaking backwards 
4753 ** compatibility.
4754 **
4755 ** See also:  [sqlcipher3_collation_needed()] and [sqlcipher3_collation_needed16()].
4756 */
4757 SQLCIPHER_API int sqlcipher3_create_collation(
4758   sqlcipher3*, 
4759   const char *zName, 
4760   int eTextRep, 
4761   void *pArg,
4762   int(*xCompare)(void*,int,const void*,int,const void*)
4763 );
4764 SQLCIPHER_API int sqlcipher3_create_collation_v2(
4765   sqlcipher3*, 
4766   const char *zName, 
4767   int eTextRep, 
4768   void *pArg,
4769   int(*xCompare)(void*,int,const void*,int,const void*),
4770   void(*xDestroy)(void*)
4771 );
4772 SQLCIPHER_API int sqlcipher3_create_collation16(
4773   sqlcipher3*, 
4774   const void *zName,
4775   int eTextRep, 
4776   void *pArg,
4777   int(*xCompare)(void*,int,const void*,int,const void*)
4778 );
4779
4780 /*
4781 ** CAPI3REF: Collation Needed Callbacks
4782 **
4783 ** ^To avoid having to register all collation sequences before a database
4784 ** can be used, a single callback function may be registered with the
4785 ** [database connection] to be invoked whenever an undefined collation
4786 ** sequence is required.
4787 **
4788 ** ^If the function is registered using the sqlcipher3_collation_needed() API,
4789 ** then it is passed the names of undefined collation sequences as strings
4790 ** encoded in UTF-8. ^If sqlcipher3_collation_needed16() is used,
4791 ** the names are passed as UTF-16 in machine native byte order.
4792 ** ^A call to either function replaces the existing collation-needed callback.
4793 **
4794 ** ^(When the callback is invoked, the first argument passed is a copy
4795 ** of the second argument to sqlcipher3_collation_needed() or
4796 ** sqlcipher3_collation_needed16().  The second argument is the database
4797 ** connection.  The third argument is one of [SQLCIPHER_UTF8], [SQLCIPHER_UTF16BE],
4798 ** or [SQLCIPHER_UTF16LE], indicating the most desirable form of the collation
4799 ** sequence function required.  The fourth parameter is the name of the
4800 ** required collation sequence.)^
4801 **
4802 ** The callback function should register the desired collation using
4803 ** [sqlcipher3_create_collation()], [sqlcipher3_create_collation16()], or
4804 ** [sqlcipher3_create_collation_v2()].
4805 */
4806 SQLCIPHER_API int sqlcipher3_collation_needed(
4807   sqlcipher3*, 
4808   void*, 
4809   void(*)(void*,sqlcipher3*,int eTextRep,const char*)
4810 );
4811 SQLCIPHER_API int sqlcipher3_collation_needed16(
4812   sqlcipher3*, 
4813   void*,
4814   void(*)(void*,sqlcipher3*,int eTextRep,const void*)
4815 );
4816
4817 #ifdef SQLCIPHER_HAS_CODEC
4818 /*
4819 ** Specify the key for an encrypted database.  This routine should be
4820 ** called right after sqlcipher3_open().
4821 **
4822 ** The code to implement this API is not available in the public release
4823 ** of SQLite.
4824 */
4825 SQLCIPHER_API int sqlcipher3_key(
4826   sqlcipher3 *db,                   /* Database to be rekeyed */
4827   const void *pKey, int nKey     /* The key */
4828 );
4829
4830 /*
4831 ** Change the key on an open database.  If the current database is not
4832 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4833 ** database is decrypted.
4834 **
4835 ** The code to implement this API is not available in the public release
4836 ** of SQLite.
4837 */
4838 SQLCIPHER_API int sqlcipher3_rekey(
4839   sqlcipher3 *db,                   /* Database to be rekeyed */
4840   const void *pKey, int nKey     /* The new key */
4841 );
4842
4843 /*
4844 ** Specify the activation key for a SEE database.  Unless 
4845 ** activated, none of the SEE routines will work.
4846 */
4847 SQLCIPHER_API void sqlcipher3_activate_see(
4848   const char *zPassPhrase        /* Activation phrase */
4849 );
4850 #endif
4851
4852 #ifdef SQLCIPHER_ENABLE_CEROD
4853 /*
4854 ** Specify the activation key for a CEROD database.  Unless 
4855 ** activated, none of the CEROD routines will work.
4856 */
4857 SQLCIPHER_API void sqlcipher3_activate_cerod(
4858   const char *zPassPhrase        /* Activation phrase */
4859 );
4860 #endif
4861
4862 /*
4863 ** CAPI3REF: Suspend Execution For A Short Time
4864 **
4865 ** The sqlcipher3_sleep() function causes the current thread to suspend execution
4866 ** for at least a number of milliseconds specified in its parameter.
4867 **
4868 ** If the operating system does not support sleep requests with
4869 ** millisecond time resolution, then the time will be rounded up to
4870 ** the nearest second. The number of milliseconds of sleep actually
4871 ** requested from the operating system is returned.
4872 **
4873 ** ^SQLite implements this interface by calling the xSleep()
4874 ** method of the default [sqlcipher3_vfs] object.  If the xSleep() method
4875 ** of the default VFS is not implemented correctly, or not implemented at
4876 ** all, then the behavior of sqlcipher3_sleep() may deviate from the description
4877 ** in the previous paragraphs.
4878 */
4879 SQLCIPHER_API int sqlcipher3_sleep(int);
4880
4881 /*
4882 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4883 **
4884 ** ^(If this global variable is made to point to a string which is
4885 ** the name of a folder (a.k.a. directory), then all temporary files
4886 ** created by SQLite when using a built-in [sqlcipher3_vfs | VFS]
4887 ** will be placed in that directory.)^  ^If this variable
4888 ** is a NULL pointer, then SQLite performs a search for an appropriate
4889 ** temporary file directory.
4890 **
4891 ** It is not safe to read or modify this variable in more than one
4892 ** thread at a time.  It is not safe to read or modify this variable
4893 ** if a [database connection] is being used at the same time in a separate
4894 ** thread.
4895 ** It is intended that this variable be set once
4896 ** as part of process initialization and before any SQLite interface
4897 ** routines have been called and that this variable remain unchanged
4898 ** thereafter.
4899 **
4900 ** ^The [temp_store_directory pragma] may modify this variable and cause
4901 ** it to point to memory obtained from [sqlcipher3_malloc].  ^Furthermore,
4902 ** the [temp_store_directory pragma] always assumes that any string
4903 ** that this variable points to is held in memory obtained from 
4904 ** [sqlcipher3_malloc] and the pragma may attempt to free that memory
4905 ** using [sqlcipher3_free].
4906 ** Hence, if this variable is modified directly, either it should be
4907 ** made NULL or made to point to memory obtained from [sqlcipher3_malloc]
4908 ** or else the use of the [temp_store_directory pragma] should be avoided.
4909 */
4910 SQLCIPHER_API char *sqlcipher3_temp_directory;
4911
4912 /*
4913 ** CAPI3REF: Test For Auto-Commit Mode
4914 ** KEYWORDS: {autocommit mode}
4915 **
4916 ** ^The sqlcipher3_get_autocommit() interface returns non-zero or
4917 ** zero if the given database connection is or is not in autocommit mode,
4918 ** respectively.  ^Autocommit mode is on by default.
4919 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4920 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4921 **
4922 ** If certain kinds of errors occur on a statement within a multi-statement
4923 ** transaction (errors including [SQLCIPHER_FULL], [SQLCIPHER_IOERR],
4924 ** [SQLCIPHER_NOMEM], [SQLCIPHER_BUSY], and [SQLCIPHER_INTERRUPT]) then the
4925 ** transaction might be rolled back automatically.  The only way to
4926 ** find out whether SQLite automatically rolled back the transaction after
4927 ** an error is to use this function.
4928 **
4929 ** If another thread changes the autocommit status of the database
4930 ** connection while this routine is running, then the return value
4931 ** is undefined.
4932 */
4933 SQLCIPHER_API int sqlcipher3_get_autocommit(sqlcipher3*);
4934
4935 /*
4936 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4937 **
4938 ** ^The sqlcipher3_db_handle interface returns the [database connection] handle
4939 ** to which a [prepared statement] belongs.  ^The [database connection]
4940 ** returned by sqlcipher3_db_handle is the same [database connection]
4941 ** that was the first argument
4942 ** to the [sqlcipher3_prepare_v2()] call (or its variants) that was used to
4943 ** create the statement in the first place.
4944 */
4945 SQLCIPHER_API sqlcipher3 *sqlcipher3_db_handle(sqlcipher3_stmt*);
4946
4947 /*
4948 ** CAPI3REF: Find the next prepared statement
4949 **
4950 ** ^This interface returns a pointer to the next [prepared statement] after
4951 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4952 ** then this interface returns a pointer to the first prepared statement
4953 ** associated with the database connection pDb.  ^If no prepared statement
4954 ** satisfies the conditions of this routine, it returns NULL.
4955 **
4956 ** The [database connection] pointer D in a call to
4957 ** [sqlcipher3_next_stmt(D,S)] must refer to an open database
4958 ** connection and in particular must not be a NULL pointer.
4959 */
4960 SQLCIPHER_API sqlcipher3_stmt *sqlcipher3_next_stmt(sqlcipher3 *pDb, sqlcipher3_stmt *pStmt);
4961
4962 /*
4963 ** CAPI3REF: Commit And Rollback Notification Callbacks
4964 **
4965 ** ^The sqlcipher3_commit_hook() interface registers a callback
4966 ** function to be invoked whenever a transaction is [COMMIT | committed].
4967 ** ^Any callback set by a previous call to sqlcipher3_commit_hook()
4968 ** for the same database connection is overridden.
4969 ** ^The sqlcipher3_rollback_hook() interface registers a callback
4970 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4971 ** ^Any callback set by a previous call to sqlcipher3_rollback_hook()
4972 ** for the same database connection is overridden.
4973 ** ^The pArg argument is passed through to the callback.
4974 ** ^If the callback on a commit hook function returns non-zero,
4975 ** then the commit is converted into a rollback.
4976 **
4977 ** ^The sqlcipher3_commit_hook(D,C,P) and sqlcipher3_rollback_hook(D,C,P) functions
4978 ** return the P argument from the previous call of the same function
4979 ** on the same [database connection] D, or NULL for
4980 ** the first call for each function on D.
4981 **
4982 ** The callback implementation must not do anything that will modify
4983 ** the database connection that invoked the callback.  Any actions
4984 ** to modify the database connection must be deferred until after the
4985 ** completion of the [sqlcipher3_step()] call that triggered the commit
4986 ** or rollback hook in the first place.
4987 ** Note that [sqlcipher3_prepare_v2()] and [sqlcipher3_step()] both modify their
4988 ** database connections for the meaning of "modify" in this paragraph.
4989 **
4990 ** ^Registering a NULL function disables the callback.
4991 **
4992 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4993 ** operation is allowed to continue normally.  ^If the commit hook
4994 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4995 ** ^The rollback hook is invoked on a rollback that results from a commit
4996 ** hook returning non-zero, just as it would be with any other rollback.
4997 **
4998 ** ^For the purposes of this API, a transaction is said to have been
4999 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5000 ** an error or constraint causes an implicit rollback to occur.
5001 ** ^The rollback callback is not invoked if a transaction is
5002 ** automatically rolled back because the database connection is closed.
5003 **
5004 ** See also the [sqlcipher3_update_hook()] interface.
5005 */
5006 SQLCIPHER_API void *sqlcipher3_commit_hook(sqlcipher3*, int(*)(void*), void*);
5007 SQLCIPHER_API void *sqlcipher3_rollback_hook(sqlcipher3*, void(*)(void *), void*);
5008
5009 /*
5010 ** CAPI3REF: Data Change Notification Callbacks
5011 **
5012 ** ^The sqlcipher3_update_hook() interface registers a callback function
5013 ** with the [database connection] identified by the first argument
5014 ** to be invoked whenever a row is updated, inserted or deleted.
5015 ** ^Any callback set by a previous call to this function
5016 ** for the same database connection is overridden.
5017 **
5018 ** ^The second argument is a pointer to the function to invoke when a
5019 ** row is updated, inserted or deleted.
5020 ** ^The first argument to the callback is a copy of the third argument
5021 ** to sqlcipher3_update_hook().
5022 ** ^The second callback argument is one of [SQLCIPHER_INSERT], [SQLCIPHER_DELETE],
5023 ** or [SQLCIPHER_UPDATE], depending on the operation that caused the callback
5024 ** to be invoked.
5025 ** ^The third and fourth arguments to the callback contain pointers to the
5026 ** database and table name containing the affected row.
5027 ** ^The final callback parameter is the [rowid] of the row.
5028 ** ^In the case of an update, this is the [rowid] after the update takes place.
5029 **
5030 ** ^(The update hook is not invoked when internal system tables are
5031 ** modified (i.e. sqlcipher_master and sqlcipher_sequence).)^
5032 **
5033 ** ^In the current implementation, the update hook
5034 ** is not invoked when duplication rows are deleted because of an
5035 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5036 ** invoked when rows are deleted using the [truncate optimization].
5037 ** The exceptions defined in this paragraph might change in a future
5038 ** release of SQLite.
5039 **
5040 ** The update hook implementation must not do anything that will modify
5041 ** the database connection that invoked the update hook.  Any actions
5042 ** to modify the database connection must be deferred until after the
5043 ** completion of the [sqlcipher3_step()] call that triggered the update hook.
5044 ** Note that [sqlcipher3_prepare_v2()] and [sqlcipher3_step()] both modify their
5045 ** database connections for the meaning of "modify" in this paragraph.
5046 **
5047 ** ^The sqlcipher3_update_hook(D,C,P) function
5048 ** returns the P argument from the previous call
5049 ** on the same [database connection] D, or NULL for
5050 ** the first call on D.
5051 **
5052 ** See also the [sqlcipher3_commit_hook()] and [sqlcipher3_rollback_hook()]
5053 ** interfaces.
5054 */
5055 SQLCIPHER_API void *sqlcipher3_update_hook(
5056   sqlcipher3*, 
5057   void(*)(void *,int ,char const *,char const *,sqlcipher3_int64),
5058   void*
5059 );
5060
5061 /*
5062 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5063 ** KEYWORDS: {shared cache}
5064 **
5065 ** ^(This routine enables or disables the sharing of the database cache
5066 ** and schema data structures between [database connection | connections]
5067 ** to the same database. Sharing is enabled if the argument is true
5068 ** and disabled if the argument is false.)^
5069 **
5070 ** ^Cache sharing is enabled and disabled for an entire process.
5071 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5072 ** sharing was enabled or disabled for each thread separately.
5073 **
5074 ** ^(The cache sharing mode set by this interface effects all subsequent
5075 ** calls to [sqlcipher3_open()], [sqlcipher3_open_v2()], and [sqlcipher3_open16()].
5076 ** Existing database connections continue use the sharing mode
5077 ** that was in effect at the time they were opened.)^
5078 **
5079 ** ^(This routine returns [SQLCIPHER_OK] if shared cache was enabled or disabled
5080 ** successfully.  An [error code] is returned otherwise.)^
5081 **
5082 ** ^Shared cache is disabled by default. But this might change in
5083 ** future releases of SQLite.  Applications that care about shared
5084 ** cache setting should set it explicitly.
5085 **
5086 ** See Also:  [SQLite Shared-Cache Mode]
5087 */
5088 SQLCIPHER_API int sqlcipher3_enable_shared_cache(int);
5089
5090 /*
5091 ** CAPI3REF: Attempt To Free Heap Memory
5092 **
5093 ** ^The sqlcipher3_release_memory() interface attempts to free N bytes
5094 ** of heap memory by deallocating non-essential memory allocations
5095 ** held by the database library.   Memory used to cache database
5096 ** pages to improve performance is an example of non-essential memory.
5097 ** ^sqlcipher3_release_memory() returns the number of bytes actually freed,
5098 ** which might be more or less than the amount requested.
5099 ** ^The sqlcipher3_release_memory() routine is a no-op returning zero
5100 ** if SQLite is not compiled with [SQLCIPHER_ENABLE_MEMORY_MANAGEMENT].
5101 */
5102 SQLCIPHER_API int sqlcipher3_release_memory(int);
5103
5104 /*
5105 ** CAPI3REF: Impose A Limit On Heap Size
5106 **
5107 ** ^The sqlcipher3_soft_heap_limit64() interface sets and/or queries the
5108 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5109 ** ^SQLite strives to keep heap memory utilization below the soft heap
5110 ** limit by reducing the number of pages held in the page cache
5111 ** as heap memory usages approaches the limit.
5112 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5113 ** below the limit, it will exceed the limit rather than generate
5114 ** an [SQLCIPHER_NOMEM] error.  In other words, the soft heap limit 
5115 ** is advisory only.
5116 **
5117 ** ^The return value from sqlcipher3_soft_heap_limit64() is the size of
5118 ** the soft heap limit prior to the call.  ^If the argument N is negative
5119 ** then no change is made to the soft heap limit.  Hence, the current
5120 ** size of the soft heap limit can be determined by invoking
5121 ** sqlcipher3_soft_heap_limit64() with a negative argument.
5122 **
5123 ** ^If the argument N is zero then the soft heap limit is disabled.
5124 **
5125 ** ^(The soft heap limit is not enforced in the current implementation
5126 ** if one or more of following conditions are true:
5127 **
5128 ** <ul>
5129 ** <li> The soft heap limit is set to zero.
5130 ** <li> Memory accounting is disabled using a combination of the
5131 **      [sqlcipher3_config]([SQLCIPHER_CONFIG_MEMSTATUS],...) start-time option and
5132 **      the [SQLCIPHER_DEFAULT_MEMSTATUS] compile-time option.
5133 ** <li> An alternative page cache implementation is specified using
5134 **      [sqlcipher3_config]([SQLCIPHER_CONFIG_PCACHE],...).
5135 ** <li> The page cache allocates from its own memory pool supplied
5136 **      by [sqlcipher3_config]([SQLCIPHER_CONFIG_PAGECACHE],...) rather than
5137 **      from the heap.
5138 ** </ul>)^
5139 **
5140 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5141 ** regardless of whether or not the [SQLCIPHER_ENABLE_MEMORY_MANAGEMENT]
5142 ** compile-time option is invoked.  With [SQLCIPHER_ENABLE_MEMORY_MANAGEMENT],
5143 ** the soft heap limit is enforced on every memory allocation.  Without
5144 ** [SQLCIPHER_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5145 ** when memory is allocated by the page cache.  Testing suggests that because
5146 ** the page cache is the predominate memory user in SQLite, most
5147 ** applications will achieve adequate soft heap limit enforcement without
5148 ** the use of [SQLCIPHER_ENABLE_MEMORY_MANAGEMENT].
5149 **
5150 ** The circumstances under which SQLite will enforce the soft heap limit may
5151 ** changes in future releases of SQLite.
5152 */
5153 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_soft_heap_limit64(sqlcipher3_int64 N);
5154
5155 /*
5156 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5157 ** DEPRECATED
5158 **
5159 ** This is a deprecated version of the [sqlcipher3_soft_heap_limit64()]
5160 ** interface.  This routine is provided for historical compatibility
5161 ** only.  All new applications should use the
5162 ** [sqlcipher3_soft_heap_limit64()] interface rather than this one.
5163 */
5164 SQLCIPHER_API SQLCIPHER_DEPRECATED void sqlcipher3_soft_heap_limit(int N);
5165
5166
5167 /*
5168 ** CAPI3REF: Extract Metadata About A Column Of A Table
5169 **
5170 ** ^This routine returns metadata about a specific column of a specific
5171 ** database table accessible using the [database connection] handle
5172 ** passed as the first function argument.
5173 **
5174 ** ^The column is identified by the second, third and fourth parameters to
5175 ** this function. ^The second parameter is either the name of the database
5176 ** (i.e. "main", "temp", or an attached database) containing the specified
5177 ** table or NULL. ^If it is NULL, then all attached databases are searched
5178 ** for the table using the same algorithm used by the database engine to
5179 ** resolve unqualified table references.
5180 **
5181 ** ^The third and fourth parameters to this function are the table and column
5182 ** name of the desired column, respectively. Neither of these parameters
5183 ** may be NULL.
5184 **
5185 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5186 ** and subsequent parameters to this function. ^Any of these arguments may be
5187 ** NULL, in which case the corresponding element of metadata is omitted.
5188 **
5189 ** ^(<blockquote>
5190 ** <table border="1">
5191 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5192 **
5193 ** <tr><td> 5th <td> const char* <td> Data type
5194 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5195 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5196 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5197 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5198 ** </table>
5199 ** </blockquote>)^
5200 **
5201 ** ^The memory pointed to by the character pointers returned for the
5202 ** declaration type and collation sequence is valid only until the next
5203 ** call to any SQLite API function.
5204 **
5205 ** ^If the specified table is actually a view, an [error code] is returned.
5206 **
5207 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5208 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5209 ** parameters are set for the explicitly declared column. ^(If there is no
5210 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5211 ** parameters are set as follows:
5212 **
5213 ** <pre>
5214 **     data type: "INTEGER"
5215 **     collation sequence: "BINARY"
5216 **     not null: 0
5217 **     primary key: 1
5218 **     auto increment: 0
5219 ** </pre>)^
5220 **
5221 ** ^(This function may load one or more schemas from database files. If an
5222 ** error occurs during this process, or if the requested table or column
5223 ** cannot be found, an [error code] is returned and an error message left
5224 ** in the [database connection] (to be retrieved using sqlcipher3_errmsg()).)^
5225 **
5226 ** ^This API is only available if the library was compiled with the
5227 ** [SQLCIPHER_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5228 */
5229 SQLCIPHER_API int sqlcipher3_table_column_metadata(
5230   sqlcipher3 *db,                /* Connection handle */
5231   const char *zDbName,        /* Database name or NULL */
5232   const char *zTableName,     /* Table name */
5233   const char *zColumnName,    /* Column name */
5234   char const **pzDataType,    /* OUTPUT: Declared data type */
5235   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5236   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5237   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5238   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5239 );
5240
5241 /*
5242 ** CAPI3REF: Load An Extension
5243 **
5244 ** ^This interface loads an SQLite extension library from the named file.
5245 **
5246 ** ^The sqlcipher3_load_extension() interface attempts to load an
5247 ** SQLite extension library contained in the file zFile.
5248 **
5249 ** ^The entry point is zProc.
5250 ** ^zProc may be 0, in which case the name of the entry point
5251 ** defaults to "sqlcipher3_extension_init".
5252 ** ^The sqlcipher3_load_extension() interface returns
5253 ** [SQLCIPHER_OK] on success and [SQLCIPHER_ERROR] if something goes wrong.
5254 ** ^If an error occurs and pzErrMsg is not 0, then the
5255 ** [sqlcipher3_load_extension()] interface shall attempt to
5256 ** fill *pzErrMsg with error message text stored in memory
5257 ** obtained from [sqlcipher3_malloc()]. The calling function
5258 ** should free this memory by calling [sqlcipher3_free()].
5259 **
5260 ** ^Extension loading must be enabled using
5261 ** [sqlcipher3_enable_load_extension()] prior to calling this API,
5262 ** otherwise an error will be returned.
5263 **
5264 ** See also the [load_extension() SQL function].
5265 */
5266 SQLCIPHER_API int sqlcipher3_load_extension(
5267   sqlcipher3 *db,          /* Load the extension into this database connection */
5268   const char *zFile,    /* Name of the shared library containing extension */
5269   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5270   char **pzErrMsg       /* Put error message here if not 0 */
5271 );
5272
5273 /*
5274 ** CAPI3REF: Enable Or Disable Extension Loading
5275 **
5276 ** ^So as not to open security holes in older applications that are
5277 ** unprepared to deal with extension loading, and as a means of disabling
5278 ** extension loading while evaluating user-entered SQL, the following API
5279 ** is provided to turn the [sqlcipher3_load_extension()] mechanism on and off.
5280 **
5281 ** ^Extension loading is off by default. See ticket #1863.
5282 ** ^Call the sqlcipher3_enable_load_extension() routine with onoff==1
5283 ** to turn extension loading on and call it with onoff==0 to turn
5284 ** it back off again.
5285 */
5286 SQLCIPHER_API int sqlcipher3_enable_load_extension(sqlcipher3 *db, int onoff);
5287
5288 /*
5289 ** CAPI3REF: Automatically Load Statically Linked Extensions
5290 **
5291 ** ^This interface causes the xEntryPoint() function to be invoked for
5292 ** each new [database connection] that is created.  The idea here is that
5293 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5294 ** that is to be automatically loaded into all new database connections.
5295 **
5296 ** ^(Even though the function prototype shows that xEntryPoint() takes
5297 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5298 ** arguments and expects and integer result as if the signature of the
5299 ** entry point where as follows:
5300 **
5301 ** <blockquote><pre>
5302 ** &nbsp;  int xEntryPoint(
5303 ** &nbsp;    sqlcipher3 *db,
5304 ** &nbsp;    const char **pzErrMsg,
5305 ** &nbsp;    const struct sqlcipher3_api_routines *pThunk
5306 ** &nbsp;  );
5307 ** </pre></blockquote>)^
5308 **
5309 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5310 ** point to an appropriate error message (obtained from [sqlcipher3_mprintf()])
5311 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5312 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5313 ** [sqlcipher3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5314 ** xEntryPoint() returns an error, the [sqlcipher3_open()], [sqlcipher3_open16()],
5315 ** or [sqlcipher3_open_v2()] call that provoked the xEntryPoint() will fail.
5316 **
5317 ** ^Calling sqlcipher3_auto_extension(X) with an entry point X that is already
5318 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5319 ** will be called more than once for each database connection that is opened.
5320 **
5321 ** See also: [sqlcipher3_reset_auto_extension()].
5322 */
5323 SQLCIPHER_API int sqlcipher3_auto_extension(void (*xEntryPoint)(void));
5324
5325 /*
5326 ** CAPI3REF: Reset Automatic Extension Loading
5327 **
5328 ** ^This interface disables all automatic extensions previously
5329 ** registered using [sqlcipher3_auto_extension()].
5330 */
5331 SQLCIPHER_API void sqlcipher3_reset_auto_extension(void);
5332
5333 /*
5334 ** The interface to the virtual-table mechanism is currently considered
5335 ** to be experimental.  The interface might change in incompatible ways.
5336 ** If this is a problem for you, do not use the interface at this time.
5337 **
5338 ** When the virtual-table mechanism stabilizes, we will declare the
5339 ** interface fixed, support it indefinitely, and remove this comment.
5340 */
5341
5342 /*
5343 ** Structures used by the virtual table interface
5344 */
5345 typedef struct sqlcipher3_vtab sqlcipher3_vtab;
5346 typedef struct sqlcipher3_index_info sqlcipher3_index_info;
5347 typedef struct sqlcipher3_vtab_cursor sqlcipher3_vtab_cursor;
5348 typedef struct sqlcipher3_module sqlcipher3_module;
5349
5350 /*
5351 ** CAPI3REF: Virtual Table Object
5352 ** KEYWORDS: sqlcipher3_module {virtual table module}
5353 **
5354 ** This structure, sometimes called a "virtual table module", 
5355 ** defines the implementation of a [virtual tables].  
5356 ** This structure consists mostly of methods for the module.
5357 **
5358 ** ^A virtual table module is created by filling in a persistent
5359 ** instance of this structure and passing a pointer to that instance
5360 ** to [sqlcipher3_create_module()] or [sqlcipher3_create_module_v2()].
5361 ** ^The registration remains valid until it is replaced by a different
5362 ** module or until the [database connection] closes.  The content
5363 ** of this structure must not change while it is registered with
5364 ** any database connection.
5365 */
5366 struct sqlcipher3_module {
5367   int iVersion;
5368   int (*xCreate)(sqlcipher3*, void *pAux,
5369                int argc, const char *const*argv,
5370                sqlcipher3_vtab **ppVTab, char**);
5371   int (*xConnect)(sqlcipher3*, void *pAux,
5372                int argc, const char *const*argv,
5373                sqlcipher3_vtab **ppVTab, char**);
5374   int (*xBestIndex)(sqlcipher3_vtab *pVTab, sqlcipher3_index_info*);
5375   int (*xDisconnect)(sqlcipher3_vtab *pVTab);
5376   int (*xDestroy)(sqlcipher3_vtab *pVTab);
5377   int (*xOpen)(sqlcipher3_vtab *pVTab, sqlcipher3_vtab_cursor **ppCursor);
5378   int (*xClose)(sqlcipher3_vtab_cursor*);
5379   int (*xFilter)(sqlcipher3_vtab_cursor*, int idxNum, const char *idxStr,
5380                 int argc, sqlcipher3_value **argv);
5381   int (*xNext)(sqlcipher3_vtab_cursor*);
5382   int (*xEof)(sqlcipher3_vtab_cursor*);
5383   int (*xColumn)(sqlcipher3_vtab_cursor*, sqlcipher3_context*, int);
5384   int (*xRowid)(sqlcipher3_vtab_cursor*, sqlcipher3_int64 *pRowid);
5385   int (*xUpdate)(sqlcipher3_vtab *, int, sqlcipher3_value **, sqlcipher3_int64 *);
5386   int (*xBegin)(sqlcipher3_vtab *pVTab);
5387   int (*xSync)(sqlcipher3_vtab *pVTab);
5388   int (*xCommit)(sqlcipher3_vtab *pVTab);
5389   int (*xRollback)(sqlcipher3_vtab *pVTab);
5390   int (*xFindFunction)(sqlcipher3_vtab *pVtab, int nArg, const char *zName,
5391                        void (**pxFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
5392                        void **ppArg);
5393   int (*xRename)(sqlcipher3_vtab *pVtab, const char *zNew);
5394   /* The methods above are in version 1 of the sqlcipher_module object. Those 
5395   ** below are for version 2 and greater. */
5396   int (*xSavepoint)(sqlcipher3_vtab *pVTab, int);
5397   int (*xRelease)(sqlcipher3_vtab *pVTab, int);
5398   int (*xRollbackTo)(sqlcipher3_vtab *pVTab, int);
5399 };
5400
5401 /*
5402 ** CAPI3REF: Virtual Table Indexing Information
5403 ** KEYWORDS: sqlcipher3_index_info
5404 **
5405 ** The sqlcipher3_index_info structure and its substructures is used as part
5406 ** of the [virtual table] interface to
5407 ** pass information into and receive the reply from the [xBestIndex]
5408 ** method of a [virtual table module].  The fields under **Inputs** are the
5409 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5410 ** results into the **Outputs** fields.
5411 **
5412 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5413 **
5414 ** <blockquote>column OP expr</blockquote>
5415 **
5416 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5417 ** stored in aConstraint[].op using one of the
5418 ** [SQLCIPHER_INDEX_CONSTRAINT_EQ | SQLCIPHER_INDEX_CONSTRAINT_ values].)^
5419 ** ^(The index of the column is stored in
5420 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5421 ** expr on the right-hand side can be evaluated (and thus the constraint
5422 ** is usable) and false if it cannot.)^
5423 **
5424 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5425 ** and makes other simplifications to the WHERE clause in an attempt to
5426 ** get as many WHERE clause terms into the form shown above as possible.
5427 ** ^The aConstraint[] array only reports WHERE clause terms that are
5428 ** relevant to the particular virtual table being queried.
5429 **
5430 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5431 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5432 **
5433 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5434 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5435 ** the right-hand side of the corresponding aConstraint[] is evaluated
5436 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5437 ** is true, then the constraint is assumed to be fully handled by the
5438 ** virtual table and is not checked again by SQLite.)^
5439 **
5440 ** ^The idxNum and idxPtr values are recorded and passed into the
5441 ** [xFilter] method.
5442 ** ^[sqlcipher3_free()] is used to free idxPtr if and only if
5443 ** needToFreeIdxPtr is true.
5444 **
5445 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5446 ** the correct order to satisfy the ORDER BY clause so that no separate
5447 ** sorting step is required.
5448 **
5449 ** ^The estimatedCost value is an estimate of the cost of doing the
5450 ** particular lookup.  A full scan of a table with N entries should have
5451 ** a cost of N.  A binary search of a table of N entries should have a
5452 ** cost of approximately log(N).
5453 */
5454 struct sqlcipher3_index_info {
5455   /* Inputs */
5456   int nConstraint;           /* Number of entries in aConstraint */
5457   struct sqlcipher3_index_constraint {
5458      int iColumn;              /* Column on left-hand side of constraint */
5459      unsigned char op;         /* Constraint operator */
5460      unsigned char usable;     /* True if this constraint is usable */
5461      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5462   } *aConstraint;            /* Table of WHERE clause constraints */
5463   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5464   struct sqlcipher3_index_orderby {
5465      int iColumn;              /* Column number */
5466      unsigned char desc;       /* True for DESC.  False for ASC. */
5467   } *aOrderBy;               /* The ORDER BY clause */
5468   /* Outputs */
5469   struct sqlcipher3_index_constraint_usage {
5470     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5471     unsigned char omit;      /* Do not code a test for this constraint */
5472   } *aConstraintUsage;
5473   int idxNum;                /* Number used to identify the index */
5474   char *idxStr;              /* String, possibly obtained from sqlcipher3_malloc */
5475   int needToFreeIdxStr;      /* Free idxStr using sqlcipher3_free() if true */
5476   int orderByConsumed;       /* True if output is already ordered */
5477   double estimatedCost;      /* Estimated cost of using this index */
5478 };
5479
5480 /*
5481 ** CAPI3REF: Virtual Table Constraint Operator Codes
5482 **
5483 ** These macros defined the allowed values for the
5484 ** [sqlcipher3_index_info].aConstraint[].op field.  Each value represents
5485 ** an operator that is part of a constraint term in the wHERE clause of
5486 ** a query that uses a [virtual table].
5487 */
5488 #define SQLCIPHER_INDEX_CONSTRAINT_EQ    2
5489 #define SQLCIPHER_INDEX_CONSTRAINT_GT    4
5490 #define SQLCIPHER_INDEX_CONSTRAINT_LE    8
5491 #define SQLCIPHER_INDEX_CONSTRAINT_LT    16
5492 #define SQLCIPHER_INDEX_CONSTRAINT_GE    32
5493 #define SQLCIPHER_INDEX_CONSTRAINT_MATCH 64
5494
5495 /*
5496 ** CAPI3REF: Register A Virtual Table Implementation
5497 **
5498 ** ^These routines are used to register a new [virtual table module] name.
5499 ** ^Module names must be registered before
5500 ** creating a new [virtual table] using the module and before using a
5501 ** preexisting [virtual table] for the module.
5502 **
5503 ** ^The module name is registered on the [database connection] specified
5504 ** by the first parameter.  ^The name of the module is given by the 
5505 ** second parameter.  ^The third parameter is a pointer to
5506 ** the implementation of the [virtual table module].   ^The fourth
5507 ** parameter is an arbitrary client data pointer that is passed through
5508 ** into the [xCreate] and [xConnect] methods of the virtual table module
5509 ** when a new virtual table is be being created or reinitialized.
5510 **
5511 ** ^The sqlcipher3_create_module_v2() interface has a fifth parameter which
5512 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5513 ** invoke the destructor function (if it is not NULL) when SQLite
5514 ** no longer needs the pClientData pointer.  ^The destructor will also
5515 ** be invoked if the call to sqlcipher3_create_module_v2() fails.
5516 ** ^The sqlcipher3_create_module()
5517 ** interface is equivalent to sqlcipher3_create_module_v2() with a NULL
5518 ** destructor.
5519 */
5520 SQLCIPHER_API int sqlcipher3_create_module(
5521   sqlcipher3 *db,               /* SQLite connection to register module with */
5522   const char *zName,         /* Name of the module */
5523   const sqlcipher3_module *p,   /* Methods for the module */
5524   void *pClientData          /* Client data for xCreate/xConnect */
5525 );
5526 SQLCIPHER_API int sqlcipher3_create_module_v2(
5527   sqlcipher3 *db,               /* SQLite connection to register module with */
5528   const char *zName,         /* Name of the module */
5529   const sqlcipher3_module *p,   /* Methods for the module */
5530   void *pClientData,         /* Client data for xCreate/xConnect */
5531   void(*xDestroy)(void*)     /* Module destructor function */
5532 );
5533
5534 /*
5535 ** CAPI3REF: Virtual Table Instance Object
5536 ** KEYWORDS: sqlcipher3_vtab
5537 **
5538 ** Every [virtual table module] implementation uses a subclass
5539 ** of this object to describe a particular instance
5540 ** of the [virtual table].  Each subclass will
5541 ** be tailored to the specific needs of the module implementation.
5542 ** The purpose of this superclass is to define certain fields that are
5543 ** common to all module implementations.
5544 **
5545 ** ^Virtual tables methods can set an error message by assigning a
5546 ** string obtained from [sqlcipher3_mprintf()] to zErrMsg.  The method should
5547 ** take care that any prior string is freed by a call to [sqlcipher3_free()]
5548 ** prior to assigning a new string to zErrMsg.  ^After the error message
5549 ** is delivered up to the client application, the string will be automatically
5550 ** freed by sqlcipher3_free() and the zErrMsg field will be zeroed.
5551 */
5552 struct sqlcipher3_vtab {
5553   const sqlcipher3_module *pModule;  /* The module for this virtual table */
5554   int nRef;                       /* NO LONGER USED */
5555   char *zErrMsg;                  /* Error message from sqlcipher3_mprintf() */
5556   /* Virtual table implementations will typically add additional fields */
5557 };
5558
5559 /*
5560 ** CAPI3REF: Virtual Table Cursor Object
5561 ** KEYWORDS: sqlcipher3_vtab_cursor {virtual table cursor}
5562 **
5563 ** Every [virtual table module] implementation uses a subclass of the
5564 ** following structure to describe cursors that point into the
5565 ** [virtual table] and are used
5566 ** to loop through the virtual table.  Cursors are created using the
5567 ** [sqlcipher3_module.xOpen | xOpen] method of the module and are destroyed
5568 ** by the [sqlcipher3_module.xClose | xClose] method.  Cursors are used
5569 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5570 ** of the module.  Each module implementation will define
5571 ** the content of a cursor structure to suit its own needs.
5572 **
5573 ** This superclass exists in order to define fields of the cursor that
5574 ** are common to all implementations.
5575 */
5576 struct sqlcipher3_vtab_cursor {
5577   sqlcipher3_vtab *pVtab;      /* Virtual table of this cursor */
5578   /* Virtual table implementations will typically add additional fields */
5579 };
5580
5581 /*
5582 ** CAPI3REF: Declare The Schema Of A Virtual Table
5583 **
5584 ** ^The [xCreate] and [xConnect] methods of a
5585 ** [virtual table module] call this interface
5586 ** to declare the format (the names and datatypes of the columns) of
5587 ** the virtual tables they implement.
5588 */
5589 SQLCIPHER_API int sqlcipher3_declare_vtab(sqlcipher3*, const char *zSQL);
5590
5591 /*
5592 ** CAPI3REF: Overload A Function For A Virtual Table
5593 **
5594 ** ^(Virtual tables can provide alternative implementations of functions
5595 ** using the [xFindFunction] method of the [virtual table module].  
5596 ** But global versions of those functions
5597 ** must exist in order to be overloaded.)^
5598 **
5599 ** ^(This API makes sure a global version of a function with a particular
5600 ** name and number of parameters exists.  If no such function exists
5601 ** before this API is called, a new function is created.)^  ^The implementation
5602 ** of the new function always causes an exception to be thrown.  So
5603 ** the new function is not good for anything by itself.  Its only
5604 ** purpose is to be a placeholder function that can be overloaded
5605 ** by a [virtual table].
5606 */
5607 SQLCIPHER_API int sqlcipher3_overload_function(sqlcipher3*, const char *zFuncName, int nArg);
5608
5609 /*
5610 ** The interface to the virtual-table mechanism defined above (back up
5611 ** to a comment remarkably similar to this one) is currently considered
5612 ** to be experimental.  The interface might change in incompatible ways.
5613 ** If this is a problem for you, do not use the interface at this time.
5614 **
5615 ** When the virtual-table mechanism stabilizes, we will declare the
5616 ** interface fixed, support it indefinitely, and remove this comment.
5617 */
5618
5619 /*
5620 ** CAPI3REF: A Handle To An Open BLOB
5621 ** KEYWORDS: {BLOB handle} {BLOB handles}
5622 **
5623 ** An instance of this object represents an open BLOB on which
5624 ** [sqlcipher3_blob_open | incremental BLOB I/O] can be performed.
5625 ** ^Objects of this type are created by [sqlcipher3_blob_open()]
5626 ** and destroyed by [sqlcipher3_blob_close()].
5627 ** ^The [sqlcipher3_blob_read()] and [sqlcipher3_blob_write()] interfaces
5628 ** can be used to read or write small subsections of the BLOB.
5629 ** ^The [sqlcipher3_blob_bytes()] interface returns the size of the BLOB in bytes.
5630 */
5631 typedef struct sqlcipher3_blob sqlcipher3_blob;
5632
5633 /*
5634 ** CAPI3REF: Open A BLOB For Incremental I/O
5635 **
5636 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5637 ** in row iRow, column zColumn, table zTable in database zDb;
5638 ** in other words, the same BLOB that would be selected by:
5639 **
5640 ** <pre>
5641 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5642 ** </pre>)^
5643 **
5644 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5645 ** and write access. ^If it is zero, the BLOB is opened for read access.
5646 ** ^It is not possible to open a column that is part of an index or primary 
5647 ** key for writing. ^If [foreign key constraints] are enabled, it is 
5648 ** not possible to open a column that is part of a [child key] for writing.
5649 **
5650 ** ^Note that the database name is not the filename that contains
5651 ** the database but rather the symbolic name of the database that
5652 ** appears after the AS keyword when the database is connected using [ATTACH].
5653 ** ^For the main database file, the database name is "main".
5654 ** ^For TEMP tables, the database name is "temp".
5655 **
5656 ** ^(On success, [SQLCIPHER_OK] is returned and the new [BLOB handle] is written
5657 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5658 ** to be a null pointer.)^
5659 ** ^This function sets the [database connection] error code and message
5660 ** accessible via [sqlcipher3_errcode()] and [sqlcipher3_errmsg()] and related
5661 ** functions. ^Note that the *ppBlob variable is always initialized in a
5662 ** way that makes it safe to invoke [sqlcipher3_blob_close()] on *ppBlob
5663 ** regardless of the success or failure of this routine.
5664 **
5665 ** ^(If the row that a BLOB handle points to is modified by an
5666 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5667 ** then the BLOB handle is marked as "expired".
5668 ** This is true if any column of the row is changed, even a column
5669 ** other than the one the BLOB handle is open on.)^
5670 ** ^Calls to [sqlcipher3_blob_read()] and [sqlcipher3_blob_write()] for
5671 ** an expired BLOB handle fail with a return code of [SQLCIPHER_ABORT].
5672 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5673 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5674 ** commit if the transaction continues to completion.)^
5675 **
5676 ** ^Use the [sqlcipher3_blob_bytes()] interface to determine the size of
5677 ** the opened blob.  ^The size of a blob may not be changed by this
5678 ** interface.  Use the [UPDATE] SQL command to change the size of a
5679 ** blob.
5680 **
5681 ** ^The [sqlcipher3_bind_zeroblob()] and [sqlcipher3_result_zeroblob()] interfaces
5682 ** and the built-in [zeroblob] SQL function can be used, if desired,
5683 ** to create an empty, zero-filled blob in which to read or write using
5684 ** this interface.
5685 **
5686 ** To avoid a resource leak, every open [BLOB handle] should eventually
5687 ** be released by a call to [sqlcipher3_blob_close()].
5688 */
5689 SQLCIPHER_API int sqlcipher3_blob_open(
5690   sqlcipher3*,
5691   const char *zDb,
5692   const char *zTable,
5693   const char *zColumn,
5694   sqlcipher3_int64 iRow,
5695   int flags,
5696   sqlcipher3_blob **ppBlob
5697 );
5698
5699 /*
5700 ** CAPI3REF: Move a BLOB Handle to a New Row
5701 **
5702 ** ^This function is used to move an existing blob handle so that it points
5703 ** to a different row of the same database table. ^The new row is identified
5704 ** by the rowid value passed as the second argument. Only the row can be
5705 ** changed. ^The database, table and column on which the blob handle is open
5706 ** remain the same. Moving an existing blob handle to a new row can be
5707 ** faster than closing the existing handle and opening a new one.
5708 **
5709 ** ^(The new row must meet the same criteria as for [sqlcipher3_blob_open()] -
5710 ** it must exist and there must be either a blob or text value stored in
5711 ** the nominated column.)^ ^If the new row is not present in the table, or if
5712 ** it does not contain a blob or text value, or if another error occurs, an
5713 ** SQLite error code is returned and the blob handle is considered aborted.
5714 ** ^All subsequent calls to [sqlcipher3_blob_read()], [sqlcipher3_blob_write()] or
5715 ** [sqlcipher3_blob_reopen()] on an aborted blob handle immediately return
5716 ** SQLCIPHER_ABORT. ^Calling [sqlcipher3_blob_bytes()] on an aborted blob handle
5717 ** always returns zero.
5718 **
5719 ** ^This function sets the database handle error code and message.
5720 */
5721 SQLCIPHER_API SQLCIPHER_EXPERIMENTAL int sqlcipher3_blob_reopen(sqlcipher3_blob *, sqlcipher3_int64);
5722
5723 /*
5724 ** CAPI3REF: Close A BLOB Handle
5725 **
5726 ** ^Closes an open [BLOB handle].
5727 **
5728 ** ^Closing a BLOB shall cause the current transaction to commit
5729 ** if there are no other BLOBs, no pending prepared statements, and the
5730 ** database connection is in [autocommit mode].
5731 ** ^If any writes were made to the BLOB, they might be held in cache
5732 ** until the close operation if they will fit.
5733 **
5734 ** ^(Closing the BLOB often forces the changes
5735 ** out to disk and so if any I/O errors occur, they will likely occur
5736 ** at the time when the BLOB is closed.  Any errors that occur during
5737 ** closing are reported as a non-zero return value.)^
5738 **
5739 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5740 ** an error code, the BLOB is still closed.)^
5741 **
5742 ** ^Calling this routine with a null pointer (such as would be returned
5743 ** by a failed call to [sqlcipher3_blob_open()]) is a harmless no-op.
5744 */
5745 SQLCIPHER_API int sqlcipher3_blob_close(sqlcipher3_blob *);
5746
5747 /*
5748 ** CAPI3REF: Return The Size Of An Open BLOB
5749 **
5750 ** ^Returns the size in bytes of the BLOB accessible via the 
5751 ** successfully opened [BLOB handle] in its only argument.  ^The
5752 ** incremental blob I/O routines can only read or overwriting existing
5753 ** blob content; they cannot change the size of a blob.
5754 **
5755 ** This routine only works on a [BLOB handle] which has been created
5756 ** by a prior successful call to [sqlcipher3_blob_open()] and which has not
5757 ** been closed by [sqlcipher3_blob_close()].  Passing any other pointer in
5758 ** to this routine results in undefined and probably undesirable behavior.
5759 */
5760 SQLCIPHER_API int sqlcipher3_blob_bytes(sqlcipher3_blob *);
5761
5762 /*
5763 ** CAPI3REF: Read Data From A BLOB Incrementally
5764 **
5765 ** ^(This function is used to read data from an open [BLOB handle] into a
5766 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5767 ** from the open BLOB, starting at offset iOffset.)^
5768 **
5769 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5770 ** [SQLCIPHER_ERROR] is returned and no data is read.  ^If N or iOffset is
5771 ** less than zero, [SQLCIPHER_ERROR] is returned and no data is read.
5772 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5773 ** can be determined using the [sqlcipher3_blob_bytes()] interface.
5774 **
5775 ** ^An attempt to read from an expired [BLOB handle] fails with an
5776 ** error code of [SQLCIPHER_ABORT].
5777 **
5778 ** ^(On success, sqlcipher3_blob_read() returns SQLCIPHER_OK.
5779 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5780 **
5781 ** This routine only works on a [BLOB handle] which has been created
5782 ** by a prior successful call to [sqlcipher3_blob_open()] and which has not
5783 ** been closed by [sqlcipher3_blob_close()].  Passing any other pointer in
5784 ** to this routine results in undefined and probably undesirable behavior.
5785 **
5786 ** See also: [sqlcipher3_blob_write()].
5787 */
5788 SQLCIPHER_API int sqlcipher3_blob_read(sqlcipher3_blob *, void *Z, int N, int iOffset);
5789
5790 /*
5791 ** CAPI3REF: Write Data Into A BLOB Incrementally
5792 **
5793 ** ^This function is used to write data into an open [BLOB handle] from a
5794 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5795 ** into the open BLOB, starting at offset iOffset.
5796 **
5797 ** ^If the [BLOB handle] passed as the first argument was not opened for
5798 ** writing (the flags parameter to [sqlcipher3_blob_open()] was zero),
5799 ** this function returns [SQLCIPHER_READONLY].
5800 **
5801 ** ^This function may only modify the contents of the BLOB; it is
5802 ** not possible to increase the size of a BLOB using this API.
5803 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5804 ** [SQLCIPHER_ERROR] is returned and no data is written.  ^If N is
5805 ** less than zero [SQLCIPHER_ERROR] is returned and no data is written.
5806 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5807 ** can be determined using the [sqlcipher3_blob_bytes()] interface.
5808 **
5809 ** ^An attempt to write to an expired [BLOB handle] fails with an
5810 ** error code of [SQLCIPHER_ABORT].  ^Writes to the BLOB that occurred
5811 ** before the [BLOB handle] expired are not rolled back by the
5812 ** expiration of the handle, though of course those changes might
5813 ** have been overwritten by the statement that expired the BLOB handle
5814 ** or by other independent statements.
5815 **
5816 ** ^(On success, sqlcipher3_blob_write() returns SQLCIPHER_OK.
5817 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5818 **
5819 ** This routine only works on a [BLOB handle] which has been created
5820 ** by a prior successful call to [sqlcipher3_blob_open()] and which has not
5821 ** been closed by [sqlcipher3_blob_close()].  Passing any other pointer in
5822 ** to this routine results in undefined and probably undesirable behavior.
5823 **
5824 ** See also: [sqlcipher3_blob_read()].
5825 */
5826 SQLCIPHER_API int sqlcipher3_blob_write(sqlcipher3_blob *, const void *z, int n, int iOffset);
5827
5828 /*
5829 ** CAPI3REF: Virtual File System Objects
5830 **
5831 ** A virtual filesystem (VFS) is an [sqlcipher3_vfs] object
5832 ** that SQLite uses to interact
5833 ** with the underlying operating system.  Most SQLite builds come with a
5834 ** single default VFS that is appropriate for the host computer.
5835 ** New VFSes can be registered and existing VFSes can be unregistered.
5836 ** The following interfaces are provided.
5837 **
5838 ** ^The sqlcipher3_vfs_find() interface returns a pointer to a VFS given its name.
5839 ** ^Names are case sensitive.
5840 ** ^Names are zero-terminated UTF-8 strings.
5841 ** ^If there is no match, a NULL pointer is returned.
5842 ** ^If zVfsName is NULL then the default VFS is returned.
5843 **
5844 ** ^New VFSes are registered with sqlcipher3_vfs_register().
5845 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5846 ** ^The same VFS can be registered multiple times without injury.
5847 ** ^To make an existing VFS into the default VFS, register it again
5848 ** with the makeDflt flag set.  If two different VFSes with the
5849 ** same name are registered, the behavior is undefined.  If a
5850 ** VFS is registered with a name that is NULL or an empty string,
5851 ** then the behavior is undefined.
5852 **
5853 ** ^Unregister a VFS with the sqlcipher3_vfs_unregister() interface.
5854 ** ^(If the default VFS is unregistered, another VFS is chosen as
5855 ** the default.  The choice for the new VFS is arbitrary.)^
5856 */
5857 SQLCIPHER_API sqlcipher3_vfs *sqlcipher3_vfs_find(const char *zVfsName);
5858 SQLCIPHER_API int sqlcipher3_vfs_register(sqlcipher3_vfs*, int makeDflt);
5859 SQLCIPHER_API int sqlcipher3_vfs_unregister(sqlcipher3_vfs*);
5860
5861 /*
5862 ** CAPI3REF: Mutexes
5863 **
5864 ** The SQLite core uses these routines for thread
5865 ** synchronization. Though they are intended for internal
5866 ** use by SQLite, code that links against SQLite is
5867 ** permitted to use any of these routines.
5868 **
5869 ** The SQLite source code contains multiple implementations
5870 ** of these mutex routines.  An appropriate implementation
5871 ** is selected automatically at compile-time.  ^(The following
5872 ** implementations are available in the SQLite core:
5873 **
5874 ** <ul>
5875 ** <li>   SQLCIPHER_MUTEX_OS2
5876 ** <li>   SQLCIPHER_MUTEX_PTHREAD
5877 ** <li>   SQLCIPHER_MUTEX_W32
5878 ** <li>   SQLCIPHER_MUTEX_NOOP
5879 ** </ul>)^
5880 **
5881 ** ^The SQLCIPHER_MUTEX_NOOP implementation is a set of routines
5882 ** that does no real locking and is appropriate for use in
5883 ** a single-threaded application.  ^The SQLCIPHER_MUTEX_OS2,
5884 ** SQLCIPHER_MUTEX_PTHREAD, and SQLCIPHER_MUTEX_W32 implementations
5885 ** are appropriate for use on OS/2, Unix, and Windows.
5886 **
5887 ** ^(If SQLite is compiled with the SQLCIPHER_MUTEX_APPDEF preprocessor
5888 ** macro defined (with "-DSQLCIPHER_MUTEX_APPDEF=1"), then no mutex
5889 ** implementation is included with the library. In this case the
5890 ** application must supply a custom mutex implementation using the
5891 ** [SQLCIPHER_CONFIG_MUTEX] option of the sqlcipher3_config() function
5892 ** before calling sqlcipher3_initialize() or any other public sqlcipher3_
5893 ** function that calls sqlcipher3_initialize().)^
5894 **
5895 ** ^The sqlcipher3_mutex_alloc() routine allocates a new
5896 ** mutex and returns a pointer to it. ^If it returns NULL
5897 ** that means that a mutex could not be allocated.  ^SQLite
5898 ** will unwind its stack and return an error.  ^(The argument
5899 ** to sqlcipher3_mutex_alloc() is one of these integer constants:
5900 **
5901 ** <ul>
5902 ** <li>  SQLCIPHER_MUTEX_FAST
5903 ** <li>  SQLCIPHER_MUTEX_RECURSIVE
5904 ** <li>  SQLCIPHER_MUTEX_STATIC_MASTER
5905 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM
5906 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM2
5907 ** <li>  SQLCIPHER_MUTEX_STATIC_PRNG
5908 ** <li>  SQLCIPHER_MUTEX_STATIC_LRU
5909 ** <li>  SQLCIPHER_MUTEX_STATIC_LRU2
5910 ** </ul>)^
5911 **
5912 ** ^The first two constants (SQLCIPHER_MUTEX_FAST and SQLCIPHER_MUTEX_RECURSIVE)
5913 ** cause sqlcipher3_mutex_alloc() to create
5914 ** a new mutex.  ^The new mutex is recursive when SQLCIPHER_MUTEX_RECURSIVE
5915 ** is used but not necessarily so when SQLCIPHER_MUTEX_FAST is used.
5916 ** The mutex implementation does not need to make a distinction
5917 ** between SQLCIPHER_MUTEX_RECURSIVE and SQLCIPHER_MUTEX_FAST if it does
5918 ** not want to.  ^SQLite will only request a recursive mutex in
5919 ** cases where it really needs one.  ^If a faster non-recursive mutex
5920 ** implementation is available on the host platform, the mutex subsystem
5921 ** might return such a mutex in response to SQLCIPHER_MUTEX_FAST.
5922 **
5923 ** ^The other allowed parameters to sqlcipher3_mutex_alloc() (anything other
5924 ** than SQLCIPHER_MUTEX_FAST and SQLCIPHER_MUTEX_RECURSIVE) each return
5925 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
5926 ** used by the current version of SQLite.  Future versions of SQLite
5927 ** may add additional static mutexes.  Static mutexes are for internal
5928 ** use by SQLite only.  Applications that use SQLite mutexes should
5929 ** use only the dynamic mutexes returned by SQLCIPHER_MUTEX_FAST or
5930 ** SQLCIPHER_MUTEX_RECURSIVE.
5931 **
5932 ** ^Note that if one of the dynamic mutex parameters (SQLCIPHER_MUTEX_FAST
5933 ** or SQLCIPHER_MUTEX_RECURSIVE) is used then sqlcipher3_mutex_alloc()
5934 ** returns a different mutex on every call.  ^But for the static
5935 ** mutex types, the same mutex is returned on every call that has
5936 ** the same type number.
5937 **
5938 ** ^The sqlcipher3_mutex_free() routine deallocates a previously
5939 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5940 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5941 ** use when they are deallocated.  Attempting to deallocate a static
5942 ** mutex results in undefined behavior.  ^SQLite never deallocates
5943 ** a static mutex.
5944 **
5945 ** ^The sqlcipher3_mutex_enter() and sqlcipher3_mutex_try() routines attempt
5946 ** to enter a mutex.  ^If another thread is already within the mutex,
5947 ** sqlcipher3_mutex_enter() will block and sqlcipher3_mutex_try() will return
5948 ** SQLCIPHER_BUSY.  ^The sqlcipher3_mutex_try() interface returns [SQLCIPHER_OK]
5949 ** upon successful entry.  ^(Mutexes created using
5950 ** SQLCIPHER_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5951 ** In such cases the,
5952 ** mutex must be exited an equal number of times before another thread
5953 ** can enter.)^  ^(If the same thread tries to enter any other
5954 ** kind of mutex more than once, the behavior is undefined.
5955 ** SQLite will never exhibit
5956 ** such behavior in its own use of mutexes.)^
5957 **
5958 ** ^(Some systems (for example, Windows 95) do not support the operation
5959 ** implemented by sqlcipher3_mutex_try().  On those systems, sqlcipher3_mutex_try()
5960 ** will always return SQLCIPHER_BUSY.  The SQLite core only ever uses
5961 ** sqlcipher3_mutex_try() as an optimization so this is acceptable behavior.)^
5962 **
5963 ** ^The sqlcipher3_mutex_leave() routine exits a mutex that was
5964 ** previously entered by the same thread.   ^(The behavior
5965 ** is undefined if the mutex is not currently entered by the
5966 ** calling thread or is not currently allocated.  SQLite will
5967 ** never do either.)^
5968 **
5969 ** ^If the argument to sqlcipher3_mutex_enter(), sqlcipher3_mutex_try(), or
5970 ** sqlcipher3_mutex_leave() is a NULL pointer, then all three routines
5971 ** behave as no-ops.
5972 **
5973 ** See also: [sqlcipher3_mutex_held()] and [sqlcipher3_mutex_notheld()].
5974 */
5975 SQLCIPHER_API sqlcipher3_mutex *sqlcipher3_mutex_alloc(int);
5976 SQLCIPHER_API void sqlcipher3_mutex_free(sqlcipher3_mutex*);
5977 SQLCIPHER_API void sqlcipher3_mutex_enter(sqlcipher3_mutex*);
5978 SQLCIPHER_API int sqlcipher3_mutex_try(sqlcipher3_mutex*);
5979 SQLCIPHER_API void sqlcipher3_mutex_leave(sqlcipher3_mutex*);
5980
5981 /*
5982 ** CAPI3REF: Mutex Methods Object
5983 **
5984 ** An instance of this structure defines the low-level routines
5985 ** used to allocate and use mutexes.
5986 **
5987 ** Usually, the default mutex implementations provided by SQLite are
5988 ** sufficient, however the user has the option of substituting a custom
5989 ** implementation for specialized deployments or systems for which SQLite
5990 ** does not provide a suitable implementation. In this case, the user
5991 ** creates and populates an instance of this structure to pass
5992 ** to sqlcipher3_config() along with the [SQLCIPHER_CONFIG_MUTEX] option.
5993 ** Additionally, an instance of this structure can be used as an
5994 ** output variable when querying the system for the current mutex
5995 ** implementation, using the [SQLCIPHER_CONFIG_GETMUTEX] option.
5996 **
5997 ** ^The xMutexInit method defined by this structure is invoked as
5998 ** part of system initialization by the sqlcipher3_initialize() function.
5999 ** ^The xMutexInit routine is called by SQLite exactly once for each
6000 ** effective call to [sqlcipher3_initialize()].
6001 **
6002 ** ^The xMutexEnd method defined by this structure is invoked as
6003 ** part of system shutdown by the sqlcipher3_shutdown() function. The
6004 ** implementation of this method is expected to release all outstanding
6005 ** resources obtained by the mutex methods implementation, especially
6006 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
6007 ** interface is invoked exactly once for each call to [sqlcipher3_shutdown()].
6008 **
6009 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6010 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6011 ** xMutexNotheld) implement the following interfaces (respectively):
6012 **
6013 ** <ul>
6014 **   <li>  [sqlcipher3_mutex_alloc()] </li>
6015 **   <li>  [sqlcipher3_mutex_free()] </li>
6016 **   <li>  [sqlcipher3_mutex_enter()] </li>
6017 **   <li>  [sqlcipher3_mutex_try()] </li>
6018 **   <li>  [sqlcipher3_mutex_leave()] </li>
6019 **   <li>  [sqlcipher3_mutex_held()] </li>
6020 **   <li>  [sqlcipher3_mutex_notheld()] </li>
6021 ** </ul>)^
6022 **
6023 ** The only difference is that the public sqlcipher3_XXX functions enumerated
6024 ** above silently ignore any invocations that pass a NULL pointer instead
6025 ** of a valid mutex handle. The implementations of the methods defined
6026 ** by this structure are not required to handle this case, the results
6027 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6028 ** (i.e. it is acceptable to provide an implementation that segfaults if
6029 ** it is passed a NULL pointer).
6030 **
6031 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
6032 ** invoke xMutexInit() multiple times within the same process and without
6033 ** intervening calls to xMutexEnd().  Second and subsequent calls to
6034 ** xMutexInit() must be no-ops.
6035 **
6036 ** ^xMutexInit() must not use SQLite memory allocation ([sqlcipher3_malloc()]
6037 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
6038 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6039 ** memory allocation for a fast or recursive mutex.
6040 **
6041 ** ^SQLite will invoke the xMutexEnd() method when [sqlcipher3_shutdown()] is
6042 ** called, but only if the prior call to xMutexInit returned SQLCIPHER_OK.
6043 ** If xMutexInit fails in any way, it is expected to clean up after itself
6044 ** prior to returning.
6045 */
6046 typedef struct sqlcipher3_mutex_methods sqlcipher3_mutex_methods;
6047 struct sqlcipher3_mutex_methods {
6048   int (*xMutexInit)(void);
6049   int (*xMutexEnd)(void);
6050   sqlcipher3_mutex *(*xMutexAlloc)(int);
6051   void (*xMutexFree)(sqlcipher3_mutex *);
6052   void (*xMutexEnter)(sqlcipher3_mutex *);
6053   int (*xMutexTry)(sqlcipher3_mutex *);
6054   void (*xMutexLeave)(sqlcipher3_mutex *);
6055   int (*xMutexHeld)(sqlcipher3_mutex *);
6056   int (*xMutexNotheld)(sqlcipher3_mutex *);
6057 };
6058
6059 /*
6060 ** CAPI3REF: Mutex Verification Routines
6061 **
6062 ** The sqlcipher3_mutex_held() and sqlcipher3_mutex_notheld() routines
6063 ** are intended for use inside assert() statements.  ^The SQLite core
6064 ** never uses these routines except inside an assert() and applications
6065 ** are advised to follow the lead of the core.  ^The SQLite core only
6066 ** provides implementations for these routines when it is compiled
6067 ** with the SQLCIPHER_DEBUG flag.  ^External mutex implementations
6068 ** are only required to provide these routines if SQLCIPHER_DEBUG is
6069 ** defined and if NDEBUG is not defined.
6070 **
6071 ** ^These routines should return true if the mutex in their argument
6072 ** is held or not held, respectively, by the calling thread.
6073 **
6074 ** ^The implementation is not required to provided versions of these
6075 ** routines that actually work. If the implementation does not provide working
6076 ** versions of these routines, it should at least provide stubs that always
6077 ** return true so that one does not get spurious assertion failures.
6078 **
6079 ** ^If the argument to sqlcipher3_mutex_held() is a NULL pointer then
6080 ** the routine should return 1.   This seems counter-intuitive since
6081 ** clearly the mutex cannot be held if it does not exist.  But
6082 ** the reason the mutex does not exist is because the build is not
6083 ** using mutexes.  And we do not want the assert() containing the
6084 ** call to sqlcipher3_mutex_held() to fail, so a non-zero return is
6085 ** the appropriate thing to do.  ^The sqlcipher3_mutex_notheld()
6086 ** interface should also return 1 when given a NULL pointer.
6087 */
6088 #ifndef NDEBUG
6089 SQLCIPHER_API int sqlcipher3_mutex_held(sqlcipher3_mutex*);
6090 SQLCIPHER_API int sqlcipher3_mutex_notheld(sqlcipher3_mutex*);
6091 #endif
6092
6093 /*
6094 ** CAPI3REF: Mutex Types
6095 **
6096 ** The [sqlcipher3_mutex_alloc()] interface takes a single argument
6097 ** which is one of these integer constants.
6098 **
6099 ** The set of static mutexes may change from one SQLite release to the
6100 ** next.  Applications that override the built-in mutex logic must be
6101 ** prepared to accommodate additional static mutexes.
6102 */
6103 #define SQLCIPHER_MUTEX_FAST             0
6104 #define SQLCIPHER_MUTEX_RECURSIVE        1
6105 #define SQLCIPHER_MUTEX_STATIC_MASTER    2
6106 #define SQLCIPHER_MUTEX_STATIC_MEM       3  /* sqlcipher3_malloc() */
6107 #define SQLCIPHER_MUTEX_STATIC_MEM2      4  /* NOT USED */
6108 #define SQLCIPHER_MUTEX_STATIC_OPEN      4  /* sqlcipher3BtreeOpen() */
6109 #define SQLCIPHER_MUTEX_STATIC_PRNG      5  /* sqlcipher3_random() */
6110 #define SQLCIPHER_MUTEX_STATIC_LRU       6  /* lru page list */
6111 #define SQLCIPHER_MUTEX_STATIC_LRU2      7  /* NOT USED */
6112 #define SQLCIPHER_MUTEX_STATIC_PMEM      7  /* sqlcipher3PageMalloc() */
6113
6114 /*
6115 ** CAPI3REF: Retrieve the mutex for a database connection
6116 **
6117 ** ^This interface returns a pointer the [sqlcipher3_mutex] object that 
6118 ** serializes access to the [database connection] given in the argument
6119 ** when the [threading mode] is Serialized.
6120 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6121 ** routine returns a NULL pointer.
6122 */
6123 SQLCIPHER_API sqlcipher3_mutex *sqlcipher3_db_mutex(sqlcipher3*);
6124
6125 /*
6126 ** CAPI3REF: Low-Level Control Of Database Files
6127 **
6128 ** ^The [sqlcipher3_file_control()] interface makes a direct call to the
6129 ** xFileControl method for the [sqlcipher3_io_methods] object associated
6130 ** with a particular database identified by the second argument. ^The
6131 ** name of the database is "main" for the main database or "temp" for the
6132 ** TEMP database, or the name that appears after the AS keyword for
6133 ** databases that are added using the [ATTACH] SQL command.
6134 ** ^A NULL pointer can be used in place of "main" to refer to the
6135 ** main database file.
6136 ** ^The third and fourth parameters to this routine
6137 ** are passed directly through to the second and third parameters of
6138 ** the xFileControl method.  ^The return value of the xFileControl
6139 ** method becomes the return value of this routine.
6140 **
6141 ** ^The SQLCIPHER_FCNTL_FILE_POINTER value for the op parameter causes
6142 ** a pointer to the underlying [sqlcipher3_file] object to be written into
6143 ** the space pointed to by the 4th parameter.  ^The SQLCIPHER_FCNTL_FILE_POINTER
6144 ** case is a short-circuit path which does not actually invoke the
6145 ** underlying sqlcipher3_io_methods.xFileControl method.
6146 **
6147 ** ^If the second parameter (zDbName) does not match the name of any
6148 ** open database file, then SQLCIPHER_ERROR is returned.  ^This error
6149 ** code is not remembered and will not be recalled by [sqlcipher3_errcode()]
6150 ** or [sqlcipher3_errmsg()].  The underlying xFileControl method might
6151 ** also return SQLCIPHER_ERROR.  There is no way to distinguish between
6152 ** an incorrect zDbName and an SQLCIPHER_ERROR return from the underlying
6153 ** xFileControl method.
6154 **
6155 ** See also: [SQLCIPHER_FCNTL_LOCKSTATE]
6156 */
6157 SQLCIPHER_API int sqlcipher3_file_control(sqlcipher3*, const char *zDbName, int op, void*);
6158
6159 /*
6160 ** CAPI3REF: Testing Interface
6161 **
6162 ** ^The sqlcipher3_test_control() interface is used to read out internal
6163 ** state of SQLite and to inject faults into SQLite for testing
6164 ** purposes.  ^The first parameter is an operation code that determines
6165 ** the number, meaning, and operation of all subsequent parameters.
6166 **
6167 ** This interface is not for use by applications.  It exists solely
6168 ** for verifying the correct operation of the SQLite library.  Depending
6169 ** on how the SQLite library is compiled, this interface might not exist.
6170 **
6171 ** The details of the operation codes, their meanings, the parameters
6172 ** they take, and what they do are all subject to change without notice.
6173 ** Unlike most of the SQLite API, this function is not guaranteed to
6174 ** operate consistently from one release to the next.
6175 */
6176 SQLCIPHER_API int sqlcipher3_test_control(int op, ...);
6177
6178 /*
6179 ** CAPI3REF: Testing Interface Operation Codes
6180 **
6181 ** These constants are the valid operation code parameters used
6182 ** as the first argument to [sqlcipher3_test_control()].
6183 **
6184 ** These parameters and their meanings are subject to change
6185 ** without notice.  These values are for testing purposes only.
6186 ** Applications should not use any of these parameters or the
6187 ** [sqlcipher3_test_control()] interface.
6188 */
6189 #define SQLCIPHER_TESTCTRL_FIRST                    5
6190 #define SQLCIPHER_TESTCTRL_PRNG_SAVE                5
6191 #define SQLCIPHER_TESTCTRL_PRNG_RESTORE             6
6192 #define SQLCIPHER_TESTCTRL_PRNG_RESET               7
6193 #define SQLCIPHER_TESTCTRL_BITVEC_TEST              8
6194 #define SQLCIPHER_TESTCTRL_FAULT_INSTALL            9
6195 #define SQLCIPHER_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6196 #define SQLCIPHER_TESTCTRL_PENDING_BYTE            11
6197 #define SQLCIPHER_TESTCTRL_ASSERT                  12
6198 #define SQLCIPHER_TESTCTRL_ALWAYS                  13
6199 #define SQLCIPHER_TESTCTRL_RESERVE                 14
6200 #define SQLCIPHER_TESTCTRL_OPTIMIZATIONS           15
6201 #define SQLCIPHER_TESTCTRL_ISKEYWORD               16
6202 #define SQLCIPHER_TESTCTRL_PGHDRSZ                 17
6203 #define SQLCIPHER_TESTCTRL_SCRATCHMALLOC           18
6204 #define SQLCIPHER_TESTCTRL_LOCALTIME_FAULT         19
6205 #define SQLCIPHER_TESTCTRL_LAST                    19
6206
6207 /*
6208 ** CAPI3REF: SQLite Runtime Status
6209 **
6210 ** ^This interface is used to retrieve runtime status information
6211 ** about the performance of SQLite, and optionally to reset various
6212 ** highwater marks.  ^The first argument is an integer code for
6213 ** the specific parameter to measure.  ^(Recognized integer codes
6214 ** are of the form [status parameters | SQLCIPHER_STATUS_...].)^
6215 ** ^The current value of the parameter is returned into *pCurrent.
6216 ** ^The highest recorded value is returned in *pHighwater.  ^If the
6217 ** resetFlag is true, then the highest record value is reset after
6218 ** *pHighwater is written.  ^(Some parameters do not record the highest
6219 ** value.  For those parameters
6220 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6221 ** ^(Other parameters record only the highwater mark and not the current
6222 ** value.  For these latter parameters nothing is written into *pCurrent.)^
6223 **
6224 ** ^The sqlcipher3_status() routine returns SQLCIPHER_OK on success and a
6225 ** non-zero [error code] on failure.
6226 **
6227 ** This routine is threadsafe but is not atomic.  This routine can be
6228 ** called while other threads are running the same or different SQLite
6229 ** interfaces.  However the values returned in *pCurrent and
6230 ** *pHighwater reflect the status of SQLite at different points in time
6231 ** and it is possible that another thread might change the parameter
6232 ** in between the times when *pCurrent and *pHighwater are written.
6233 **
6234 ** See also: [sqlcipher3_db_status()]
6235 */
6236 SQLCIPHER_API int sqlcipher3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6237
6238
6239 /*
6240 ** CAPI3REF: Status Parameters
6241 ** KEYWORDS: {status parameters}
6242 **
6243 ** These integer constants designate various run-time status parameters
6244 ** that can be returned by [sqlcipher3_status()].
6245 **
6246 ** <dl>
6247 ** [[SQLCIPHER_STATUS_MEMORY_USED]] ^(<dt>SQLCIPHER_STATUS_MEMORY_USED</dt>
6248 ** <dd>This parameter is the current amount of memory checked out
6249 ** using [sqlcipher3_malloc()], either directly or indirectly.  The
6250 ** figure includes calls made to [sqlcipher3_malloc()] by the application
6251 ** and internal memory usage by the SQLite library.  Scratch memory
6252 ** controlled by [SQLCIPHER_CONFIG_SCRATCH] and auxiliary page-cache
6253 ** memory controlled by [SQLCIPHER_CONFIG_PAGECACHE] is not included in
6254 ** this parameter.  The amount returned is the sum of the allocation
6255 ** sizes as reported by the xSize method in [sqlcipher3_mem_methods].</dd>)^
6256 **
6257 ** [[SQLCIPHER_STATUS_MALLOC_SIZE]] ^(<dt>SQLCIPHER_STATUS_MALLOC_SIZE</dt>
6258 ** <dd>This parameter records the largest memory allocation request
6259 ** handed to [sqlcipher3_malloc()] or [sqlcipher3_realloc()] (or their
6260 ** internal equivalents).  Only the value returned in the
6261 ** *pHighwater parameter to [sqlcipher3_status()] is of interest.  
6262 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6263 **
6264 ** [[SQLCIPHER_STATUS_MALLOC_COUNT]] ^(<dt>SQLCIPHER_STATUS_MALLOC_COUNT</dt>
6265 ** <dd>This parameter records the number of separate memory allocations
6266 ** currently checked out.</dd>)^
6267 **
6268 ** [[SQLCIPHER_STATUS_PAGECACHE_USED]] ^(<dt>SQLCIPHER_STATUS_PAGECACHE_USED</dt>
6269 ** <dd>This parameter returns the number of pages used out of the
6270 ** [pagecache memory allocator] that was configured using 
6271 ** [SQLCIPHER_CONFIG_PAGECACHE].  The
6272 ** value returned is in pages, not in bytes.</dd>)^
6273 **
6274 ** [[SQLCIPHER_STATUS_PAGECACHE_OVERFLOW]] 
6275 ** ^(<dt>SQLCIPHER_STATUS_PAGECACHE_OVERFLOW</dt>
6276 ** <dd>This parameter returns the number of bytes of page cache
6277 ** allocation which could not be satisfied by the [SQLCIPHER_CONFIG_PAGECACHE]
6278 ** buffer and where forced to overflow to [sqlcipher3_malloc()].  The
6279 ** returned value includes allocations that overflowed because they
6280 ** where too large (they were larger than the "sz" parameter to
6281 ** [SQLCIPHER_CONFIG_PAGECACHE]) and allocations that overflowed because
6282 ** no space was left in the page cache.</dd>)^
6283 **
6284 ** [[SQLCIPHER_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLCIPHER_STATUS_PAGECACHE_SIZE</dt>
6285 ** <dd>This parameter records the largest memory allocation request
6286 ** handed to [pagecache memory allocator].  Only the value returned in the
6287 ** *pHighwater parameter to [sqlcipher3_status()] is of interest.  
6288 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6289 **
6290 ** [[SQLCIPHER_STATUS_SCRATCH_USED]] ^(<dt>SQLCIPHER_STATUS_SCRATCH_USED</dt>
6291 ** <dd>This parameter returns the number of allocations used out of the
6292 ** [scratch memory allocator] configured using
6293 ** [SQLCIPHER_CONFIG_SCRATCH].  The value returned is in allocations, not
6294 ** in bytes.  Since a single thread may only have one scratch allocation
6295 ** outstanding at time, this parameter also reports the number of threads
6296 ** using scratch memory at the same time.</dd>)^
6297 **
6298 ** [[SQLCIPHER_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLCIPHER_STATUS_SCRATCH_OVERFLOW</dt>
6299 ** <dd>This parameter returns the number of bytes of scratch memory
6300 ** allocation which could not be satisfied by the [SQLCIPHER_CONFIG_SCRATCH]
6301 ** buffer and where forced to overflow to [sqlcipher3_malloc()].  The values
6302 ** returned include overflows because the requested allocation was too
6303 ** larger (that is, because the requested allocation was larger than the
6304 ** "sz" parameter to [SQLCIPHER_CONFIG_SCRATCH]) and because no scratch buffer
6305 ** slots were available.
6306 ** </dd>)^
6307 **
6308 ** [[SQLCIPHER_STATUS_SCRATCH_SIZE]] ^(<dt>SQLCIPHER_STATUS_SCRATCH_SIZE</dt>
6309 ** <dd>This parameter records the largest memory allocation request
6310 ** handed to [scratch memory allocator].  Only the value returned in the
6311 ** *pHighwater parameter to [sqlcipher3_status()] is of interest.  
6312 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6313 **
6314 ** [[SQLCIPHER_STATUS_PARSER_STACK]] ^(<dt>SQLCIPHER_STATUS_PARSER_STACK</dt>
6315 ** <dd>This parameter records the deepest parser stack.  It is only
6316 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6317 ** </dl>
6318 **
6319 ** New status parameters may be added from time to time.
6320 */
6321 #define SQLCIPHER_STATUS_MEMORY_USED          0
6322 #define SQLCIPHER_STATUS_PAGECACHE_USED       1
6323 #define SQLCIPHER_STATUS_PAGECACHE_OVERFLOW   2
6324 #define SQLCIPHER_STATUS_SCRATCH_USED         3
6325 #define SQLCIPHER_STATUS_SCRATCH_OVERFLOW     4
6326 #define SQLCIPHER_STATUS_MALLOC_SIZE          5
6327 #define SQLCIPHER_STATUS_PARSER_STACK         6
6328 #define SQLCIPHER_STATUS_PAGECACHE_SIZE       7
6329 #define SQLCIPHER_STATUS_SCRATCH_SIZE         8
6330 #define SQLCIPHER_STATUS_MALLOC_COUNT         9
6331
6332 /*
6333 ** CAPI3REF: Database Connection Status
6334 **
6335 ** ^This interface is used to retrieve runtime status information 
6336 ** about a single [database connection].  ^The first argument is the
6337 ** database connection object to be interrogated.  ^The second argument
6338 ** is an integer constant, taken from the set of
6339 ** [SQLCIPHER_DBSTATUS options], that
6340 ** determines the parameter to interrogate.  The set of 
6341 ** [SQLCIPHER_DBSTATUS options] is likely
6342 ** to grow in future releases of SQLite.
6343 **
6344 ** ^The current value of the requested parameter is written into *pCur
6345 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6346 ** the resetFlg is true, then the highest instantaneous value is
6347 ** reset back down to the current value.
6348 **
6349 ** ^The sqlcipher3_db_status() routine returns SQLCIPHER_OK on success and a
6350 ** non-zero [error code] on failure.
6351 **
6352 ** See also: [sqlcipher3_status()] and [sqlcipher3_stmt_status()].
6353 */
6354 SQLCIPHER_API int sqlcipher3_db_status(sqlcipher3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6355
6356 /*
6357 ** CAPI3REF: Status Parameters for database connections
6358 ** KEYWORDS: {SQLCIPHER_DBSTATUS options}
6359 **
6360 ** These constants are the available integer "verbs" that can be passed as
6361 ** the second argument to the [sqlcipher3_db_status()] interface.
6362 **
6363 ** New verbs may be added in future releases of SQLite. Existing verbs
6364 ** might be discontinued. Applications should check the return code from
6365 ** [sqlcipher3_db_status()] to make sure that the call worked.
6366 ** The [sqlcipher3_db_status()] interface will return a non-zero error code
6367 ** if a discontinued or unsupported verb is invoked.
6368 **
6369 ** <dl>
6370 ** [[SQLCIPHER_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLCIPHER_DBSTATUS_LOOKASIDE_USED</dt>
6371 ** <dd>This parameter returns the number of lookaside memory slots currently
6372 ** checked out.</dd>)^
6373 **
6374 ** [[SQLCIPHER_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLCIPHER_DBSTATUS_LOOKASIDE_HIT</dt>
6375 ** <dd>This parameter returns the number malloc attempts that were 
6376 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6377 ** the current value is always zero.)^
6378 **
6379 ** [[SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6380 ** ^(<dt>SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6381 ** <dd>This parameter returns the number malloc attempts that might have
6382 ** been satisfied using lookaside memory but failed due to the amount of
6383 ** memory requested being larger than the lookaside slot size.
6384 ** Only the high-water value is meaningful;
6385 ** the current value is always zero.)^
6386 **
6387 ** [[SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_FULL]]
6388 ** ^(<dt>SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6389 ** <dd>This parameter returns the number malloc attempts that might have
6390 ** been satisfied using lookaside memory but failed due to all lookaside
6391 ** memory already being in use.
6392 ** Only the high-water value is meaningful;
6393 ** the current value is always zero.)^
6394 **
6395 ** [[SQLCIPHER_DBSTATUS_CACHE_USED]] ^(<dt>SQLCIPHER_DBSTATUS_CACHE_USED</dt>
6396 ** <dd>This parameter returns the approximate number of of bytes of heap
6397 ** memory used by all pager caches associated with the database connection.)^
6398 ** ^The highwater mark associated with SQLCIPHER_DBSTATUS_CACHE_USED is always 0.
6399 **
6400 ** [[SQLCIPHER_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLCIPHER_DBSTATUS_SCHEMA_USED</dt>
6401 ** <dd>This parameter returns the approximate number of of bytes of heap
6402 ** memory used to store the schema for all databases associated
6403 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
6404 ** ^The full amount of memory used by the schemas is reported, even if the
6405 ** schema memory is shared with other database connections due to
6406 ** [shared cache mode] being enabled.
6407 ** ^The highwater mark associated with SQLCIPHER_DBSTATUS_SCHEMA_USED is always 0.
6408 **
6409 ** [[SQLCIPHER_DBSTATUS_STMT_USED]] ^(<dt>SQLCIPHER_DBSTATUS_STMT_USED</dt>
6410 ** <dd>This parameter returns the approximate number of of bytes of heap
6411 ** and lookaside memory used by all prepared statements associated with
6412 ** the database connection.)^
6413 ** ^The highwater mark associated with SQLCIPHER_DBSTATUS_STMT_USED is always 0.
6414 ** </dd>
6415 **
6416 ** [[SQLCIPHER_DBSTATUS_CACHE_HIT]] ^(<dt>SQLCIPHER_DBSTATUS_CACHE_HIT</dt>
6417 ** <dd>This parameter returns the number of pager cache hits that have
6418 ** occurred.)^ ^The highwater mark associated with SQLCIPHER_DBSTATUS_CACHE_HIT 
6419 ** is always 0.
6420 ** </dd>
6421 **
6422 ** [[SQLCIPHER_DBSTATUS_CACHE_MISS]] ^(<dt>SQLCIPHER_DBSTATUS_CACHE_MISS</dt>
6423 ** <dd>This parameter returns the number of pager cache misses that have
6424 ** occurred.)^ ^The highwater mark associated with SQLCIPHER_DBSTATUS_CACHE_MISS 
6425 ** is always 0.
6426 ** </dd>
6427 ** </dl>
6428 */
6429 #define SQLCIPHER_DBSTATUS_LOOKASIDE_USED       0
6430 #define SQLCIPHER_DBSTATUS_CACHE_USED           1
6431 #define SQLCIPHER_DBSTATUS_SCHEMA_USED          2
6432 #define SQLCIPHER_DBSTATUS_STMT_USED            3
6433 #define SQLCIPHER_DBSTATUS_LOOKASIDE_HIT        4
6434 #define SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6435 #define SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_FULL  6
6436 #define SQLCIPHER_DBSTATUS_CACHE_HIT            7
6437 #define SQLCIPHER_DBSTATUS_CACHE_MISS           8
6438 #define SQLCIPHER_DBSTATUS_MAX                  8   /* Largest defined DBSTATUS */
6439
6440
6441 /*
6442 ** CAPI3REF: Prepared Statement Status
6443 **
6444 ** ^(Each prepared statement maintains various
6445 ** [SQLCIPHER_STMTSTATUS counters] that measure the number
6446 ** of times it has performed specific operations.)^  These counters can
6447 ** be used to monitor the performance characteristics of the prepared
6448 ** statements.  For example, if the number of table steps greatly exceeds
6449 ** the number of table searches or result rows, that would tend to indicate
6450 ** that the prepared statement is using a full table scan rather than
6451 ** an index.  
6452 **
6453 ** ^(This interface is used to retrieve and reset counter values from
6454 ** a [prepared statement].  The first argument is the prepared statement
6455 ** object to be interrogated.  The second argument
6456 ** is an integer code for a specific [SQLCIPHER_STMTSTATUS counter]
6457 ** to be interrogated.)^
6458 ** ^The current value of the requested counter is returned.
6459 ** ^If the resetFlg is true, then the counter is reset to zero after this
6460 ** interface call returns.
6461 **
6462 ** See also: [sqlcipher3_status()] and [sqlcipher3_db_status()].
6463 */
6464 SQLCIPHER_API int sqlcipher3_stmt_status(sqlcipher3_stmt*, int op,int resetFlg);
6465
6466 /*
6467 ** CAPI3REF: Status Parameters for prepared statements
6468 ** KEYWORDS: {SQLCIPHER_STMTSTATUS counter} {SQLCIPHER_STMTSTATUS counters}
6469 **
6470 ** These preprocessor macros define integer codes that name counter
6471 ** values associated with the [sqlcipher3_stmt_status()] interface.
6472 ** The meanings of the various counters are as follows:
6473 **
6474 ** <dl>
6475 ** [[SQLCIPHER_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLCIPHER_STMTSTATUS_FULLSCAN_STEP</dt>
6476 ** <dd>^This is the number of times that SQLite has stepped forward in
6477 ** a table as part of a full table scan.  Large numbers for this counter
6478 ** may indicate opportunities for performance improvement through 
6479 ** careful use of indices.</dd>
6480 **
6481 ** [[SQLCIPHER_STMTSTATUS_SORT]] <dt>SQLCIPHER_STMTSTATUS_SORT</dt>
6482 ** <dd>^This is the number of sort operations that have occurred.
6483 ** A non-zero value in this counter may indicate an opportunity to
6484 ** improvement performance through careful use of indices.</dd>
6485 **
6486 ** [[SQLCIPHER_STMTSTATUS_AUTOINDEX]] <dt>SQLCIPHER_STMTSTATUS_AUTOINDEX</dt>
6487 ** <dd>^This is the number of rows inserted into transient indices that
6488 ** were created automatically in order to help joins run faster.
6489 ** A non-zero value in this counter may indicate an opportunity to
6490 ** improvement performance by adding permanent indices that do not
6491 ** need to be reinitialized each time the statement is run.</dd>
6492 ** </dl>
6493 */
6494 #define SQLCIPHER_STMTSTATUS_FULLSCAN_STEP     1
6495 #define SQLCIPHER_STMTSTATUS_SORT              2
6496 #define SQLCIPHER_STMTSTATUS_AUTOINDEX         3
6497
6498 /*
6499 ** CAPI3REF: Custom Page Cache Object
6500 **
6501 ** The sqlcipher3_pcache type is opaque.  It is implemented by
6502 ** the pluggable module.  The SQLite core has no knowledge of
6503 ** its size or internal structure and never deals with the
6504 ** sqlcipher3_pcache object except by holding and passing pointers
6505 ** to the object.
6506 **
6507 ** See [sqlcipher3_pcache_methods] for additional information.
6508 */
6509 typedef struct sqlcipher3_pcache sqlcipher3_pcache;
6510
6511 /*
6512 ** CAPI3REF: Application Defined Page Cache.
6513 ** KEYWORDS: {page cache}
6514 **
6515 ** ^(The [sqlcipher3_config]([SQLCIPHER_CONFIG_PCACHE], ...) interface can
6516 ** register an alternative page cache implementation by passing in an 
6517 ** instance of the sqlcipher3_pcache_methods structure.)^
6518 ** In many applications, most of the heap memory allocated by 
6519 ** SQLite is used for the page cache.
6520 ** By implementing a 
6521 ** custom page cache using this API, an application can better control
6522 ** the amount of memory consumed by SQLite, the way in which 
6523 ** that memory is allocated and released, and the policies used to 
6524 ** determine exactly which parts of a database file are cached and for 
6525 ** how long.
6526 **
6527 ** The alternative page cache mechanism is an
6528 ** extreme measure that is only needed by the most demanding applications.
6529 ** The built-in page cache is recommended for most uses.
6530 **
6531 ** ^(The contents of the sqlcipher3_pcache_methods structure are copied to an
6532 ** internal buffer by SQLite within the call to [sqlcipher3_config].  Hence
6533 ** the application may discard the parameter after the call to
6534 ** [sqlcipher3_config()] returns.)^
6535 **
6536 ** [[the xInit() page cache method]]
6537 ** ^(The xInit() method is called once for each effective 
6538 ** call to [sqlcipher3_initialize()])^
6539 ** (usually only once during the lifetime of the process). ^(The xInit()
6540 ** method is passed a copy of the sqlcipher3_pcache_methods.pArg value.)^
6541 ** The intent of the xInit() method is to set up global data structures 
6542 ** required by the custom page cache implementation. 
6543 ** ^(If the xInit() method is NULL, then the 
6544 ** built-in default page cache is used instead of the application defined
6545 ** page cache.)^
6546 **
6547 ** [[the xShutdown() page cache method]]
6548 ** ^The xShutdown() method is called by [sqlcipher3_shutdown()].
6549 ** It can be used to clean up 
6550 ** any outstanding resources before process shutdown, if required.
6551 ** ^The xShutdown() method may be NULL.
6552 **
6553 ** ^SQLite automatically serializes calls to the xInit method,
6554 ** so the xInit method need not be threadsafe.  ^The
6555 ** xShutdown method is only called from [sqlcipher3_shutdown()] so it does
6556 ** not need to be threadsafe either.  All other methods must be threadsafe
6557 ** in multithreaded applications.
6558 **
6559 ** ^SQLite will never invoke xInit() more than once without an intervening
6560 ** call to xShutdown().
6561 **
6562 ** [[the xCreate() page cache methods]]
6563 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6564 ** SQLite will typically create one cache instance for each open database file,
6565 ** though this is not guaranteed. ^The
6566 ** first parameter, szPage, is the size in bytes of the pages that must
6567 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
6568 ** will the page size of the database file that is to be cached plus an
6569 ** increment (here called "R") of less than 250.  SQLite will use the
6570 ** extra R bytes on each page to store metadata about the underlying
6571 ** database page on disk.  The value of R depends
6572 ** on the SQLite version, the target platform, and how SQLite was compiled.
6573 ** ^(R is constant for a particular build of SQLite. Except, there are two
6574 ** distinct values of R when SQLite is compiled with the proprietary
6575 ** ZIPVFS extension.)^  ^The second argument to
6576 ** xCreate(), bPurgeable, is true if the cache being created will
6577 ** be used to cache database pages of a file stored on disk, or
6578 ** false if it is used for an in-memory database. The cache implementation
6579 ** does not have to do anything special based with the value of bPurgeable;
6580 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6581 ** never invoke xUnpin() except to deliberately delete a page.
6582 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6583 ** false will always have the "discard" flag set to true.  
6584 ** ^Hence, a cache created with bPurgeable false will
6585 ** never contain any unpinned pages.
6586 **
6587 ** [[the xCachesize() page cache method]]
6588 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6589 ** suggested maximum cache-size (number of pages stored by) the cache
6590 ** instance passed as the first argument. This is the value configured using
6591 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6592 ** parameter, the implementation is not required to do anything with this
6593 ** value; it is advisory only.
6594 **
6595 ** [[the xPagecount() page cache methods]]
6596 ** The xPagecount() method must return the number of pages currently
6597 ** stored in the cache, both pinned and unpinned.
6598 ** 
6599 ** [[the xFetch() page cache methods]]
6600 ** The xFetch() method locates a page in the cache and returns a pointer to 
6601 ** the page, or a NULL pointer.
6602 ** A "page", in this context, means a buffer of szPage bytes aligned at an
6603 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
6604 ** minimum key value is 1.  After it has been retrieved using xFetch, the page 
6605 ** is considered to be "pinned".
6606 **
6607 ** If the requested page is already in the page cache, then the page cache
6608 ** implementation must return a pointer to the page buffer with its content
6609 ** intact.  If the requested page is not already in the cache, then the
6610 ** cache implementation should use the value of the createFlag
6611 ** parameter to help it determined what action to take:
6612 **
6613 ** <table border=1 width=85% align=center>
6614 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6615 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6616 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6617 **                 Otherwise return NULL.
6618 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6619 **                 NULL if allocating a new page is effectively impossible.
6620 ** </table>
6621 **
6622 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6623 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6624 ** failed.)^  In between the to xFetch() calls, SQLite may
6625 ** attempt to unpin one or more cache pages by spilling the content of
6626 ** pinned pages to disk and synching the operating system disk cache.
6627 **
6628 ** [[the xUnpin() page cache method]]
6629 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6630 ** as its second argument.  If the third parameter, discard, is non-zero,
6631 ** then the page must be evicted from the cache.
6632 ** ^If the discard parameter is
6633 ** zero, then the page may be discarded or retained at the discretion of
6634 ** page cache implementation. ^The page cache implementation
6635 ** may choose to evict unpinned pages at any time.
6636 **
6637 ** The cache must not perform any reference counting. A single 
6638 ** call to xUnpin() unpins the page regardless of the number of prior calls 
6639 ** to xFetch().
6640 **
6641 ** [[the xRekey() page cache methods]]
6642 ** The xRekey() method is used to change the key value associated with the
6643 ** page passed as the second argument. If the cache
6644 ** previously contains an entry associated with newKey, it must be
6645 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6646 ** to be pinned.
6647 **
6648 ** When SQLite calls the xTruncate() method, the cache must discard all
6649 ** existing cache entries with page numbers (keys) greater than or equal
6650 ** to the value of the iLimit parameter passed to xTruncate(). If any
6651 ** of these pages are pinned, they are implicitly unpinned, meaning that
6652 ** they can be safely discarded.
6653 **
6654 ** [[the xDestroy() page cache method]]
6655 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6656 ** All resources associated with the specified cache should be freed. ^After
6657 ** calling the xDestroy() method, SQLite considers the [sqlcipher3_pcache*]
6658 ** handle invalid, and will not use it with any other sqlcipher3_pcache_methods
6659 ** functions.
6660 */
6661 typedef struct sqlcipher3_pcache_methods sqlcipher3_pcache_methods;
6662 struct sqlcipher3_pcache_methods {
6663   void *pArg;
6664   int (*xInit)(void*);
6665   void (*xShutdown)(void*);
6666   sqlcipher3_pcache *(*xCreate)(int szPage, int bPurgeable);
6667   void (*xCachesize)(sqlcipher3_pcache*, int nCachesize);
6668   int (*xPagecount)(sqlcipher3_pcache*);
6669   void *(*xFetch)(sqlcipher3_pcache*, unsigned key, int createFlag);
6670   void (*xUnpin)(sqlcipher3_pcache*, void*, int discard);
6671   void (*xRekey)(sqlcipher3_pcache*, void*, unsigned oldKey, unsigned newKey);
6672   void (*xTruncate)(sqlcipher3_pcache*, unsigned iLimit);
6673   void (*xDestroy)(sqlcipher3_pcache*);
6674 };
6675
6676 /*
6677 ** CAPI3REF: Online Backup Object
6678 **
6679 ** The sqlcipher3_backup object records state information about an ongoing
6680 ** online backup operation.  ^The sqlcipher3_backup object is created by
6681 ** a call to [sqlcipher3_backup_init()] and is destroyed by a call to
6682 ** [sqlcipher3_backup_finish()].
6683 **
6684 ** See Also: [Using the SQLite Online Backup API]
6685 */
6686 typedef struct sqlcipher3_backup sqlcipher3_backup;
6687
6688 /*
6689 ** CAPI3REF: Online Backup API.
6690 **
6691 ** The backup API copies the content of one database into another.
6692 ** It is useful either for creating backups of databases or
6693 ** for copying in-memory databases to or from persistent files. 
6694 **
6695 ** See Also: [Using the SQLite Online Backup API]
6696 **
6697 ** ^SQLite holds a write transaction open on the destination database file
6698 ** for the duration of the backup operation.
6699 ** ^The source database is read-locked only while it is being read;
6700 ** it is not locked continuously for the entire backup operation.
6701 ** ^Thus, the backup may be performed on a live source database without
6702 ** preventing other database connections from
6703 ** reading or writing to the source database while the backup is underway.
6704 ** 
6705 ** ^(To perform a backup operation: 
6706 **   <ol>
6707 **     <li><b>sqlcipher3_backup_init()</b> is called once to initialize the
6708 **         backup, 
6709 **     <li><b>sqlcipher3_backup_step()</b> is called one or more times to transfer 
6710 **         the data between the two databases, and finally
6711 **     <li><b>sqlcipher3_backup_finish()</b> is called to release all resources 
6712 **         associated with the backup operation. 
6713 **   </ol>)^
6714 ** There should be exactly one call to sqlcipher3_backup_finish() for each
6715 ** successful call to sqlcipher3_backup_init().
6716 **
6717 ** [[sqlcipher3_backup_init()]] <b>sqlcipher3_backup_init()</b>
6718 **
6719 ** ^The D and N arguments to sqlcipher3_backup_init(D,N,S,M) are the 
6720 ** [database connection] associated with the destination database 
6721 ** and the database name, respectively.
6722 ** ^The database name is "main" for the main database, "temp" for the
6723 ** temporary database, or the name specified after the AS keyword in
6724 ** an [ATTACH] statement for an attached database.
6725 ** ^The S and M arguments passed to 
6726 ** sqlcipher3_backup_init(D,N,S,M) identify the [database connection]
6727 ** and database name of the source database, respectively.
6728 ** ^The source and destination [database connections] (parameters S and D)
6729 ** must be different or else sqlcipher3_backup_init(D,N,S,M) will fail with
6730 ** an error.
6731 **
6732 ** ^If an error occurs within sqlcipher3_backup_init(D,N,S,M), then NULL is
6733 ** returned and an error code and error message are stored in the
6734 ** destination [database connection] D.
6735 ** ^The error code and message for the failed call to sqlcipher3_backup_init()
6736 ** can be retrieved using the [sqlcipher3_errcode()], [sqlcipher3_errmsg()], and/or
6737 ** [sqlcipher3_errmsg16()] functions.
6738 ** ^A successful call to sqlcipher3_backup_init() returns a pointer to an
6739 ** [sqlcipher3_backup] object.
6740 ** ^The [sqlcipher3_backup] object may be used with the sqlcipher3_backup_step() and
6741 ** sqlcipher3_backup_finish() functions to perform the specified backup 
6742 ** operation.
6743 **
6744 ** [[sqlcipher3_backup_step()]] <b>sqlcipher3_backup_step()</b>
6745 **
6746 ** ^Function sqlcipher3_backup_step(B,N) will copy up to N pages between 
6747 ** the source and destination databases specified by [sqlcipher3_backup] object B.
6748 ** ^If N is negative, all remaining source pages are copied. 
6749 ** ^If sqlcipher3_backup_step(B,N) successfully copies N pages and there
6750 ** are still more pages to be copied, then the function returns [SQLCIPHER_OK].
6751 ** ^If sqlcipher3_backup_step(B,N) successfully finishes copying all pages
6752 ** from source to destination, then it returns [SQLCIPHER_DONE].
6753 ** ^If an error occurs while running sqlcipher3_backup_step(B,N),
6754 ** then an [error code] is returned. ^As well as [SQLCIPHER_OK] and
6755 ** [SQLCIPHER_DONE], a call to sqlcipher3_backup_step() may return [SQLCIPHER_READONLY],
6756 ** [SQLCIPHER_NOMEM], [SQLCIPHER_BUSY], [SQLCIPHER_LOCKED], or an
6757 ** [SQLCIPHER_IOERR_ACCESS | SQLCIPHER_IOERR_XXX] extended error code.
6758 **
6759 ** ^(The sqlcipher3_backup_step() might return [SQLCIPHER_READONLY] if
6760 ** <ol>
6761 ** <li> the destination database was opened read-only, or
6762 ** <li> the destination database is using write-ahead-log journaling
6763 ** and the destination and source page sizes differ, or
6764 ** <li> the destination database is an in-memory database and the
6765 ** destination and source page sizes differ.
6766 ** </ol>)^
6767 **
6768 ** ^If sqlcipher3_backup_step() cannot obtain a required file-system lock, then
6769 ** the [sqlcipher3_busy_handler | busy-handler function]
6770 ** is invoked (if one is specified). ^If the 
6771 ** busy-handler returns non-zero before the lock is available, then 
6772 ** [SQLCIPHER_BUSY] is returned to the caller. ^In this case the call to
6773 ** sqlcipher3_backup_step() can be retried later. ^If the source
6774 ** [database connection]
6775 ** is being used to write to the source database when sqlcipher3_backup_step()
6776 ** is called, then [SQLCIPHER_LOCKED] is returned immediately. ^Again, in this
6777 ** case the call to sqlcipher3_backup_step() can be retried later on. ^(If
6778 ** [SQLCIPHER_IOERR_ACCESS | SQLCIPHER_IOERR_XXX], [SQLCIPHER_NOMEM], or
6779 ** [SQLCIPHER_READONLY] is returned, then 
6780 ** there is no point in retrying the call to sqlcipher3_backup_step(). These 
6781 ** errors are considered fatal.)^  The application must accept 
6782 ** that the backup operation has failed and pass the backup operation handle 
6783 ** to the sqlcipher3_backup_finish() to release associated resources.
6784 **
6785 ** ^The first call to sqlcipher3_backup_step() obtains an exclusive lock
6786 ** on the destination file. ^The exclusive lock is not released until either 
6787 ** sqlcipher3_backup_finish() is called or the backup operation is complete 
6788 ** and sqlcipher3_backup_step() returns [SQLCIPHER_DONE].  ^Every call to
6789 ** sqlcipher3_backup_step() obtains a [shared lock] on the source database that
6790 ** lasts for the duration of the sqlcipher3_backup_step() call.
6791 ** ^Because the source database is not locked between calls to
6792 ** sqlcipher3_backup_step(), the source database may be modified mid-way
6793 ** through the backup process.  ^If the source database is modified by an
6794 ** external process or via a database connection other than the one being
6795 ** used by the backup operation, then the backup will be automatically
6796 ** restarted by the next call to sqlcipher3_backup_step(). ^If the source 
6797 ** database is modified by the using the same database connection as is used
6798 ** by the backup operation, then the backup database is automatically
6799 ** updated at the same time.
6800 **
6801 ** [[sqlcipher3_backup_finish()]] <b>sqlcipher3_backup_finish()</b>
6802 **
6803 ** When sqlcipher3_backup_step() has returned [SQLCIPHER_DONE], or when the 
6804 ** application wishes to abandon the backup operation, the application
6805 ** should destroy the [sqlcipher3_backup] by passing it to sqlcipher3_backup_finish().
6806 ** ^The sqlcipher3_backup_finish() interfaces releases all
6807 ** resources associated with the [sqlcipher3_backup] object. 
6808 ** ^If sqlcipher3_backup_step() has not yet returned [SQLCIPHER_DONE], then any
6809 ** active write-transaction on the destination database is rolled back.
6810 ** The [sqlcipher3_backup] object is invalid
6811 ** and may not be used following a call to sqlcipher3_backup_finish().
6812 **
6813 ** ^The value returned by sqlcipher3_backup_finish is [SQLCIPHER_OK] if no
6814 ** sqlcipher3_backup_step() errors occurred, regardless or whether or not
6815 ** sqlcipher3_backup_step() completed.
6816 ** ^If an out-of-memory condition or IO error occurred during any prior
6817 ** sqlcipher3_backup_step() call on the same [sqlcipher3_backup] object, then
6818 ** sqlcipher3_backup_finish() returns the corresponding [error code].
6819 **
6820 ** ^A return of [SQLCIPHER_BUSY] or [SQLCIPHER_LOCKED] from sqlcipher3_backup_step()
6821 ** is not a permanent error and does not affect the return value of
6822 ** sqlcipher3_backup_finish().
6823 **
6824 ** [[sqlcipher3_backup__remaining()]] [[sqlcipher3_backup_pagecount()]]
6825 ** <b>sqlcipher3_backup_remaining() and sqlcipher3_backup_pagecount()</b>
6826 **
6827 ** ^Each call to sqlcipher3_backup_step() sets two values inside
6828 ** the [sqlcipher3_backup] object: the number of pages still to be backed
6829 ** up and the total number of pages in the source database file.
6830 ** The sqlcipher3_backup_remaining() and sqlcipher3_backup_pagecount() interfaces
6831 ** retrieve these two values, respectively.
6832 **
6833 ** ^The values returned by these functions are only updated by
6834 ** sqlcipher3_backup_step(). ^If the source database is modified during a backup
6835 ** operation, then the values are not updated to account for any extra
6836 ** pages that need to be updated or the size of the source database file
6837 ** changing.
6838 **
6839 ** <b>Concurrent Usage of Database Handles</b>
6840 **
6841 ** ^The source [database connection] may be used by the application for other
6842 ** purposes while a backup operation is underway or being initialized.
6843 ** ^If SQLite is compiled and configured to support threadsafe database
6844 ** connections, then the source database connection may be used concurrently
6845 ** from within other threads.
6846 **
6847 ** However, the application must guarantee that the destination 
6848 ** [database connection] is not passed to any other API (by any thread) after 
6849 ** sqlcipher3_backup_init() is called and before the corresponding call to
6850 ** sqlcipher3_backup_finish().  SQLite does not currently check to see
6851 ** if the application incorrectly accesses the destination [database connection]
6852 ** and so no error code is reported, but the operations may malfunction
6853 ** nevertheless.  Use of the destination database connection while a
6854 ** backup is in progress might also also cause a mutex deadlock.
6855 **
6856 ** If running in [shared cache mode], the application must
6857 ** guarantee that the shared cache used by the destination database
6858 ** is not accessed while the backup is running. In practice this means
6859 ** that the application must guarantee that the disk file being 
6860 ** backed up to is not accessed by any connection within the process,
6861 ** not just the specific connection that was passed to sqlcipher3_backup_init().
6862 **
6863 ** The [sqlcipher3_backup] object itself is partially threadsafe. Multiple 
6864 ** threads may safely make multiple concurrent calls to sqlcipher3_backup_step().
6865 ** However, the sqlcipher3_backup_remaining() and sqlcipher3_backup_pagecount()
6866 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6867 ** same time as another thread is invoking sqlcipher3_backup_step() it is
6868 ** possible that they return invalid values.
6869 */
6870 SQLCIPHER_API sqlcipher3_backup *sqlcipher3_backup_init(
6871   sqlcipher3 *pDest,                        /* Destination database handle */
6872   const char *zDestName,                 /* Destination database name */
6873   sqlcipher3 *pSource,                      /* Source database handle */
6874   const char *zSourceName                /* Source database name */
6875 );
6876 SQLCIPHER_API int sqlcipher3_backup_step(sqlcipher3_backup *p, int nPage);
6877 SQLCIPHER_API int sqlcipher3_backup_finish(sqlcipher3_backup *p);
6878 SQLCIPHER_API int sqlcipher3_backup_remaining(sqlcipher3_backup *p);
6879 SQLCIPHER_API int sqlcipher3_backup_pagecount(sqlcipher3_backup *p);
6880
6881 /*
6882 ** CAPI3REF: Unlock Notification
6883 **
6884 ** ^When running in shared-cache mode, a database operation may fail with
6885 ** an [SQLCIPHER_LOCKED] error if the required locks on the shared-cache or
6886 ** individual tables within the shared-cache cannot be obtained. See
6887 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
6888 ** ^This API may be used to register a callback that SQLite will invoke 
6889 ** when the connection currently holding the required lock relinquishes it.
6890 ** ^This API is only available if the library was compiled with the
6891 ** [SQLCIPHER_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6892 **
6893 ** See Also: [Using the SQLite Unlock Notification Feature].
6894 **
6895 ** ^Shared-cache locks are released when a database connection concludes
6896 ** its current transaction, either by committing it or rolling it back. 
6897 **
6898 ** ^When a connection (known as the blocked connection) fails to obtain a
6899 ** shared-cache lock and SQLCIPHER_LOCKED is returned to the caller, the
6900 ** identity of the database connection (the blocking connection) that
6901 ** has locked the required resource is stored internally. ^After an 
6902 ** application receives an SQLCIPHER_LOCKED error, it may call the
6903 ** sqlcipher3_unlock_notify() method with the blocked connection handle as 
6904 ** the first argument to register for a callback that will be invoked
6905 ** when the blocking connections current transaction is concluded. ^The
6906 ** callback is invoked from within the [sqlcipher3_step] or [sqlcipher3_close]
6907 ** call that concludes the blocking connections transaction.
6908 **
6909 ** ^(If sqlcipher3_unlock_notify() is called in a multi-threaded application,
6910 ** there is a chance that the blocking connection will have already
6911 ** concluded its transaction by the time sqlcipher3_unlock_notify() is invoked.
6912 ** If this happens, then the specified callback is invoked immediately,
6913 ** from within the call to sqlcipher3_unlock_notify().)^
6914 **
6915 ** ^If the blocked connection is attempting to obtain a write-lock on a
6916 ** shared-cache table, and more than one other connection currently holds
6917 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
6918 ** the other connections to use as the blocking connection.
6919 **
6920 ** ^(There may be at most one unlock-notify callback registered by a 
6921 ** blocked connection. If sqlcipher3_unlock_notify() is called when the
6922 ** blocked connection already has a registered unlock-notify callback,
6923 ** then the new callback replaces the old.)^ ^If sqlcipher3_unlock_notify() is
6924 ** called with a NULL pointer as its second argument, then any existing
6925 ** unlock-notify callback is canceled. ^The blocked connections 
6926 ** unlock-notify callback may also be canceled by closing the blocked
6927 ** connection using [sqlcipher3_close()].
6928 **
6929 ** The unlock-notify callback is not reentrant. If an application invokes
6930 ** any sqlcipher3_xxx API functions from within an unlock-notify callback, a
6931 ** crash or deadlock may be the result.
6932 **
6933 ** ^Unless deadlock is detected (see below), sqlcipher3_unlock_notify() always
6934 ** returns SQLCIPHER_OK.
6935 **
6936 ** <b>Callback Invocation Details</b>
6937 **
6938 ** When an unlock-notify callback is registered, the application provides a 
6939 ** single void* pointer that is passed to the callback when it is invoked.
6940 ** However, the signature of the callback function allows SQLite to pass
6941 ** it an array of void* context pointers. The first argument passed to
6942 ** an unlock-notify callback is a pointer to an array of void* pointers,
6943 ** and the second is the number of entries in the array.
6944 **
6945 ** When a blocking connections transaction is concluded, there may be
6946 ** more than one blocked connection that has registered for an unlock-notify
6947 ** callback. ^If two or more such blocked connections have specified the
6948 ** same callback function, then instead of invoking the callback function
6949 ** multiple times, it is invoked once with the set of void* context pointers
6950 ** specified by the blocked connections bundled together into an array.
6951 ** This gives the application an opportunity to prioritize any actions 
6952 ** related to the set of unblocked database connections.
6953 **
6954 ** <b>Deadlock Detection</b>
6955 **
6956 ** Assuming that after registering for an unlock-notify callback a 
6957 ** database waits for the callback to be issued before taking any further
6958 ** action (a reasonable assumption), then using this API may cause the
6959 ** application to deadlock. For example, if connection X is waiting for
6960 ** connection Y's transaction to be concluded, and similarly connection
6961 ** Y is waiting on connection X's transaction, then neither connection
6962 ** will proceed and the system may remain deadlocked indefinitely.
6963 **
6964 ** To avoid this scenario, the sqlcipher3_unlock_notify() performs deadlock
6965 ** detection. ^If a given call to sqlcipher3_unlock_notify() would put the
6966 ** system in a deadlocked state, then SQLCIPHER_LOCKED is returned and no
6967 ** unlock-notify callback is registered. The system is said to be in
6968 ** a deadlocked state if connection A has registered for an unlock-notify
6969 ** callback on the conclusion of connection B's transaction, and connection
6970 ** B has itself registered for an unlock-notify callback when connection
6971 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6972 ** the system is also considered to be deadlocked if connection B has
6973 ** registered for an unlock-notify callback on the conclusion of connection
6974 ** C's transaction, where connection C is waiting on connection A. ^Any
6975 ** number of levels of indirection are allowed.
6976 **
6977 ** <b>The "DROP TABLE" Exception</b>
6978 **
6979 ** When a call to [sqlcipher3_step()] returns SQLCIPHER_LOCKED, it is almost 
6980 ** always appropriate to call sqlcipher3_unlock_notify(). There is however,
6981 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6982 ** SQLite checks if there are any currently executing SELECT statements
6983 ** that belong to the same connection. If there are, SQLCIPHER_LOCKED is
6984 ** returned. In this case there is no "blocking connection", so invoking
6985 ** sqlcipher3_unlock_notify() results in the unlock-notify callback being
6986 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6987 ** or "DROP INDEX" query, an infinite loop might be the result.
6988 **
6989 ** One way around this problem is to check the extended error code returned
6990 ** by an sqlcipher3_step() call. ^(If there is a blocking connection, then the
6991 ** extended error code is set to SQLCIPHER_LOCKED_SHAREDCACHE. Otherwise, in
6992 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
6993 ** SQLCIPHER_LOCKED.)^
6994 */
6995 SQLCIPHER_API int sqlcipher3_unlock_notify(
6996   sqlcipher3 *pBlocked,                          /* Waiting connection */
6997   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6998   void *pNotifyArg                            /* Argument to pass to xNotify */
6999 );
7000
7001
7002 /*
7003 ** CAPI3REF: String Comparison
7004 **
7005 ** ^The [sqlcipher3_strnicmp()] API allows applications and extensions to
7006 ** compare the contents of two buffers containing UTF-8 strings in a
7007 ** case-independent fashion, using the same definition of case independence 
7008 ** that SQLite uses internally when comparing identifiers.
7009 */
7010 SQLCIPHER_API int sqlcipher3_strnicmp(const char *, const char *, int);
7011
7012 /*
7013 ** CAPI3REF: Error Logging Interface
7014 **
7015 ** ^The [sqlcipher3_log()] interface writes a message into the error log
7016 ** established by the [SQLCIPHER_CONFIG_LOG] option to [sqlcipher3_config()].
7017 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7018 ** used with [sqlcipher3_snprintf()] to generate the final output string.
7019 **
7020 ** The sqlcipher3_log() interface is intended for use by extensions such as
7021 ** virtual tables, collating functions, and SQL functions.  While there is
7022 ** nothing to prevent an application from calling sqlcipher3_log(), doing so
7023 ** is considered bad form.
7024 **
7025 ** The zFormat string must not be NULL.
7026 **
7027 ** To avoid deadlocks and other threading problems, the sqlcipher3_log() routine
7028 ** will not use dynamically allocated memory.  The log message is stored in
7029 ** a fixed-length buffer on the stack.  If the log message is longer than
7030 ** a few hundred characters, it will be truncated to the length of the
7031 ** buffer.
7032 */
7033 SQLCIPHER_API void sqlcipher3_log(int iErrCode, const char *zFormat, ...);
7034
7035 /*
7036 ** CAPI3REF: Write-Ahead Log Commit Hook
7037 **
7038 ** ^The [sqlcipher3_wal_hook()] function is used to register a callback that
7039 ** will be invoked each time a database connection commits data to a
7040 ** [write-ahead log] (i.e. whenever a transaction is committed in
7041 ** [journal_mode | journal_mode=WAL mode]). 
7042 **
7043 ** ^The callback is invoked by SQLite after the commit has taken place and 
7044 ** the associated write-lock on the database released, so the implementation 
7045 ** may read, write or [checkpoint] the database as required.
7046 **
7047 ** ^The first parameter passed to the callback function when it is invoked
7048 ** is a copy of the third parameter passed to sqlcipher3_wal_hook() when
7049 ** registering the callback. ^The second is a copy of the database handle.
7050 ** ^The third parameter is the name of the database that was written to -
7051 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7052 ** is the number of pages currently in the write-ahead log file,
7053 ** including those that were just committed.
7054 **
7055 ** The callback function should normally return [SQLCIPHER_OK].  ^If an error
7056 ** code is returned, that error will propagate back up through the
7057 ** SQLite code base to cause the statement that provoked the callback
7058 ** to report an error, though the commit will have still occurred. If the
7059 ** callback returns [SQLCIPHER_ROW] or [SQLCIPHER_DONE], or if it returns a value
7060 ** that does not correspond to any valid SQLite error code, the results
7061 ** are undefined.
7062 **
7063 ** A single database handle may have at most a single write-ahead log callback 
7064 ** registered at one time. ^Calling [sqlcipher3_wal_hook()] replaces any
7065 ** previously registered write-ahead log callback. ^Note that the
7066 ** [sqlcipher3_wal_autocheckpoint()] interface and the
7067 ** [wal_autocheckpoint pragma] both invoke [sqlcipher3_wal_hook()] and will
7068 ** those overwrite any prior [sqlcipher3_wal_hook()] settings.
7069 */
7070 SQLCIPHER_API void *sqlcipher3_wal_hook(
7071   sqlcipher3*, 
7072   int(*)(void *,sqlcipher3*,const char*,int),
7073   void*
7074 );
7075
7076 /*
7077 ** CAPI3REF: Configure an auto-checkpoint
7078 **
7079 ** ^The [sqlcipher3_wal_autocheckpoint(D,N)] is a wrapper around
7080 ** [sqlcipher3_wal_hook()] that causes any database on [database connection] D
7081 ** to automatically [checkpoint]
7082 ** after committing a transaction if there are N or
7083 ** more frames in the [write-ahead log] file.  ^Passing zero or 
7084 ** a negative value as the nFrame parameter disables automatic
7085 ** checkpoints entirely.
7086 **
7087 ** ^The callback registered by this function replaces any existing callback
7088 ** registered using [sqlcipher3_wal_hook()].  ^Likewise, registering a callback
7089 ** using [sqlcipher3_wal_hook()] disables the automatic checkpoint mechanism
7090 ** configured by this function.
7091 **
7092 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7093 ** from SQL.
7094 **
7095 ** ^Every new [database connection] defaults to having the auto-checkpoint
7096 ** enabled with a threshold of 1000 or [SQLCIPHER_DEFAULT_WAL_AUTOCHECKPOINT]
7097 ** pages.  The use of this interface
7098 ** is only necessary if the default setting is found to be suboptimal
7099 ** for a particular application.
7100 */
7101 SQLCIPHER_API int sqlcipher3_wal_autocheckpoint(sqlcipher3 *db, int N);
7102
7103 /*
7104 ** CAPI3REF: Checkpoint a database
7105 **
7106 ** ^The [sqlcipher3_wal_checkpoint(D,X)] interface causes database named X
7107 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7108 ** empty string, then a checkpoint is run on all databases of
7109 ** connection D.  ^If the database connection D is not in
7110 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7111 **
7112 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7113 ** from SQL.  ^The [sqlcipher3_wal_autocheckpoint()] interface and the
7114 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7115 ** run whenever the WAL reaches a certain size threshold.
7116 **
7117 ** See also: [sqlcipher3_wal_checkpoint_v2()]
7118 */
7119 SQLCIPHER_API int sqlcipher3_wal_checkpoint(sqlcipher3 *db, const char *zDb);
7120
7121 /*
7122 ** CAPI3REF: Checkpoint a database
7123 **
7124 ** Run a checkpoint operation on WAL database zDb attached to database 
7125 ** handle db. The specific operation is determined by the value of the 
7126 ** eMode parameter:
7127 **
7128 ** <dl>
7129 ** <dt>SQLCIPHER_CHECKPOINT_PASSIVE<dd>
7130 **   Checkpoint as many frames as possible without waiting for any database 
7131 **   readers or writers to finish. Sync the db file if all frames in the log
7132 **   are checkpointed. This mode is the same as calling 
7133 **   sqlcipher3_wal_checkpoint(). The busy-handler callback is never invoked.
7134 **
7135 ** <dt>SQLCIPHER_CHECKPOINT_FULL<dd>
7136 **   This mode blocks (calls the busy-handler callback) until there is no
7137 **   database writer and all readers are reading from the most recent database
7138 **   snapshot. It then checkpoints all frames in the log file and syncs the
7139 **   database file. This call blocks database writers while it is running,
7140 **   but not database readers.
7141 **
7142 ** <dt>SQLCIPHER_CHECKPOINT_RESTART<dd>
7143 **   This mode works the same way as SQLCIPHER_CHECKPOINT_FULL, except after 
7144 **   checkpointing the log file it blocks (calls the busy-handler callback)
7145 **   until all readers are reading from the database file only. This ensures 
7146 **   that the next client to write to the database file restarts the log file 
7147 **   from the beginning. This call blocks database writers while it is running,
7148 **   but not database readers.
7149 ** </dl>
7150 **
7151 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7152 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7153 ** the total number of checkpointed frames (including any that were already
7154 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7155 ** populated even if sqlcipher3_wal_checkpoint_v2() returns other than SQLCIPHER_OK.
7156 ** If no values are available because of an error, they are both set to -1
7157 ** before returning to communicate this to the caller.
7158 **
7159 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7160 ** any other process is running a checkpoint operation at the same time, the 
7161 ** lock cannot be obtained and SQLCIPHER_BUSY is returned. Even if there is a 
7162 ** busy-handler configured, it will not be invoked in this case.
7163 **
7164 ** The SQLCIPHER_CHECKPOINT_FULL and RESTART modes also obtain the exclusive 
7165 ** "writer" lock on the database file. If the writer lock cannot be obtained
7166 ** immediately, and a busy-handler is configured, it is invoked and the writer
7167 ** lock retried until either the busy-handler returns 0 or the lock is
7168 ** successfully obtained. The busy-handler is also invoked while waiting for
7169 ** database readers as described above. If the busy-handler returns 0 before
7170 ** the writer lock is obtained or while waiting for database readers, the
7171 ** checkpoint operation proceeds from that point in the same way as 
7172 ** SQLCIPHER_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
7173 ** without blocking any further. SQLCIPHER_BUSY is returned in this case.
7174 **
7175 ** If parameter zDb is NULL or points to a zero length string, then the
7176 ** specified operation is attempted on all WAL databases. In this case the
7177 ** values written to output parameters *pnLog and *pnCkpt are undefined. If 
7178 ** an SQLCIPHER_BUSY error is encountered when processing one or more of the 
7179 ** attached WAL databases, the operation is still attempted on any remaining 
7180 ** attached databases and SQLCIPHER_BUSY is returned to the caller. If any other 
7181 ** error occurs while processing an attached database, processing is abandoned 
7182 ** and the error code returned to the caller immediately. If no error 
7183 ** (SQLCIPHER_BUSY or otherwise) is encountered while processing the attached 
7184 ** databases, SQLCIPHER_OK is returned.
7185 **
7186 ** If database zDb is the name of an attached database that is not in WAL
7187 ** mode, SQLCIPHER_OK is returned and both *pnLog and *pnCkpt set to -1. If
7188 ** zDb is not NULL (or a zero length string) and is not the name of any
7189 ** attached database, SQLCIPHER_ERROR is returned to the caller.
7190 */
7191 SQLCIPHER_API int sqlcipher3_wal_checkpoint_v2(
7192   sqlcipher3 *db,                    /* Database handle */
7193   const char *zDb,                /* Name of attached database (or NULL) */
7194   int eMode,                      /* SQLCIPHER_CHECKPOINT_* value */
7195   int *pnLog,                     /* OUT: Size of WAL log in frames */
7196   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7197 );
7198
7199 /*
7200 ** CAPI3REF: Checkpoint operation parameters
7201 **
7202 ** These constants can be used as the 3rd parameter to
7203 ** [sqlcipher3_wal_checkpoint_v2()].  See the [sqlcipher3_wal_checkpoint_v2()]
7204 ** documentation for additional information about the meaning and use of
7205 ** each of these values.
7206 */
7207 #define SQLCIPHER_CHECKPOINT_PASSIVE 0
7208 #define SQLCIPHER_CHECKPOINT_FULL    1
7209 #define SQLCIPHER_CHECKPOINT_RESTART 2
7210
7211 /*
7212 ** CAPI3REF: Virtual Table Interface Configuration
7213 **
7214 ** This function may be called by either the [xConnect] or [xCreate] method
7215 ** of a [virtual table] implementation to configure
7216 ** various facets of the virtual table interface.
7217 **
7218 ** If this interface is invoked outside the context of an xConnect or
7219 ** xCreate virtual table method then the behavior is undefined.
7220 **
7221 ** At present, there is only one option that may be configured using
7222 ** this function. (See [SQLCIPHER_VTAB_CONSTRAINT_SUPPORT].)  Further options
7223 ** may be added in the future.
7224 */
7225 SQLCIPHER_API int sqlcipher3_vtab_config(sqlcipher3*, int op, ...);
7226
7227 /*
7228 ** CAPI3REF: Virtual Table Configuration Options
7229 **
7230 ** These macros define the various options to the
7231 ** [sqlcipher3_vtab_config()] interface that [virtual table] implementations
7232 ** can use to customize and optimize their behavior.
7233 **
7234 ** <dl>
7235 ** <dt>SQLCIPHER_VTAB_CONSTRAINT_SUPPORT
7236 ** <dd>Calls of the form
7237 ** [sqlcipher3_vtab_config](db,SQLCIPHER_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7238 ** where X is an integer.  If X is zero, then the [virtual table] whose
7239 ** [xCreate] or [xConnect] method invoked [sqlcipher3_vtab_config()] does not
7240 ** support constraints.  In this configuration (which is the default) if
7241 ** a call to the [xUpdate] method returns [SQLCIPHER_CONSTRAINT], then the entire
7242 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7243 ** specified as part of the users SQL statement, regardless of the actual
7244 ** ON CONFLICT mode specified.
7245 **
7246 ** If X is non-zero, then the virtual table implementation guarantees
7247 ** that if [xUpdate] returns [SQLCIPHER_CONSTRAINT], it will do so before
7248 ** any modifications to internal or persistent data structures have been made.
7249 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
7250 ** is able to roll back a statement or database transaction, and abandon
7251 ** or continue processing the current SQL statement as appropriate. 
7252 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7253 ** [SQLCIPHER_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7254 ** had been ABORT.
7255 **
7256 ** Virtual table implementations that are required to handle OR REPLACE
7257 ** must do so within the [xUpdate] method. If a call to the 
7258 ** [sqlcipher3_vtab_on_conflict()] function indicates that the current ON 
7259 ** CONFLICT policy is REPLACE, the virtual table implementation should 
7260 ** silently replace the appropriate rows within the xUpdate callback and
7261 ** return SQLCIPHER_OK. Or, if this is not possible, it may return
7262 ** SQLCIPHER_CONSTRAINT, in which case SQLite falls back to OR ABORT 
7263 ** constraint handling.
7264 ** </dl>
7265 */
7266 #define SQLCIPHER_VTAB_CONSTRAINT_SUPPORT 1
7267
7268 /*
7269 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7270 **
7271 ** This function may only be called from within a call to the [xUpdate] method
7272 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7273 ** value returned is one of [SQLCIPHER_ROLLBACK], [SQLCIPHER_IGNORE], [SQLCIPHER_FAIL],
7274 ** [SQLCIPHER_ABORT], or [SQLCIPHER_REPLACE], according to the [ON CONFLICT] mode
7275 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7276 ** [virtual table].
7277 */
7278 SQLCIPHER_API int sqlcipher3_vtab_on_conflict(sqlcipher3 *);
7279
7280 /*
7281 ** CAPI3REF: Conflict resolution modes
7282 **
7283 ** These constants are returned by [sqlcipher3_vtab_on_conflict()] to
7284 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7285 ** is for the SQL statement being evaluated.
7286 **
7287 ** Note that the [SQLCIPHER_IGNORE] constant is also used as a potential
7288 ** return value from the [sqlcipher3_set_authorizer()] callback and that
7289 ** [SQLCIPHER_ABORT] is also a [result code].
7290 */
7291 #define SQLCIPHER_ROLLBACK 1
7292 /* #define SQLCIPHER_IGNORE 2 // Also used by sqlcipher3_authorizer() callback */
7293 #define SQLCIPHER_FAIL     3
7294 /* #define SQLCIPHER_ABORT 4  // Also an error code */
7295 #define SQLCIPHER_REPLACE  5
7296
7297
7298
7299 /*
7300 ** Undo the hack that converts floating point types to integer for
7301 ** builds on processors without floating point support.
7302 */
7303 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
7304 # undef double
7305 #endif
7306
7307 #if 0
7308 }  /* End of the 'extern "C"' block */
7309 #endif
7310 #endif
7311
7312 /*
7313 ** 2010 August 30
7314 **
7315 ** The author disclaims copyright to this source code.  In place of
7316 ** a legal notice, here is a blessing:
7317 **
7318 **    May you do good and not evil.
7319 **    May you find forgiveness for yourself and forgive others.
7320 **    May you share freely, never taking more than you give.
7321 **
7322 *************************************************************************
7323 */
7324
7325 #ifndef _SQLCIPHER3RTREE_H_
7326 #define _SQLCIPHER3RTREE_H_
7327
7328
7329 #if 0
7330 extern "C" {
7331 #endif
7332
7333 typedef struct sqlcipher3_rtree_geometry sqlcipher3_rtree_geometry;
7334
7335 /*
7336 ** Register a geometry callback named zGeom that can be used as part of an
7337 ** R-Tree geometry query as follows:
7338 **
7339 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7340 */
7341 SQLCIPHER_API int sqlcipher3_rtree_geometry_callback(
7342   sqlcipher3 *db,
7343   const char *zGeom,
7344   int (*xGeom)(sqlcipher3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
7345   void *pContext
7346 );
7347
7348
7349 /*
7350 ** A pointer to a structure of the following type is passed as the first
7351 ** argument to callbacks registered using rtree_geometry_callback().
7352 */
7353 struct sqlcipher3_rtree_geometry {
7354   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7355   int nParam;                     /* Size of array aParam[] */
7356   double *aParam;                 /* Parameters passed to SQL geom function */
7357   void *pUser;                    /* Callback implementation user data */
7358   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7359 };
7360
7361
7362 #if 0
7363 }  /* end of the 'extern "C"' block */
7364 #endif
7365
7366 #endif  /* ifndef _SQLCIPHER3RTREE_H_ */
7367
7368
7369 /************** End of sqlcipher3.h *********************************************/
7370 /************** Continuing where we left off in sqlcipherInt.h ******************/
7371 /************** Include hash.h in the middle of sqlcipherInt.h ******************/
7372 /************** Begin file hash.h ********************************************/
7373 /*
7374 ** 2001 September 22
7375 **
7376 ** The author disclaims copyright to this source code.  In place of
7377 ** a legal notice, here is a blessing:
7378 **
7379 **    May you do good and not evil.
7380 **    May you find forgiveness for yourself and forgive others.
7381 **    May you share freely, never taking more than you give.
7382 **
7383 *************************************************************************
7384 ** This is the header file for the generic hash-table implemenation
7385 ** used in SQLite.
7386 */
7387 #ifndef _SQLCIPHER_HASH_H_
7388 #define _SQLCIPHER_HASH_H_
7389
7390 /* Forward declarations of structures. */
7391 typedef struct Hash Hash;
7392 typedef struct HashElem HashElem;
7393
7394 /* A complete hash table is an instance of the following structure.
7395 ** The internals of this structure are intended to be opaque -- client
7396 ** code should not attempt to access or modify the fields of this structure
7397 ** directly.  Change this structure only by using the routines below.
7398 ** However, some of the "procedures" and "functions" for modifying and
7399 ** accessing this structure are really macros, so we can't really make
7400 ** this structure opaque.
7401 **
7402 ** All elements of the hash table are on a single doubly-linked list.
7403 ** Hash.first points to the head of this list.
7404 **
7405 ** There are Hash.htsize buckets.  Each bucket points to a spot in
7406 ** the global doubly-linked list.  The contents of the bucket are the
7407 ** element pointed to plus the next _ht.count-1 elements in the list.
7408 **
7409 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7410 ** by a linear search of the global list.  For small tables, the 
7411 ** Hash.ht table is never allocated because if there are few elements
7412 ** in the table, it is faster to do a linear search than to manage
7413 ** the hash table.
7414 */
7415 struct Hash {
7416   unsigned int htsize;      /* Number of buckets in the hash table */
7417   unsigned int count;       /* Number of entries in this table */
7418   HashElem *first;          /* The first element of the array */
7419   struct _ht {              /* the hash table */
7420     int count;                 /* Number of entries with this hash */
7421     HashElem *chain;           /* Pointer to first entry with this hash */
7422   } *ht;
7423 };
7424
7425 /* Each element in the hash table is an instance of the following 
7426 ** structure.  All elements are stored on a single doubly-linked list.
7427 **
7428 ** Again, this structure is intended to be opaque, but it can't really
7429 ** be opaque because it is used by macros.
7430 */
7431 struct HashElem {
7432   HashElem *next, *prev;       /* Next and previous elements in the table */
7433   void *data;                  /* Data associated with this element */
7434   const char *pKey; int nKey;  /* Key associated with this element */
7435 };
7436
7437 /*
7438 ** Access routines.  To delete, insert a NULL pointer.
7439 */
7440 SQLCIPHER_PRIVATE void sqlcipher3HashInit(Hash*);
7441 SQLCIPHER_PRIVATE void *sqlcipher3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7442 SQLCIPHER_PRIVATE void *sqlcipher3HashFind(const Hash*, const char *pKey, int nKey);
7443 SQLCIPHER_PRIVATE void sqlcipher3HashClear(Hash*);
7444
7445 /*
7446 ** Macros for looping over all elements of a hash table.  The idiom is
7447 ** like this:
7448 **
7449 **   Hash h;
7450 **   HashElem *p;
7451 **   ...
7452 **   for(p=sqlcipherHashFirst(&h); p; p=sqlcipherHashNext(p)){
7453 **     SomeStructure *pData = sqlcipherHashData(p);
7454 **     // do something with pData
7455 **   }
7456 */
7457 #define sqlcipherHashFirst(H)  ((H)->first)
7458 #define sqlcipherHashNext(E)   ((E)->next)
7459 #define sqlcipherHashData(E)   ((E)->data)
7460 /* #define sqlcipherHashKey(E)    ((E)->pKey) // NOT USED */
7461 /* #define sqlcipherHashKeysize(E) ((E)->nKey)  // NOT USED */
7462
7463 /*
7464 ** Number of entries in a hash table
7465 */
7466 /* #define sqlcipherHashCount(H)  ((H)->count) // NOT USED */
7467
7468 #endif /* _SQLCIPHER_HASH_H_ */
7469
7470 /************** End of hash.h ************************************************/
7471 /************** Continuing where we left off in sqlcipherInt.h ******************/
7472 /************** Include parse.h in the middle of sqlcipherInt.h *****************/
7473 /************** Begin file parse.h *******************************************/
7474 #define TK_SEMI                            1
7475 #define TK_EXPLAIN                         2
7476 #define TK_QUERY                           3
7477 #define TK_PLAN                            4
7478 #define TK_BEGIN                           5
7479 #define TK_TRANSACTION                     6
7480 #define TK_DEFERRED                        7
7481 #define TK_IMMEDIATE                       8
7482 #define TK_EXCLUSIVE                       9
7483 #define TK_COMMIT                         10
7484 #define TK_END                            11
7485 #define TK_ROLLBACK                       12
7486 #define TK_SAVEPOINT                      13
7487 #define TK_RELEASE                        14
7488 #define TK_TO                             15
7489 #define TK_TABLE                          16
7490 #define TK_CREATE                         17
7491 #define TK_IF                             18
7492 #define TK_NOT                            19
7493 #define TK_EXISTS                         20
7494 #define TK_TEMP                           21
7495 #define TK_LP                             22
7496 #define TK_RP                             23
7497 #define TK_AS                             24
7498 #define TK_COMMA                          25
7499 #define TK_ID                             26
7500 #define TK_INDEXED                        27
7501 #define TK_ABORT                          28
7502 #define TK_ACTION                         29
7503 #define TK_AFTER                          30
7504 #define TK_ANALYZE                        31
7505 #define TK_ASC                            32
7506 #define TK_ATTACH                         33
7507 #define TK_BEFORE                         34
7508 #define TK_BY                             35
7509 #define TK_CASCADE                        36
7510 #define TK_CAST                           37
7511 #define TK_COLUMNKW                       38
7512 #define TK_CONFLICT                       39
7513 #define TK_DATABASE                       40
7514 #define TK_DESC                           41
7515 #define TK_DETACH                         42
7516 #define TK_EACH                           43
7517 #define TK_FAIL                           44
7518 #define TK_FOR                            45
7519 #define TK_IGNORE                         46
7520 #define TK_INITIALLY                      47
7521 #define TK_INSTEAD                        48
7522 #define TK_LIKE_KW                        49
7523 #define TK_MATCH                          50
7524 #define TK_NO                             51
7525 #define TK_KEY                            52
7526 #define TK_OF                             53
7527 #define TK_OFFSET                         54
7528 #define TK_PRAGMA                         55
7529 #define TK_RAISE                          56
7530 #define TK_REPLACE                        57
7531 #define TK_RESTRICT                       58
7532 #define TK_ROW                            59
7533 #define TK_TRIGGER                        60
7534 #define TK_VACUUM                         61
7535 #define TK_VIEW                           62
7536 #define TK_VIRTUAL                        63
7537 #define TK_REINDEX                        64
7538 #define TK_RENAME                         65
7539 #define TK_CTIME_KW                       66
7540 #define TK_ANY                            67
7541 #define TK_OR                             68
7542 #define TK_AND                            69
7543 #define TK_IS                             70
7544 #define TK_BETWEEN                        71
7545 #define TK_IN                             72
7546 #define TK_ISNULL                         73
7547 #define TK_NOTNULL                        74
7548 #define TK_NE                             75
7549 #define TK_EQ                             76
7550 #define TK_GT                             77
7551 #define TK_LE                             78
7552 #define TK_LT                             79
7553 #define TK_GE                             80
7554 #define TK_ESCAPE                         81
7555 #define TK_BITAND                         82
7556 #define TK_BITOR                          83
7557 #define TK_LSHIFT                         84
7558 #define TK_RSHIFT                         85
7559 #define TK_PLUS                           86
7560 #define TK_MINUS                          87
7561 #define TK_STAR                           88
7562 #define TK_SLASH                          89
7563 #define TK_REM                            90
7564 #define TK_CONCAT                         91
7565 #define TK_COLLATE                        92
7566 #define TK_BITNOT                         93
7567 #define TK_STRING                         94
7568 #define TK_JOIN_KW                        95
7569 #define TK_CONSTRAINT                     96
7570 #define TK_DEFAULT                        97
7571 #define TK_NULL                           98
7572 #define TK_PRIMARY                        99
7573 #define TK_UNIQUE                         100
7574 #define TK_CHECK                          101
7575 #define TK_REFERENCES                     102
7576 #define TK_AUTOINCR                       103
7577 #define TK_ON                             104
7578 #define TK_INSERT                         105
7579 #define TK_DELETE                         106
7580 #define TK_UPDATE                         107
7581 #define TK_SET                            108
7582 #define TK_DEFERRABLE                     109
7583 #define TK_FOREIGN                        110
7584 #define TK_DROP                           111
7585 #define TK_UNION                          112
7586 #define TK_ALL                            113
7587 #define TK_EXCEPT                         114
7588 #define TK_INTERSECT                      115
7589 #define TK_SELECT                         116
7590 #define TK_DISTINCT                       117
7591 #define TK_DOT                            118
7592 #define TK_FROM                           119
7593 #define TK_JOIN                           120
7594 #define TK_USING                          121
7595 #define TK_ORDER                          122
7596 #define TK_GROUP                          123
7597 #define TK_HAVING                         124
7598 #define TK_LIMIT                          125
7599 #define TK_WHERE                          126
7600 #define TK_INTO                           127
7601 #define TK_VALUES                         128
7602 #define TK_INTEGER                        129
7603 #define TK_FLOAT                          130
7604 #define TK_BLOB                           131
7605 #define TK_REGISTER                       132
7606 #define TK_VARIABLE                       133
7607 #define TK_CASE                           134
7608 #define TK_WHEN                           135
7609 #define TK_THEN                           136
7610 #define TK_ELSE                           137
7611 #define TK_INDEX                          138
7612 #define TK_ALTER                          139
7613 #define TK_ADD                            140
7614 #define TK_TO_TEXT                        141
7615 #define TK_TO_BLOB                        142
7616 #define TK_TO_NUMERIC                     143
7617 #define TK_TO_INT                         144
7618 #define TK_TO_REAL                        145
7619 #define TK_ISNOT                          146
7620 #define TK_END_OF_FILE                    147
7621 #define TK_ILLEGAL                        148
7622 #define TK_SPACE                          149
7623 #define TK_UNCLOSED_STRING                150
7624 #define TK_FUNCTION                       151
7625 #define TK_COLUMN                         152
7626 #define TK_AGG_FUNCTION                   153
7627 #define TK_AGG_COLUMN                     154
7628 #define TK_CONST_FUNC                     155
7629 #define TK_UMINUS                         156
7630 #define TK_UPLUS                          157
7631
7632 /************** End of parse.h ***********************************************/
7633 /************** Continuing where we left off in sqlcipherInt.h ******************/
7634 #include <stdio.h>
7635 #include <stdlib.h>
7636 #include <string.h>
7637 #include <assert.h>
7638 #include <stddef.h>
7639
7640 /*
7641 ** If compiling for a processor that lacks floating point support,
7642 ** substitute integer for floating-point
7643 */
7644 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
7645 # define double sqlcipher_int64
7646 # define float sqlcipher_int64
7647 # define LONGDOUBLE_TYPE sqlcipher_int64
7648 # ifndef SQLCIPHER_BIG_DBL
7649 #   define SQLCIPHER_BIG_DBL (((sqlcipher3_int64)1)<<50)
7650 # endif
7651 # define SQLCIPHER_OMIT_DATETIME_FUNCS 1
7652 # define SQLCIPHER_OMIT_TRACE 1
7653 # undef SQLCIPHER_MIXED_ENDIAN_64BIT_FLOAT
7654 # undef SQLCIPHER_HAVE_ISNAN
7655 #endif
7656 #ifndef SQLCIPHER_BIG_DBL
7657 # define SQLCIPHER_BIG_DBL (1e99)
7658 #endif
7659
7660 /*
7661 ** OMIT_TEMPDB is set to 1 if SQLCIPHER_OMIT_TEMPDB is defined, or 0
7662 ** afterward. Having this macro allows us to cause the C compiler 
7663 ** to omit code used by TEMP tables without messy #ifndef statements.
7664 */
7665 #ifdef SQLCIPHER_OMIT_TEMPDB
7666 #define OMIT_TEMPDB 1
7667 #else
7668 #define OMIT_TEMPDB 0
7669 #endif
7670
7671 /*
7672 ** The "file format" number is an integer that is incremented whenever
7673 ** the VDBE-level file format changes.  The following macros define the
7674 ** the default file format for new databases and the maximum file format
7675 ** that the library can read.
7676 */
7677 #define SQLCIPHER_MAX_FILE_FORMAT 4
7678 #ifndef SQLCIPHER_DEFAULT_FILE_FORMAT
7679 # define SQLCIPHER_DEFAULT_FILE_FORMAT 1
7680 #endif
7681
7682 /*
7683 ** Determine whether triggers are recursive by default.  This can be
7684 ** changed at run-time using a pragma.
7685 */
7686 #ifndef SQLCIPHER_DEFAULT_RECURSIVE_TRIGGERS
7687 # define SQLCIPHER_DEFAULT_RECURSIVE_TRIGGERS 0
7688 #endif
7689
7690 /*
7691 ** Provide a default value for SQLCIPHER_TEMP_STORE in case it is not specified
7692 ** on the command-line
7693 */
7694 #ifndef SQLCIPHER_TEMP_STORE
7695 # define SQLCIPHER_TEMP_STORE 1
7696 #endif
7697
7698 /*
7699 ** GCC does not define the offsetof() macro so we'll have to do it
7700 ** ourselves.
7701 */
7702 #ifndef offsetof
7703 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7704 #endif
7705
7706 /*
7707 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7708 ** not, there are still machines out there that use EBCDIC.)
7709 */
7710 #if 'A' == '\301'
7711 # define SQLCIPHER_EBCDIC 1
7712 #else
7713 # define SQLCIPHER_ASCII 1
7714 #endif
7715
7716 /*
7717 ** Integers of known sizes.  These typedefs might change for architectures
7718 ** where the sizes very.  Preprocessor macros are available so that the
7719 ** types can be conveniently redefined at compile-type.  Like this:
7720 **
7721 **         cc '-DUINTPTR_TYPE=long long int' ...
7722 */
7723 #ifndef UINT32_TYPE
7724 # ifdef HAVE_UINT32_T
7725 #  define UINT32_TYPE uint32_t
7726 # else
7727 #  define UINT32_TYPE unsigned int
7728 # endif
7729 #endif
7730 #ifndef UINT16_TYPE
7731 # ifdef HAVE_UINT16_T
7732 #  define UINT16_TYPE uint16_t
7733 # else
7734 #  define UINT16_TYPE unsigned short int
7735 # endif
7736 #endif
7737 #ifndef INT16_TYPE
7738 # ifdef HAVE_INT16_T
7739 #  define INT16_TYPE int16_t
7740 # else
7741 #  define INT16_TYPE short int
7742 # endif
7743 #endif
7744 #ifndef UINT8_TYPE
7745 # ifdef HAVE_UINT8_T
7746 #  define UINT8_TYPE uint8_t
7747 # else
7748 #  define UINT8_TYPE unsigned char
7749 # endif
7750 #endif
7751 #ifndef INT8_TYPE
7752 # ifdef HAVE_INT8_T
7753 #  define INT8_TYPE int8_t
7754 # else
7755 #  define INT8_TYPE signed char
7756 # endif
7757 #endif
7758 #ifndef LONGDOUBLE_TYPE
7759 # define LONGDOUBLE_TYPE long double
7760 #endif
7761 typedef sqlcipher_int64 i64;          /* 8-byte signed integer */
7762 typedef sqlcipher_uint64 u64;         /* 8-byte unsigned integer */
7763 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7764 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7765 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7766 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7767 typedef INT8_TYPE i8;              /* 1-byte signed integer */
7768
7769 /*
7770 ** SQLCIPHER_MAX_U32 is a u64 constant that is the maximum u64 value
7771 ** that can be stored in a u32 without loss of data.  The value
7772 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
7773 ** have to specify the value in the less intuitive manner shown:
7774 */
7775 #define SQLCIPHER_MAX_U32  ((((u64)1)<<32)-1)
7776
7777 /*
7778 ** The datatype used to store estimates of the number of rows in a
7779 ** table or index.  This is an unsigned integer type.  For 99.9% of
7780 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
7781 ** can be used at compile-time if desired.
7782 */
7783 #ifdef SQLCIPHER_64BIT_STATS
7784  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
7785 #else
7786  typedef u32 tRowcnt;    /* 32-bit is the default */
7787 #endif
7788
7789 /*
7790 ** Macros to determine whether the machine is big or little endian,
7791 ** evaluated at runtime.
7792 */
7793 #ifdef SQLCIPHER_AMALGAMATION
7794 SQLCIPHER_PRIVATE const int sqlcipher3one = 1;
7795 #else
7796 SQLCIPHER_PRIVATE const int sqlcipher3one;
7797 #endif
7798 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7799                              || defined(__x86_64) || defined(__x86_64__)
7800 # define SQLCIPHER_BIGENDIAN    0
7801 # define SQLCIPHER_LITTLEENDIAN 1
7802 # define SQLCIPHER_UTF16NATIVE  SQLCIPHER_UTF16LE
7803 #else
7804 # define SQLCIPHER_BIGENDIAN    (*(char *)(&sqlcipher3one)==0)
7805 # define SQLCIPHER_LITTLEENDIAN (*(char *)(&sqlcipher3one)==1)
7806 # define SQLCIPHER_UTF16NATIVE (SQLCIPHER_BIGENDIAN?SQLCIPHER_UTF16BE:SQLCIPHER_UTF16LE)
7807 #endif
7808
7809 /*
7810 ** Constants for the largest and smallest possible 64-bit signed integers.
7811 ** These macros are designed to work correctly on both 32-bit and 64-bit
7812 ** compilers.
7813 */
7814 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7815 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7816
7817 /* 
7818 ** Round up a number to the next larger multiple of 8.  This is used
7819 ** to force 8-byte alignment on 64-bit architectures.
7820 */
7821 #define ROUND8(x)     (((x)+7)&~7)
7822
7823 /*
7824 ** Round down to the nearest multiple of 8
7825 */
7826 #define ROUNDDOWN8(x) ((x)&~7)
7827
7828 /*
7829 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
7830 ** macro is used only within assert() to verify that the code gets
7831 ** all alignment restrictions correct.
7832 **
7833 ** Except, if SQLCIPHER_4_BYTE_ALIGNED_MALLOC is defined, then the
7834 ** underlying malloc() implemention might return us 4-byte aligned
7835 ** pointers.  In that case, only verify 4-byte alignment.
7836 */
7837 #ifdef SQLCIPHER_4_BYTE_ALIGNED_MALLOC
7838 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
7839 #else
7840 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
7841 #endif
7842
7843
7844 /*
7845 ** An instance of the following structure is used to store the busy-handler
7846 ** callback for a given sqlcipher handle. 
7847 **
7848 ** The sqlcipher.busyHandler member of the sqlcipher struct contains the busy
7849 ** callback for the database handle. Each pager opened via the sqlcipher
7850 ** handle is passed a pointer to sqlcipher.busyHandler. The busy-handler
7851 ** callback is currently invoked only from within pager.c.
7852 */
7853 typedef struct BusyHandler BusyHandler;
7854 struct BusyHandler {
7855   int (*xFunc)(void *,int);  /* The busy callback */
7856   void *pArg;                /* First arg to busy callback */
7857   int nBusy;                 /* Incremented with each busy call */
7858 };
7859
7860 /*
7861 ** Name of the master database table.  The master database table
7862 ** is a special table that holds the names and attributes of all
7863 ** user tables and indices.
7864 */
7865 #define MASTER_NAME       "sqlcipher_master"
7866 #define TEMP_MASTER_NAME  "sqlcipher_temp_master"
7867
7868 /*
7869 ** The root-page of the master database table.
7870 */
7871 #define MASTER_ROOT       1
7872
7873 /*
7874 ** The name of the schema table.
7875 */
7876 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7877
7878 /*
7879 ** A convenience macro that returns the number of elements in
7880 ** an array.
7881 */
7882 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
7883
7884 /*
7885 ** The following value as a destructor means to use sqlcipher3DbFree().
7886 ** This is an internal extension to SQLCIPHER_STATIC and SQLCIPHER_TRANSIENT.
7887 */
7888 #define SQLCIPHER_DYNAMIC   ((sqlcipher3_destructor_type)sqlcipher3DbFree)
7889
7890 /*
7891 ** When SQLCIPHER_OMIT_WSD is defined, it means that the target platform does
7892 ** not support Writable Static Data (WSD) such as global and static variables.
7893 ** All variables must either be on the stack or dynamically allocated from
7894 ** the heap.  When WSD is unsupported, the variable declarations scattered
7895 ** throughout the SQLite code must become constants instead.  The SQLCIPHER_WSD
7896 ** macro is used for this purpose.  And instead of referencing the variable
7897 ** directly, we use its constant as a key to lookup the run-time allocated
7898 ** buffer that holds real variable.  The constant is also the initializer
7899 ** for the run-time allocated buffer.
7900 **
7901 ** In the usual case where WSD is supported, the SQLCIPHER_WSD and GLOBAL
7902 ** macros become no-ops and have zero performance impact.
7903 */
7904 #ifdef SQLCIPHER_OMIT_WSD
7905   #define SQLCIPHER_WSD const
7906   #define GLOBAL(t,v) (*(t*)sqlcipher3_wsd_find((void*)&(v), sizeof(v)))
7907   #define sqlcipher3GlobalConfig GLOBAL(struct Sqlite3Config, sqlcipher3Config)
7908 SQLCIPHER_API   int sqlcipher3_wsd_init(int N, int J);
7909 SQLCIPHER_API   void *sqlcipher3_wsd_find(void *K, int L);
7910 #else
7911   #define SQLCIPHER_WSD 
7912   #define GLOBAL(t,v) v
7913   #define sqlcipher3GlobalConfig sqlcipher3Config
7914 #endif
7915
7916 /*
7917 ** The following macros are used to suppress compiler warnings and to
7918 ** make it clear to human readers when a function parameter is deliberately 
7919 ** left unused within the body of a function. This usually happens when
7920 ** a function is called via a function pointer. For example the 
7921 ** implementation of an SQL aggregate step callback may not use the
7922 ** parameter indicating the number of arguments passed to the aggregate,
7923 ** if it knows that this is enforced elsewhere.
7924 **
7925 ** When a function parameter is not used at all within the body of a function,
7926 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7927 ** However, these macros may also be used to suppress warnings related to
7928 ** parameters that may or may not be used depending on compilation options.
7929 ** For example those parameters only used in assert() statements. In these
7930 ** cases the parameters are named as per the usual conventions.
7931 */
7932 #define UNUSED_PARAMETER(x) (void)(x)
7933 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7934
7935 /*
7936 ** Forward references to structures
7937 */
7938 typedef struct AggInfo AggInfo;
7939 typedef struct AuthContext AuthContext;
7940 typedef struct AutoincInfo AutoincInfo;
7941 typedef struct Bitvec Bitvec;
7942 typedef struct CollSeq CollSeq;
7943 typedef struct Column Column;
7944 typedef struct Db Db;
7945 typedef struct Schema Schema;
7946 typedef struct Expr Expr;
7947 typedef struct ExprList ExprList;
7948 typedef struct ExprSpan ExprSpan;
7949 typedef struct FKey FKey;
7950 typedef struct FuncDestructor FuncDestructor;
7951 typedef struct FuncDef FuncDef;
7952 typedef struct FuncDefHash FuncDefHash;
7953 typedef struct IdList IdList;
7954 typedef struct Index Index;
7955 typedef struct IndexSample IndexSample;
7956 typedef struct KeyClass KeyClass;
7957 typedef struct KeyInfo KeyInfo;
7958 typedef struct Lookaside Lookaside;
7959 typedef struct LookasideSlot LookasideSlot;
7960 typedef struct Module Module;
7961 typedef struct NameContext NameContext;
7962 typedef struct Parse Parse;
7963 typedef struct RowSet RowSet;
7964 typedef struct Savepoint Savepoint;
7965 typedef struct Select Select;
7966 typedef struct SrcList SrcList;
7967 typedef struct StrAccum StrAccum;
7968 typedef struct Table Table;
7969 typedef struct TableLock TableLock;
7970 typedef struct Token Token;
7971 typedef struct Trigger Trigger;
7972 typedef struct TriggerPrg TriggerPrg;
7973 typedef struct TriggerStep TriggerStep;
7974 typedef struct UnpackedRecord UnpackedRecord;
7975 typedef struct VTable VTable;
7976 typedef struct VtabCtx VtabCtx;
7977 typedef struct Walker Walker;
7978 typedef struct WherePlan WherePlan;
7979 typedef struct WhereInfo WhereInfo;
7980 typedef struct WhereLevel WhereLevel;
7981
7982 /*
7983 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7984 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7985 ** pointer types (i.e. FuncDef) defined above.
7986 */
7987 /************** Include btree.h in the middle of sqlcipherInt.h *****************/
7988 /************** Begin file btree.h *******************************************/
7989 /*
7990 ** 2001 September 15
7991 **
7992 ** The author disclaims copyright to this source code.  In place of
7993 ** a legal notice, here is a blessing:
7994 **
7995 **    May you do good and not evil.
7996 **    May you find forgiveness for yourself and forgive others.
7997 **    May you share freely, never taking more than you give.
7998 **
7999 *************************************************************************
8000 ** This header file defines the interface that the sqlcipher B-Tree file
8001 ** subsystem.  See comments in the source code for a detailed description
8002 ** of what each interface routine does.
8003 */
8004 #ifndef _BTREE_H_
8005 #define _BTREE_H_
8006
8007 /* TODO: This definition is just included so other modules compile. It
8008 ** needs to be revisited.
8009 */
8010 #define SQLCIPHER_N_BTREE_META 10
8011
8012 /*
8013 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8014 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8015 */
8016 #ifndef SQLCIPHER_DEFAULT_AUTOVACUUM
8017   #define SQLCIPHER_DEFAULT_AUTOVACUUM 0
8018 #endif
8019
8020 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8021 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8022 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8023
8024 /*
8025 ** Forward declarations of structure
8026 */
8027 typedef struct Btree Btree;
8028 typedef struct BtCursor BtCursor;
8029 typedef struct BtShared BtShared;
8030
8031
8032 SQLCIPHER_PRIVATE int sqlcipher3BtreeOpen(
8033   sqlcipher3_vfs *pVfs,       /* VFS to use with this b-tree */
8034   const char *zFilename,   /* Name of database file to open */
8035   sqlcipher3 *db,             /* Associated database connection */
8036   Btree **ppBtree,         /* Return open Btree* here */
8037   int flags,               /* Flags */
8038   int vfsFlags             /* Flags passed through to VFS open */
8039 );
8040
8041 /* The flags parameter to sqlcipher3BtreeOpen can be the bitwise or of the
8042 ** following values.
8043 **
8044 ** NOTE:  These values must match the corresponding PAGER_ values in
8045 ** pager.h.
8046 */
8047 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
8048 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
8049 #define BTREE_MEMORY        4  /* This is an in-memory DB */
8050 #define BTREE_SINGLE        8  /* The file contains at most 1 b-tree */
8051 #define BTREE_UNORDERED    16  /* Use of a hash implementation is OK */
8052
8053 SQLCIPHER_PRIVATE int sqlcipher3BtreeClose(Btree*);
8054 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetCacheSize(Btree*,int);
8055 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetSafetyLevel(Btree*,int,int,int);
8056 SQLCIPHER_PRIVATE int sqlcipher3BtreeSyncDisabled(Btree*);
8057 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8058 SQLCIPHER_PRIVATE int sqlcipher3BtreeGetPageSize(Btree*);
8059 SQLCIPHER_PRIVATE int sqlcipher3BtreeMaxPageCount(Btree*,int);
8060 SQLCIPHER_PRIVATE u32 sqlcipher3BtreeLastPage(Btree*);
8061 SQLCIPHER_PRIVATE int sqlcipher3BtreeSecureDelete(Btree*,int);
8062 SQLCIPHER_PRIVATE int sqlcipher3BtreeGetReserve(Btree*);
8063 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetAutoVacuum(Btree *, int);
8064 SQLCIPHER_PRIVATE int sqlcipher3BtreeGetAutoVacuum(Btree *);
8065 SQLCIPHER_PRIVATE int sqlcipher3BtreeBeginTrans(Btree*,int);
8066 SQLCIPHER_PRIVATE int sqlcipher3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8067 SQLCIPHER_PRIVATE int sqlcipher3BtreeCommitPhaseTwo(Btree*, int);
8068 SQLCIPHER_PRIVATE int sqlcipher3BtreeCommit(Btree*);
8069 SQLCIPHER_PRIVATE int sqlcipher3BtreeRollback(Btree*);
8070 SQLCIPHER_PRIVATE int sqlcipher3BtreeBeginStmt(Btree*,int);
8071 SQLCIPHER_PRIVATE int sqlcipher3BtreeCreateTable(Btree*, int*, int flags);
8072 SQLCIPHER_PRIVATE int sqlcipher3BtreeIsInTrans(Btree*);
8073 SQLCIPHER_PRIVATE int sqlcipher3BtreeIsInReadTrans(Btree*);
8074 SQLCIPHER_PRIVATE int sqlcipher3BtreeIsInBackup(Btree*);
8075 SQLCIPHER_PRIVATE void *sqlcipher3BtreeSchema(Btree *, int, void(*)(void *));
8076 SQLCIPHER_PRIVATE int sqlcipher3BtreeSchemaLocked(Btree *pBtree);
8077 SQLCIPHER_PRIVATE int sqlcipher3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8078 SQLCIPHER_PRIVATE int sqlcipher3BtreeSavepoint(Btree *, int, int);
8079
8080 SQLCIPHER_PRIVATE const char *sqlcipher3BtreeGetFilename(Btree *);
8081 SQLCIPHER_PRIVATE const char *sqlcipher3BtreeGetJournalname(Btree *);
8082 SQLCIPHER_PRIVATE int sqlcipher3BtreeCopyFile(Btree *, Btree *);
8083
8084 SQLCIPHER_PRIVATE int sqlcipher3BtreeIncrVacuum(Btree *);
8085
8086 /* The flags parameter to sqlcipher3BtreeCreateTable can be the bitwise OR
8087 ** of the flags shown below.
8088 **
8089 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8090 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8091 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
8092 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8093 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
8094 ** indices.)
8095 */
8096 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8097 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
8098
8099 SQLCIPHER_PRIVATE int sqlcipher3BtreeDropTable(Btree*, int, int*);
8100 SQLCIPHER_PRIVATE int sqlcipher3BtreeClearTable(Btree*, int, int*);
8101 SQLCIPHER_PRIVATE void sqlcipher3BtreeTripAllCursors(Btree*, int);
8102
8103 SQLCIPHER_PRIVATE void sqlcipher3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8104 SQLCIPHER_PRIVATE int sqlcipher3BtreeUpdateMeta(Btree*, int idx, u32 value);
8105
8106 /*
8107 ** The second parameter to sqlcipher3BtreeGetMeta or sqlcipher3BtreeUpdateMeta
8108 ** should be one of the following values. The integer values are assigned 
8109 ** to constants so that the offset of the corresponding field in an
8110 ** SQLite database header may be found using the following formula:
8111 **
8112 **   offset = 36 + (idx * 4)
8113 **
8114 ** For example, the free-page-count field is located at byte offset 36 of
8115 ** the database file header. The incr-vacuum-flag field is located at
8116 ** byte offset 64 (== 36+4*7).
8117 */
8118 #define BTREE_FREE_PAGE_COUNT     0
8119 #define BTREE_SCHEMA_VERSION      1
8120 #define BTREE_FILE_FORMAT         2
8121 #define BTREE_DEFAULT_CACHE_SIZE  3
8122 #define BTREE_LARGEST_ROOT_PAGE   4
8123 #define BTREE_TEXT_ENCODING       5
8124 #define BTREE_USER_VERSION        6
8125 #define BTREE_INCR_VACUUM         7
8126
8127 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursor(
8128   Btree*,                              /* BTree containing table to open */
8129   int iTable,                          /* Index of root page */
8130   int wrFlag,                          /* 1 for writing.  0 for read-only */
8131   struct KeyInfo*,                     /* First argument to compare function */
8132   BtCursor *pCursor                    /* Space to write cursor structure */
8133 );
8134 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorSize(void);
8135 SQLCIPHER_PRIVATE void sqlcipher3BtreeCursorZero(BtCursor*);
8136
8137 SQLCIPHER_PRIVATE int sqlcipher3BtreeCloseCursor(BtCursor*);
8138 SQLCIPHER_PRIVATE int sqlcipher3BtreeMovetoUnpacked(
8139   BtCursor*,
8140   UnpackedRecord *pUnKey,
8141   i64 intKey,
8142   int bias,
8143   int *pRes
8144 );
8145 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorHasMoved(BtCursor*, int*);
8146 SQLCIPHER_PRIVATE int sqlcipher3BtreeDelete(BtCursor*);
8147 SQLCIPHER_PRIVATE int sqlcipher3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8148                                   const void *pData, int nData,
8149                                   int nZero, int bias, int seekResult);
8150 SQLCIPHER_PRIVATE int sqlcipher3BtreeFirst(BtCursor*, int *pRes);
8151 SQLCIPHER_PRIVATE int sqlcipher3BtreeLast(BtCursor*, int *pRes);
8152 SQLCIPHER_PRIVATE int sqlcipher3BtreeNext(BtCursor*, int *pRes);
8153 SQLCIPHER_PRIVATE int sqlcipher3BtreeEof(BtCursor*);
8154 SQLCIPHER_PRIVATE int sqlcipher3BtreePrevious(BtCursor*, int *pRes);
8155 SQLCIPHER_PRIVATE int sqlcipher3BtreeKeySize(BtCursor*, i64 *pSize);
8156 SQLCIPHER_PRIVATE int sqlcipher3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8157 SQLCIPHER_PRIVATE const void *sqlcipher3BtreeKeyFetch(BtCursor*, int *pAmt);
8158 SQLCIPHER_PRIVATE const void *sqlcipher3BtreeDataFetch(BtCursor*, int *pAmt);
8159 SQLCIPHER_PRIVATE int sqlcipher3BtreeDataSize(BtCursor*, u32 *pSize);
8160 SQLCIPHER_PRIVATE int sqlcipher3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8161 SQLCIPHER_PRIVATE void sqlcipher3BtreeSetCachedRowid(BtCursor*, sqlcipher3_int64);
8162 SQLCIPHER_PRIVATE sqlcipher3_int64 sqlcipher3BtreeGetCachedRowid(BtCursor*);
8163
8164 SQLCIPHER_PRIVATE char *sqlcipher3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8165 SQLCIPHER_PRIVATE struct Pager *sqlcipher3BtreePager(Btree*);
8166
8167 SQLCIPHER_PRIVATE int sqlcipher3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8168 SQLCIPHER_PRIVATE void sqlcipher3BtreeCacheOverflow(BtCursor *);
8169 SQLCIPHER_PRIVATE void sqlcipher3BtreeClearCursor(BtCursor *);
8170
8171 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetVersion(Btree *pBt, int iVersion);
8172
8173 #ifndef NDEBUG
8174 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorIsValid(BtCursor*);
8175 #endif
8176
8177 #ifndef SQLCIPHER_OMIT_BTREECOUNT
8178 SQLCIPHER_PRIVATE int sqlcipher3BtreeCount(BtCursor *, i64 *);
8179 #endif
8180
8181 #ifdef SQLCIPHER_TEST
8182 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorInfo(BtCursor*, int*, int);
8183 SQLCIPHER_PRIVATE void sqlcipher3BtreeCursorList(Btree*);
8184 #endif
8185
8186 #ifndef SQLCIPHER_OMIT_WAL
8187 SQLCIPHER_PRIVATE   int sqlcipher3BtreeCheckpoint(Btree*, int, int *, int *);
8188 #endif
8189
8190 /*
8191 ** If we are not using shared cache, then there is no need to
8192 ** use mutexes to access the BtShared structures.  So make the
8193 ** Enter and Leave procedures no-ops.
8194 */
8195 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
8196 SQLCIPHER_PRIVATE   void sqlcipher3BtreeEnter(Btree*);
8197 SQLCIPHER_PRIVATE   void sqlcipher3BtreeEnterAll(sqlcipher3*);
8198 #else
8199 # define sqlcipher3BtreeEnter(X) 
8200 # define sqlcipher3BtreeEnterAll(X)
8201 #endif
8202
8203 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && SQLCIPHER_THREADSAFE
8204 SQLCIPHER_PRIVATE   int sqlcipher3BtreeSharable(Btree*);
8205 SQLCIPHER_PRIVATE   void sqlcipher3BtreeLeave(Btree*);
8206 SQLCIPHER_PRIVATE   void sqlcipher3BtreeEnterCursor(BtCursor*);
8207 SQLCIPHER_PRIVATE   void sqlcipher3BtreeLeaveCursor(BtCursor*);
8208 SQLCIPHER_PRIVATE   void sqlcipher3BtreeLeaveAll(sqlcipher3*);
8209 #ifndef NDEBUG
8210   /* These routines are used inside assert() statements only. */
8211 SQLCIPHER_PRIVATE   int sqlcipher3BtreeHoldsMutex(Btree*);
8212 SQLCIPHER_PRIVATE   int sqlcipher3BtreeHoldsAllMutexes(sqlcipher3*);
8213 SQLCIPHER_PRIVATE   int sqlcipher3SchemaMutexHeld(sqlcipher3*,int,Schema*);
8214 #endif
8215 #else
8216
8217 # define sqlcipher3BtreeSharable(X) 0
8218 # define sqlcipher3BtreeLeave(X)
8219 # define sqlcipher3BtreeEnterCursor(X)
8220 # define sqlcipher3BtreeLeaveCursor(X)
8221 # define sqlcipher3BtreeLeaveAll(X)
8222
8223 # define sqlcipher3BtreeHoldsMutex(X) 1
8224 # define sqlcipher3BtreeHoldsAllMutexes(X) 1
8225 # define sqlcipher3SchemaMutexHeld(X,Y,Z) 1
8226 #endif
8227
8228
8229 #endif /* _BTREE_H_ */
8230
8231 /************** End of btree.h ***********************************************/
8232 /************** Continuing where we left off in sqlcipherInt.h ******************/
8233 /************** Include vdbe.h in the middle of sqlcipherInt.h ******************/
8234 /************** Begin file vdbe.h ********************************************/
8235 /*
8236 ** 2001 September 15
8237 **
8238 ** The author disclaims copyright to this source code.  In place of
8239 ** a legal notice, here is a blessing:
8240 **
8241 **    May you do good and not evil.
8242 **    May you find forgiveness for yourself and forgive others.
8243 **    May you share freely, never taking more than you give.
8244 **
8245 *************************************************************************
8246 ** Header file for the Virtual DataBase Engine (VDBE)
8247 **
8248 ** This header defines the interface to the virtual database engine
8249 ** or VDBE.  The VDBE implements an abstract machine that runs a
8250 ** simple program to access and modify the underlying database.
8251 */
8252 #ifndef _SQLCIPHER_VDBE_H_
8253 #define _SQLCIPHER_VDBE_H_
8254 /* #include <stdio.h> */
8255
8256 /*
8257 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
8258 ** in the source file sqlcipherVdbe.c are allowed to see the insides
8259 ** of this structure.
8260 */
8261 typedef struct Vdbe Vdbe;
8262
8263 /*
8264 ** The names of the following types declared in vdbeInt.h are required
8265 ** for the VdbeOp definition.
8266 */
8267 typedef struct VdbeFunc VdbeFunc;
8268 typedef struct Mem Mem;
8269 typedef struct SubProgram SubProgram;
8270
8271 /*
8272 ** A single instruction of the virtual machine has an opcode
8273 ** and as many as three operands.  The instruction is recorded
8274 ** as an instance of the following structure:
8275 */
8276 struct VdbeOp {
8277   u8 opcode;          /* What operation to perform */
8278   signed char p4type; /* One of the P4_xxx constants for p4 */
8279   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
8280   u8 p5;              /* Fifth parameter is an unsigned character */
8281   int p1;             /* First operand */
8282   int p2;             /* Second parameter (often the jump destination) */
8283   int p3;             /* The third parameter */
8284   union {             /* fourth parameter */
8285     int i;                 /* Integer value if p4type==P4_INT32 */
8286     void *p;               /* Generic pointer */
8287     char *z;               /* Pointer to data for string (char array) types */
8288     i64 *pI64;             /* Used when p4type is P4_INT64 */
8289     double *pReal;         /* Used when p4type is P4_REAL */
8290     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8291     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8292     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8293     Mem *pMem;             /* Used when p4type is P4_MEM */
8294     VTable *pVtab;         /* Used when p4type is P4_VTAB */
8295     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8296     int *ai;               /* Used when p4type is P4_INTARRAY */
8297     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
8298     int (*xAdvance)(BtCursor *, int *);
8299   } p4;
8300 #ifdef SQLCIPHER_DEBUG
8301   char *zComment;          /* Comment to improve readability */
8302 #endif
8303 #ifdef VDBE_PROFILE
8304   int cnt;                 /* Number of times this instruction was executed */
8305   u64 cycles;              /* Total time spent executing this instruction */
8306 #endif
8307 };
8308 typedef struct VdbeOp VdbeOp;
8309
8310
8311 /*
8312 ** A sub-routine used to implement a trigger program.
8313 */
8314 struct SubProgram {
8315   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
8316   int nOp;                      /* Elements in aOp[] */
8317   int nMem;                     /* Number of memory cells required */
8318   int nCsr;                     /* Number of cursors required */
8319   void *token;                  /* id that may be used to recursive triggers */
8320   SubProgram *pNext;            /* Next sub-program already visited */
8321 };
8322
8323 /*
8324 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8325 ** it takes up less space.
8326 */
8327 struct VdbeOpList {
8328   u8 opcode;          /* What operation to perform */
8329   signed char p1;     /* First operand */
8330   signed char p2;     /* Second parameter (often the jump destination) */
8331   signed char p3;     /* Third parameter */
8332 };
8333 typedef struct VdbeOpList VdbeOpList;
8334
8335 /*
8336 ** Allowed values of VdbeOp.p4type
8337 */
8338 #define P4_NOTUSED    0   /* The P4 parameter is not used */
8339 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqlcipherMalloc() */
8340 #define P4_STATIC   (-2)  /* Pointer to a static string */
8341 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8342 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8343 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8344 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8345 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8346 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
8347 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlcipher3_vtab structure */
8348 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlcipher3_mprintf() */
8349 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8350 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8351 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8352 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8353 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
8354 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8355
8356 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8357 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
8358 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8359 ** gets freed when the Vdbe is finalized so it still should be obtained
8360 ** from a single sqlcipherMalloc().  But no copy is made and the calling
8361 ** function should *not* try to free the KeyInfo.
8362 */
8363 #define P4_KEYINFO_HANDOFF (-16)
8364 #define P4_KEYINFO_STATIC  (-17)
8365
8366 /*
8367 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
8368 ** number of columns of data returned by the statement.
8369 */
8370 #define COLNAME_NAME     0
8371 #define COLNAME_DECLTYPE 1
8372 #define COLNAME_DATABASE 2
8373 #define COLNAME_TABLE    3
8374 #define COLNAME_COLUMN   4
8375 #ifdef SQLCIPHER_ENABLE_COLUMN_METADATA
8376 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8377 #else
8378 # ifdef SQLCIPHER_OMIT_DECLTYPE
8379 #   define COLNAME_N      1      /* Store only the name */
8380 # else
8381 #   define COLNAME_N      2      /* Store the name and decltype */
8382 # endif
8383 #endif
8384
8385 /*
8386 ** The following macro converts a relative address in the p2 field
8387 ** of a VdbeOp structure into a negative number so that 
8388 ** sqlcipher3VdbeAddOpList() knows that the address is relative.  Calling
8389 ** the macro again restores the address.
8390 */
8391 #define ADDR(X)  (-1-(X))
8392
8393 /*
8394 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8395 ** header file that defines a number for each opcode used by the VDBE.
8396 */
8397 /************** Include opcodes.h in the middle of vdbe.h ********************/
8398 /************** Begin file opcodes.h *****************************************/
8399 /* Automatically generated.  Do not edit */
8400 /* See the mkopcodeh.awk script for details */
8401 #define OP_Goto                                 1
8402 #define OP_Gosub                                2
8403 #define OP_Return                               3
8404 #define OP_Yield                                4
8405 #define OP_HaltIfNull                           5
8406 #define OP_Halt                                 6
8407 #define OP_Integer                              7
8408 #define OP_Int64                                8
8409 #define OP_Real                               130   /* same as TK_FLOAT    */
8410 #define OP_String8                             94   /* same as TK_STRING   */
8411 #define OP_String                               9
8412 #define OP_Null                                10
8413 #define OP_Blob                                11
8414 #define OP_Variable                            12
8415 #define OP_Move                                13
8416 #define OP_Copy                                14
8417 #define OP_SCopy                               15
8418 #define OP_ResultRow                           16
8419 #define OP_Concat                              91   /* same as TK_CONCAT   */
8420 #define OP_Add                                 86   /* same as TK_PLUS     */
8421 #define OP_Subtract                            87   /* same as TK_MINUS    */
8422 #define OP_Multiply                            88   /* same as TK_STAR     */
8423 #define OP_Divide                              89   /* same as TK_SLASH    */
8424 #define OP_Remainder                           90   /* same as TK_REM      */
8425 #define OP_CollSeq                             17
8426 #define OP_Function                            18
8427 #define OP_BitAnd                              82   /* same as TK_BITAND   */
8428 #define OP_BitOr                               83   /* same as TK_BITOR    */
8429 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8430 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8431 #define OP_AddImm                              20
8432 #define OP_MustBeInt                           21
8433 #define OP_RealAffinity                        22
8434 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
8435 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8436 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8437 #define OP_ToInt                              144   /* same as TK_TO_INT   */
8438 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
8439 #define OP_Eq                                  76   /* same as TK_EQ       */
8440 #define OP_Ne                                  75   /* same as TK_NE       */
8441 #define OP_Lt                                  79   /* same as TK_LT       */
8442 #define OP_Le                                  78   /* same as TK_LE       */
8443 #define OP_Gt                                  77   /* same as TK_GT       */
8444 #define OP_Ge                                  80   /* same as TK_GE       */
8445 #define OP_Permutation                         23
8446 #define OP_Compare                             24
8447 #define OP_Jump                                25
8448 #define OP_And                                 69   /* same as TK_AND      */
8449 #define OP_Or                                  68   /* same as TK_OR       */
8450 #define OP_Not                                 19   /* same as TK_NOT      */
8451 #define OP_BitNot                              93   /* same as TK_BITNOT   */
8452 #define OP_Once                                26
8453 #define OP_If                                  27
8454 #define OP_IfNot                               28
8455 #define OP_IsNull                              73   /* same as TK_ISNULL   */
8456 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
8457 #define OP_Column                              29
8458 #define OP_Affinity                            30
8459 #define OP_MakeRecord                          31
8460 #define OP_Count                               32
8461 #define OP_Savepoint                           33
8462 #define OP_AutoCommit                          34
8463 #define OP_Transaction                         35
8464 #define OP_ReadCookie                          36
8465 #define OP_SetCookie                           37
8466 #define OP_VerifyCookie                        38
8467 #define OP_OpenRead                            39
8468 #define OP_OpenWrite                           40
8469 #define OP_OpenAutoindex                       41
8470 #define OP_OpenEphemeral                       42
8471 #define OP_SorterOpen                          43
8472 #define OP_OpenPseudo                          44
8473 #define OP_Close                               45
8474 #define OP_SeekLt                              46
8475 #define OP_SeekLe                              47
8476 #define OP_SeekGe                              48
8477 #define OP_SeekGt                              49
8478 #define OP_Seek                                50
8479 #define OP_NotFound                            51
8480 #define OP_Found                               52
8481 #define OP_IsUnique                            53
8482 #define OP_NotExists                           54
8483 #define OP_Sequence                            55
8484 #define OP_NewRowid                            56
8485 #define OP_Insert                              57
8486 #define OP_InsertInt                           58
8487 #define OP_Delete                              59
8488 #define OP_ResetCount                          60
8489 #define OP_SorterCompare                       61
8490 #define OP_SorterData                          62
8491 #define OP_RowKey                              63
8492 #define OP_RowData                             64
8493 #define OP_Rowid                               65
8494 #define OP_NullRow                             66
8495 #define OP_Last                                67
8496 #define OP_SorterSort                          70
8497 #define OP_Sort                                71
8498 #define OP_Rewind                              72
8499 #define OP_SorterNext                          81
8500 #define OP_Prev                                92
8501 #define OP_Next                                95
8502 #define OP_SorterInsert                        96
8503 #define OP_IdxInsert                           97
8504 #define OP_IdxDelete                           98
8505 #define OP_IdxRowid                            99
8506 #define OP_IdxLT                              100
8507 #define OP_IdxGE                              101
8508 #define OP_Destroy                            102
8509 #define OP_Clear                              103
8510 #define OP_CreateIndex                        104
8511 #define OP_CreateTable                        105
8512 #define OP_ParseSchema                        106
8513 #define OP_LoadAnalysis                       107
8514 #define OP_DropTable                          108
8515 #define OP_DropIndex                          109
8516 #define OP_DropTrigger                        110
8517 #define OP_IntegrityCk                        111
8518 #define OP_RowSetAdd                          112
8519 #define OP_RowSetRead                         113
8520 #define OP_RowSetTest                         114
8521 #define OP_Program                            115
8522 #define OP_Param                              116
8523 #define OP_FkCounter                          117
8524 #define OP_FkIfZero                           118
8525 #define OP_MemMax                             119
8526 #define OP_IfPos                              120
8527 #define OP_IfNeg                              121
8528 #define OP_IfZero                             122
8529 #define OP_AggStep                            123
8530 #define OP_AggFinal                           124
8531 #define OP_Checkpoint                         125
8532 #define OP_JournalMode                        126
8533 #define OP_Vacuum                             127
8534 #define OP_IncrVacuum                         128
8535 #define OP_Expire                             129
8536 #define OP_TableLock                          131
8537 #define OP_VBegin                             132
8538 #define OP_VCreate                            133
8539 #define OP_VDestroy                           134
8540 #define OP_VOpen                              135
8541 #define OP_VFilter                            136
8542 #define OP_VColumn                            137
8543 #define OP_VNext                              138
8544 #define OP_VRename                            139
8545 #define OP_VUpdate                            140
8546 #define OP_Pagecount                          146
8547 #define OP_MaxPgcnt                           147
8548 #define OP_Trace                              148
8549 #define OP_Noop                               149
8550 #define OP_Explain                            150
8551
8552
8553 /* Properties such as "out2" or "jump" that are specified in
8554 ** comments following the "case" for each opcode in the vdbe.c
8555 ** are encoded into bitvectors as follows:
8556 */
8557 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8558 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8559 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8560 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8561 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8562 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8563 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8564 #define OPFLG_INITIALIZER {\
8565 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
8566 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8567 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8568 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00,\
8569 /*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
8570 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
8571 /*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
8572 /*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8573 /*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
8574 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8575 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8576 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
8577 /*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
8578 /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8579 /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
8580 /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
8581 /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8582 /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
8583 /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
8584
8585 /************** End of opcodes.h *********************************************/
8586 /************** Continuing where we left off in vdbe.h ***********************/
8587
8588 /*
8589 ** Prototypes for the VDBE interface.  See comments on the implementation
8590 ** for a description of what each of these routines does.
8591 */
8592 SQLCIPHER_PRIVATE Vdbe *sqlcipher3VdbeCreate(sqlcipher3*);
8593 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp0(Vdbe*,int);
8594 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp1(Vdbe*,int,int);
8595 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp2(Vdbe*,int,int,int);
8596 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp3(Vdbe*,int,int,int,int);
8597 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8598 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8599 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8600 SQLCIPHER_PRIVATE void sqlcipher3VdbeAddParseSchemaOp(Vdbe*,int,char*);
8601 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP1(Vdbe*, u32 addr, int P1);
8602 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP2(Vdbe*, u32 addr, int P2);
8603 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP3(Vdbe*, u32 addr, int P3);
8604 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP5(Vdbe*, u8 P5);
8605 SQLCIPHER_PRIVATE void sqlcipher3VdbeJumpHere(Vdbe*, int addr);
8606 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeToNoop(Vdbe*, int addr);
8607 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8608 SQLCIPHER_PRIVATE void sqlcipher3VdbeUsesBtree(Vdbe*, int);
8609 SQLCIPHER_PRIVATE VdbeOp *sqlcipher3VdbeGetOp(Vdbe*, int);
8610 SQLCIPHER_PRIVATE int sqlcipher3VdbeMakeLabel(Vdbe*);
8611 SQLCIPHER_PRIVATE void sqlcipher3VdbeRunOnlyOnce(Vdbe*);
8612 SQLCIPHER_PRIVATE void sqlcipher3VdbeDelete(Vdbe*);
8613 SQLCIPHER_PRIVATE void sqlcipher3VdbeDeleteObject(sqlcipher3*,Vdbe*);
8614 SQLCIPHER_PRIVATE void sqlcipher3VdbeMakeReady(Vdbe*,Parse*);
8615 SQLCIPHER_PRIVATE int sqlcipher3VdbeFinalize(Vdbe*);
8616 SQLCIPHER_PRIVATE void sqlcipher3VdbeResolveLabel(Vdbe*, int);
8617 SQLCIPHER_PRIVATE int sqlcipher3VdbeCurrentAddr(Vdbe*);
8618 #ifdef SQLCIPHER_DEBUG
8619 SQLCIPHER_PRIVATE   int sqlcipher3VdbeAssertMayAbort(Vdbe *, int);
8620 SQLCIPHER_PRIVATE   void sqlcipher3VdbeTrace(Vdbe*,FILE*);
8621 #endif
8622 SQLCIPHER_PRIVATE void sqlcipher3VdbeResetStepResult(Vdbe*);
8623 SQLCIPHER_PRIVATE void sqlcipher3VdbeRewind(Vdbe*);
8624 SQLCIPHER_PRIVATE int sqlcipher3VdbeReset(Vdbe*);
8625 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetNumCols(Vdbe*,int);
8626 SQLCIPHER_PRIVATE int sqlcipher3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8627 SQLCIPHER_PRIVATE void sqlcipher3VdbeCountChanges(Vdbe*);
8628 SQLCIPHER_PRIVATE sqlcipher3 *sqlcipher3VdbeDb(Vdbe*);
8629 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetSql(Vdbe*, const char *z, int n, int);
8630 SQLCIPHER_PRIVATE void sqlcipher3VdbeSwap(Vdbe*,Vdbe*);
8631 SQLCIPHER_PRIVATE VdbeOp *sqlcipher3VdbeTakeOpArray(Vdbe*, int*, int*);
8632 SQLCIPHER_PRIVATE sqlcipher3_value *sqlcipher3VdbeGetValue(Vdbe*, int, u8);
8633 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetVarmask(Vdbe*, int);
8634 #ifndef SQLCIPHER_OMIT_TRACE
8635 SQLCIPHER_PRIVATE   char *sqlcipher3VdbeExpandSql(Vdbe*, const char*);
8636 #endif
8637
8638 SQLCIPHER_PRIVATE void sqlcipher3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
8639 SQLCIPHER_PRIVATE int sqlcipher3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8640 SQLCIPHER_PRIVATE UnpackedRecord *sqlcipher3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
8641
8642 #ifndef SQLCIPHER_OMIT_TRIGGER
8643 SQLCIPHER_PRIVATE void sqlcipher3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8644 #endif
8645
8646
8647 #ifndef NDEBUG
8648 SQLCIPHER_PRIVATE   void sqlcipher3VdbeComment(Vdbe*, const char*, ...);
8649 # define VdbeComment(X)  sqlcipher3VdbeComment X
8650 SQLCIPHER_PRIVATE   void sqlcipher3VdbeNoopComment(Vdbe*, const char*, ...);
8651 # define VdbeNoopComment(X)  sqlcipher3VdbeNoopComment X
8652 #else
8653 # define VdbeComment(X)
8654 # define VdbeNoopComment(X)
8655 #endif
8656
8657 #endif
8658
8659 /************** End of vdbe.h ************************************************/
8660 /************** Continuing where we left off in sqlcipherInt.h ******************/
8661 /************** Include pager.h in the middle of sqlcipherInt.h *****************/
8662 /************** Begin file pager.h *******************************************/
8663 /*
8664 ** 2001 September 15
8665 **
8666 ** The author disclaims copyright to this source code.  In place of
8667 ** a legal notice, here is a blessing:
8668 **
8669 **    May you do good and not evil.
8670 **    May you find forgiveness for yourself and forgive others.
8671 **    May you share freely, never taking more than you give.
8672 **
8673 *************************************************************************
8674 ** This header file defines the interface that the sqlcipher page cache
8675 ** subsystem.  The page cache subsystem reads and writes a file a page
8676 ** at a time and provides a journal for rollback.
8677 */
8678
8679 #ifndef _PAGER_H_
8680 #define _PAGER_H_
8681
8682 /*
8683 ** Default maximum size for persistent journal files. A negative 
8684 ** value means no limit. This value may be overridden using the 
8685 ** sqlcipher3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8686 */
8687 #ifndef SQLCIPHER_DEFAULT_JOURNAL_SIZE_LIMIT
8688   #define SQLCIPHER_DEFAULT_JOURNAL_SIZE_LIMIT -1
8689 #endif
8690
8691 /*
8692 ** The type used to represent a page number.  The first page in a file
8693 ** is called page 1.  0 is used to represent "not a page".
8694 */
8695 typedef u32 Pgno;
8696
8697 /*
8698 ** Each open file is managed by a separate instance of the "Pager" structure.
8699 */
8700 typedef struct Pager Pager;
8701
8702 /*
8703 ** Handle type for pages.
8704 */
8705 typedef struct PgHdr DbPage;
8706
8707 /*
8708 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8709 ** reserved for working around a windows/posix incompatibility). It is
8710 ** used in the journal to signify that the remainder of the journal file 
8711 ** is devoted to storing a master journal name - there are no more pages to
8712 ** roll back. See comments for function writeMasterJournal() in pager.c 
8713 ** for details.
8714 */
8715 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8716
8717 /*
8718 ** Allowed values for the flags parameter to sqlcipher3PagerOpen().
8719 **
8720 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8721 */
8722 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8723 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8724 #define PAGER_MEMORY        0x0004    /* In-memory database */
8725
8726 /*
8727 ** Valid values for the second argument to sqlcipher3PagerLockingMode().
8728 */
8729 #define PAGER_LOCKINGMODE_QUERY      -1
8730 #define PAGER_LOCKINGMODE_NORMAL      0
8731 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8732
8733 /*
8734 ** Numeric constants that encode the journalmode.  
8735 */
8736 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
8737 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8738 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8739 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8740 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8741 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8742 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
8743
8744 /*
8745 ** The remainder of this file contains the declarations of the functions
8746 ** that make up the Pager sub-system API. See source code comments for 
8747 ** a detailed description of each routine.
8748 */
8749
8750 /* Open and close a Pager connection. */ 
8751 SQLCIPHER_PRIVATE int sqlcipher3PagerOpen(
8752   sqlcipher3_vfs*,
8753   Pager **ppPager,
8754   const char*,
8755   int,
8756   int,
8757   int,
8758   void(*)(DbPage*)
8759 );
8760 SQLCIPHER_PRIVATE int sqlcipher3PagerClose(Pager *pPager);
8761 SQLCIPHER_PRIVATE int sqlcipher3PagerReadFileheader(Pager*, int, unsigned char*);
8762
8763 /* Functions used to configure a Pager object. */
8764 SQLCIPHER_PRIVATE void sqlcipher3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8765 SQLCIPHER_PRIVATE int sqlcipher3PagerSetPagesize(Pager*, u32*, int);
8766 SQLCIPHER_PRIVATE int sqlcipher3PagerMaxPageCount(Pager*, int);
8767 SQLCIPHER_PRIVATE void sqlcipher3PagerSetCachesize(Pager*, int);
8768 SQLCIPHER_PRIVATE void sqlcipher3PagerSetSafetyLevel(Pager*,int,int,int);
8769 SQLCIPHER_PRIVATE int sqlcipher3PagerLockingMode(Pager *, int);
8770 SQLCIPHER_PRIVATE int sqlcipher3PagerSetJournalMode(Pager *, int);
8771 SQLCIPHER_PRIVATE int sqlcipher3PagerGetJournalMode(Pager*);
8772 SQLCIPHER_PRIVATE int sqlcipher3PagerOkToChangeJournalMode(Pager*);
8773 SQLCIPHER_PRIVATE i64 sqlcipher3PagerJournalSizeLimit(Pager *, i64);
8774 SQLCIPHER_PRIVATE sqlcipher3_backup **sqlcipher3PagerBackupPtr(Pager*);
8775
8776 /* Functions used to obtain and release page references. */ 
8777 SQLCIPHER_PRIVATE int sqlcipher3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8778 #define sqlcipher3PagerGet(A,B,C) sqlcipher3PagerAcquire(A,B,C,0)
8779 SQLCIPHER_PRIVATE DbPage *sqlcipher3PagerLookup(Pager *pPager, Pgno pgno);
8780 SQLCIPHER_PRIVATE void sqlcipher3PagerRef(DbPage*);
8781 SQLCIPHER_PRIVATE void sqlcipher3PagerUnref(DbPage*);
8782
8783 /* Operations on page references. */
8784 SQLCIPHER_PRIVATE int sqlcipher3PagerWrite(DbPage*);
8785 SQLCIPHER_PRIVATE void sqlcipher3PagerDontWrite(DbPage*);
8786 SQLCIPHER_PRIVATE int sqlcipher3PagerMovepage(Pager*,DbPage*,Pgno,int);
8787 SQLCIPHER_PRIVATE int sqlcipher3PagerPageRefcount(DbPage*);
8788 SQLCIPHER_PRIVATE void *sqlcipher3PagerGetData(DbPage *); 
8789 SQLCIPHER_PRIVATE void *sqlcipher3PagerGetExtra(DbPage *); 
8790
8791 /* Functions used to manage pager transactions and savepoints. */
8792 SQLCIPHER_PRIVATE void sqlcipher3PagerPagecount(Pager*, int*);
8793 SQLCIPHER_PRIVATE int sqlcipher3PagerBegin(Pager*, int exFlag, int);
8794 SQLCIPHER_PRIVATE int sqlcipher3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8795 SQLCIPHER_PRIVATE int sqlcipher3PagerExclusiveLock(Pager*);
8796 SQLCIPHER_PRIVATE int sqlcipher3PagerSync(Pager *pPager);
8797 SQLCIPHER_PRIVATE int sqlcipher3PagerCommitPhaseTwo(Pager*);
8798 SQLCIPHER_PRIVATE int sqlcipher3PagerRollback(Pager*);
8799 SQLCIPHER_PRIVATE int sqlcipher3PagerOpenSavepoint(Pager *pPager, int n);
8800 SQLCIPHER_PRIVATE int sqlcipher3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8801 SQLCIPHER_PRIVATE int sqlcipher3PagerSharedLock(Pager *pPager);
8802
8803 SQLCIPHER_PRIVATE int sqlcipher3PagerCheckpoint(Pager *pPager, int, int*, int*);
8804 SQLCIPHER_PRIVATE int sqlcipher3PagerWalSupported(Pager *pPager);
8805 SQLCIPHER_PRIVATE int sqlcipher3PagerWalCallback(Pager *pPager);
8806 SQLCIPHER_PRIVATE int sqlcipher3PagerOpenWal(Pager *pPager, int *pisOpen);
8807 SQLCIPHER_PRIVATE int sqlcipher3PagerCloseWal(Pager *pPager);
8808
8809 /* Functions used to query pager state and configuration. */
8810 SQLCIPHER_PRIVATE u8 sqlcipher3PagerIsreadonly(Pager*);
8811 SQLCIPHER_PRIVATE int sqlcipher3PagerRefcount(Pager*);
8812 SQLCIPHER_PRIVATE int sqlcipher3PagerMemUsed(Pager*);
8813 SQLCIPHER_PRIVATE const char *sqlcipher3PagerFilename(Pager*);
8814 SQLCIPHER_PRIVATE const sqlcipher3_vfs *sqlcipher3PagerVfs(Pager*);
8815 SQLCIPHER_PRIVATE sqlcipher3_file *sqlcipher3PagerFile(Pager*);
8816 SQLCIPHER_PRIVATE const char *sqlcipher3PagerJournalname(Pager*);
8817 SQLCIPHER_PRIVATE int sqlcipher3PagerNosync(Pager*);
8818 SQLCIPHER_PRIVATE void *sqlcipher3PagerTempSpace(Pager*);
8819 SQLCIPHER_PRIVATE int sqlcipher3PagerIsMemdb(Pager*);
8820 SQLCIPHER_PRIVATE void sqlcipher3PagerCacheStat(Pager *, int, int, int *);
8821 SQLCIPHER_PRIVATE void sqlcipher3PagerClearCache(Pager *);
8822
8823 /* Functions used to truncate the database file. */
8824 SQLCIPHER_PRIVATE void sqlcipher3PagerTruncateImage(Pager*,Pgno);
8825
8826 #if defined(SQLCIPHER_HAS_CODEC) && !defined(SQLCIPHER_OMIT_WAL)
8827 SQLCIPHER_PRIVATE void *sqlcipher3PagerCodec(DbPage *);
8828 #endif
8829
8830 /* Functions to support testing and debugging. */
8831 #if !defined(NDEBUG) || defined(SQLCIPHER_TEST)
8832 SQLCIPHER_PRIVATE   Pgno sqlcipher3PagerPagenumber(DbPage*);
8833 SQLCIPHER_PRIVATE   int sqlcipher3PagerIswriteable(DbPage*);
8834 #endif
8835 #ifdef SQLCIPHER_TEST
8836 SQLCIPHER_PRIVATE   int *sqlcipher3PagerStats(Pager*);
8837 SQLCIPHER_PRIVATE   void sqlcipher3PagerRefdump(Pager*);
8838   void disable_simulated_io_errors(void);
8839   void enable_simulated_io_errors(void);
8840 #else
8841 # define disable_simulated_io_errors()
8842 # define enable_simulated_io_errors()
8843 #endif
8844
8845 #endif /* _PAGER_H_ */
8846
8847 /************** End of pager.h ***********************************************/
8848 /************** Continuing where we left off in sqlcipherInt.h ******************/
8849 /************** Include pcache.h in the middle of sqlcipherInt.h ****************/
8850 /************** Begin file pcache.h ******************************************/
8851 /*
8852 ** 2008 August 05
8853 **
8854 ** The author disclaims copyright to this source code.  In place of
8855 ** a legal notice, here is a blessing:
8856 **
8857 **    May you do good and not evil.
8858 **    May you find forgiveness for yourself and forgive others.
8859 **    May you share freely, never taking more than you give.
8860 **
8861 *************************************************************************
8862 ** This header file defines the interface that the sqlcipher page cache
8863 ** subsystem. 
8864 */
8865
8866 #ifndef _PCACHE_H_
8867
8868 typedef struct PgHdr PgHdr;
8869 typedef struct PCache PCache;
8870
8871 /*
8872 ** Every page in the cache is controlled by an instance of the following
8873 ** structure.
8874 */
8875 struct PgHdr {
8876   void *pData;                   /* Content of this page */
8877   void *pExtra;                  /* Extra content */
8878   PgHdr *pDirty;                 /* Transient list of dirty pages */
8879   Pgno pgno;                     /* Page number for this page */
8880   Pager *pPager;                 /* The pager this page is part of */
8881 #ifdef SQLCIPHER_CHECK_PAGES
8882   u32 pageHash;                  /* Hash of page content */
8883 #endif
8884   u16 flags;                     /* PGHDR flags defined below */
8885
8886   /**********************************************************************
8887   ** Elements above are public.  All that follows is private to pcache.c
8888   ** and should not be accessed by other modules.
8889   */
8890   i16 nRef;                      /* Number of users of this page */
8891   PCache *pCache;                /* Cache that owns this page */
8892
8893   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
8894   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
8895 };
8896
8897 /* Bit values for PgHdr.flags */
8898 #define PGHDR_DIRTY             0x002  /* Page has changed */
8899 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8900                                        ** writing this page to the database */
8901 #define PGHDR_NEED_READ         0x008  /* Content is unread */
8902 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8903 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8904
8905 /* Initialize and shutdown the page cache subsystem */
8906 SQLCIPHER_PRIVATE int sqlcipher3PcacheInitialize(void);
8907 SQLCIPHER_PRIVATE void sqlcipher3PcacheShutdown(void);
8908
8909 /* Page cache buffer management:
8910 ** These routines implement SQLCIPHER_CONFIG_PAGECACHE.
8911 */
8912 SQLCIPHER_PRIVATE void sqlcipher3PCacheBufferSetup(void *, int sz, int n);
8913
8914 /* Create a new pager cache.
8915 ** Under memory stress, invoke xStress to try to make pages clean.
8916 ** Only clean and unpinned pages can be reclaimed.
8917 */
8918 SQLCIPHER_PRIVATE void sqlcipher3PcacheOpen(
8919   int szPage,                    /* Size of every page */
8920   int szExtra,                   /* Extra space associated with each page */
8921   int bPurgeable,                /* True if pages are on backing store */
8922   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8923   void *pStress,                 /* Argument to xStress */
8924   PCache *pToInit                /* Preallocated space for the PCache */
8925 );
8926
8927 /* Modify the page-size after the cache has been created. */
8928 SQLCIPHER_PRIVATE void sqlcipher3PcacheSetPageSize(PCache *, int);
8929
8930 /* Return the size in bytes of a PCache object.  Used to preallocate
8931 ** storage space.
8932 */
8933 SQLCIPHER_PRIVATE int sqlcipher3PcacheSize(void);
8934
8935 /* One release per successful fetch.  Page is pinned until released.
8936 ** Reference counted. 
8937 */
8938 SQLCIPHER_PRIVATE int sqlcipher3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8939 SQLCIPHER_PRIVATE void sqlcipher3PcacheRelease(PgHdr*);
8940
8941 SQLCIPHER_PRIVATE void sqlcipher3PcacheDrop(PgHdr*);         /* Remove page from cache */
8942 SQLCIPHER_PRIVATE void sqlcipher3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8943 SQLCIPHER_PRIVATE void sqlcipher3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8944 SQLCIPHER_PRIVATE void sqlcipher3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8945
8946 /* Change a page number.  Used by incr-vacuum. */
8947 SQLCIPHER_PRIVATE void sqlcipher3PcacheMove(PgHdr*, Pgno);
8948
8949 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8950 SQLCIPHER_PRIVATE void sqlcipher3PcacheTruncate(PCache*, Pgno x);
8951
8952 /* Get a list of all dirty pages in the cache, sorted by page number */
8953 SQLCIPHER_PRIVATE PgHdr *sqlcipher3PcacheDirtyList(PCache*);
8954
8955 /* Reset and close the cache object */
8956 SQLCIPHER_PRIVATE void sqlcipher3PcacheClose(PCache*);
8957
8958 /* Clear flags from pages of the page cache */
8959 SQLCIPHER_PRIVATE void sqlcipher3PcacheClearSyncFlags(PCache *);
8960
8961 /* Discard the contents of the cache */
8962 SQLCIPHER_PRIVATE void sqlcipher3PcacheClear(PCache*);
8963
8964 /* Return the total number of outstanding page references */
8965 SQLCIPHER_PRIVATE int sqlcipher3PcacheRefCount(PCache*);
8966
8967 /* Increment the reference count of an existing page */
8968 SQLCIPHER_PRIVATE void sqlcipher3PcacheRef(PgHdr*);
8969
8970 SQLCIPHER_PRIVATE int sqlcipher3PcachePageRefcount(PgHdr*);
8971
8972 /* Return the total number of pages stored in the cache */
8973 SQLCIPHER_PRIVATE int sqlcipher3PcachePagecount(PCache*);
8974
8975 #if defined(SQLCIPHER_CHECK_PAGES) || defined(SQLCIPHER_DEBUG)
8976 /* Iterate through all dirty pages currently stored in the cache. This
8977 ** interface is only available if SQLCIPHER_CHECK_PAGES is defined when the 
8978 ** library is built.
8979 */
8980 SQLCIPHER_PRIVATE void sqlcipher3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8981 #endif
8982
8983 /* Set and get the suggested cache-size for the specified pager-cache.
8984 **
8985 ** If no global maximum is configured, then the system attempts to limit
8986 ** the total number of pages cached by purgeable pager-caches to the sum
8987 ** of the suggested cache-sizes.
8988 */
8989 SQLCIPHER_PRIVATE void sqlcipher3PcacheSetCachesize(PCache *, int);
8990 #ifdef SQLCIPHER_TEST
8991 SQLCIPHER_PRIVATE int sqlcipher3PcacheGetCachesize(PCache *);
8992 #endif
8993
8994 #ifdef SQLCIPHER_ENABLE_MEMORY_MANAGEMENT
8995 /* Try to return memory used by the pcache module to the main memory heap */
8996 SQLCIPHER_PRIVATE int sqlcipher3PcacheReleaseMemory(int);
8997 #endif
8998
8999 #ifdef SQLCIPHER_TEST
9000 SQLCIPHER_PRIVATE void sqlcipher3PcacheStats(int*,int*,int*,int*);
9001 #endif
9002
9003 SQLCIPHER_PRIVATE void sqlcipher3PCacheSetDefault(void);
9004
9005 #endif /* _PCACHE_H_ */
9006
9007 /************** End of pcache.h **********************************************/
9008 /************** Continuing where we left off in sqlcipherInt.h ******************/
9009
9010 /************** Include os.h in the middle of sqlcipherInt.h ********************/
9011 /************** Begin file os.h **********************************************/
9012 /*
9013 ** 2001 September 16
9014 **
9015 ** The author disclaims copyright to this source code.  In place of
9016 ** a legal notice, here is a blessing:
9017 **
9018 **    May you do good and not evil.
9019 **    May you find forgiveness for yourself and forgive others.
9020 **    May you share freely, never taking more than you give.
9021 **
9022 ******************************************************************************
9023 **
9024 ** This header file (together with is companion C source-code file
9025 ** "os.c") attempt to abstract the underlying operating system so that
9026 ** the SQLite library will work on both POSIX and windows systems.
9027 **
9028 ** This header file is #include-ed by sqlcipherInt.h and thus ends up
9029 ** being included by every source file.
9030 */
9031 #ifndef _SQLCIPHER_OS_H_
9032 #define _SQLCIPHER_OS_H_
9033
9034 /*
9035 ** Figure out if we are dealing with Unix, Windows, or some other
9036 ** operating system.  After the following block of preprocess macros,
9037 ** all of SQLCIPHER_OS_UNIX, SQLCIPHER_OS_WIN, SQLCIPHER_OS_OS2, and SQLCIPHER_OS_OTHER 
9038 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
9039 ** three will be 0.
9040 */
9041 #if defined(SQLCIPHER_OS_OTHER)
9042 # if SQLCIPHER_OS_OTHER==1
9043 #   undef SQLCIPHER_OS_UNIX
9044 #   define SQLCIPHER_OS_UNIX 0
9045 #   undef SQLCIPHER_OS_WIN
9046 #   define SQLCIPHER_OS_WIN 0
9047 #   undef SQLCIPHER_OS_OS2
9048 #   define SQLCIPHER_OS_OS2 0
9049 # else
9050 #   undef SQLCIPHER_OS_OTHER
9051 # endif
9052 #endif
9053 #if !defined(SQLCIPHER_OS_UNIX) && !defined(SQLCIPHER_OS_OTHER)
9054 # define SQLCIPHER_OS_OTHER 0
9055 # ifndef SQLCIPHER_OS_WIN
9056 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9057 #     define SQLCIPHER_OS_WIN 1
9058 #     define SQLCIPHER_OS_UNIX 0
9059 #     define SQLCIPHER_OS_OS2 0
9060 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
9061 #     define SQLCIPHER_OS_WIN 0
9062 #     define SQLCIPHER_OS_UNIX 0
9063 #     define SQLCIPHER_OS_OS2 1
9064 #   else
9065 #     define SQLCIPHER_OS_WIN 0
9066 #     define SQLCIPHER_OS_UNIX 1
9067 #     define SQLCIPHER_OS_OS2 0
9068 #  endif
9069 # else
9070 #  define SQLCIPHER_OS_UNIX 0
9071 #  define SQLCIPHER_OS_OS2 0
9072 # endif
9073 #else
9074 # ifndef SQLCIPHER_OS_WIN
9075 #  define SQLCIPHER_OS_WIN 0
9076 # endif
9077 #endif
9078
9079 /*
9080 ** Determine if we are dealing with WindowsCE - which has a much
9081 ** reduced API.
9082 */
9083 #if defined(_WIN32_WCE)
9084 # define SQLCIPHER_OS_WINCE 1
9085 #else
9086 # define SQLCIPHER_OS_WINCE 0
9087 #endif
9088
9089
9090 /*
9091 ** Define the maximum size of a temporary filename
9092 */
9093 #if SQLCIPHER_OS_WIN
9094 # include <windows.h>
9095 # define SQLCIPHER_TEMPNAME_SIZE (MAX_PATH+50)
9096 #elif SQLCIPHER_OS_OS2
9097 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
9098 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
9099 # endif
9100 # define INCL_DOSDATETIME
9101 # define INCL_DOSFILEMGR
9102 # define INCL_DOSERRORS
9103 # define INCL_DOSMISC
9104 # define INCL_DOSPROCESS
9105 # define INCL_DOSMODULEMGR
9106 # define INCL_DOSSEMAPHORES
9107 # include <os2.h>
9108 # include <uconv.h>
9109 # define SQLCIPHER_TEMPNAME_SIZE (CCHMAXPATHCOMP)
9110 #else
9111 # define SQLCIPHER_TEMPNAME_SIZE 200
9112 #endif
9113
9114 /* If the SET_FULLSYNC macro is not defined above, then make it
9115 ** a no-op
9116 */
9117 #ifndef SET_FULLSYNC
9118 # define SET_FULLSYNC(x,y)
9119 #endif
9120
9121 /*
9122 ** The default size of a disk sector
9123 */
9124 #ifndef SQLCIPHER_DEFAULT_SECTOR_SIZE
9125 # define SQLCIPHER_DEFAULT_SECTOR_SIZE 512
9126 #endif
9127
9128 /*
9129 ** Temporary files are named starting with this prefix followed by 16 random
9130 ** alphanumeric characters, and no file extension. They are stored in the
9131 ** OS's standard temporary file directory, and are deleted prior to exit.
9132 ** If sqlcipher is being embedded in another program, you may wish to change the
9133 ** prefix to reflect your program's name, so that if your program exits
9134 ** prematurely, old temporary files can be easily identified. This can be done
9135 ** using -DSQLCIPHER_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9136 **
9137 ** 2006-10-31:  The default prefix used to be "sqlcipher_".  But then
9138 ** Mcafee started using SQLite in their anti-virus product and it
9139 ** started putting files with the "sqlcipher" name in the c:/temp folder.
9140 ** This annoyed many windows users.  Those users would then do a 
9141 ** Google search for "sqlcipher", find the telephone numbers of the
9142 ** developers and call to wake them up at night and complain.
9143 ** For this reason, the default name prefix is changed to be "sqlcipher" 
9144 ** spelled backwards.  So the temp files are still identified, but
9145 ** anybody smart enough to figure out the code is also likely smart
9146 ** enough to know that calling the developer will not help get rid
9147 ** of the file.
9148 */
9149 #ifndef SQLCIPHER_TEMP_FILE_PREFIX
9150 # define SQLCIPHER_TEMP_FILE_PREFIX "etilqs_"
9151 #endif
9152
9153 /*
9154 ** The following values may be passed as the second argument to
9155 ** sqlcipher3OsLock(). The various locks exhibit the following semantics:
9156 **
9157 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9158 ** RESERVED:  A single process may hold a RESERVED lock on a file at
9159 **            any time. Other processes may hold and obtain new SHARED locks.
9160 ** PENDING:   A single process may hold a PENDING lock on a file at
9161 **            any one time. Existing SHARED locks may persist, but no new
9162 **            SHARED locks may be obtained by other processes.
9163 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9164 **
9165 ** PENDING_LOCK may not be passed directly to sqlcipher3OsLock(). Instead, a
9166 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9167 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9168 ** sqlcipher3OsLock().
9169 */
9170 #define NO_LOCK         0
9171 #define SHARED_LOCK     1
9172 #define RESERVED_LOCK   2
9173 #define PENDING_LOCK    3
9174 #define EXCLUSIVE_LOCK  4
9175
9176 /*
9177 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
9178 **
9179 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9180 ** those functions are not available.  So we use only LockFile() and
9181 ** UnlockFile().
9182 **
9183 ** LockFile() prevents not just writing but also reading by other processes.
9184 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
9185 ** byte out of a specific range of bytes. The lock byte is obtained at 
9186 ** random so two separate readers can probably access the file at the 
9187 ** same time, unless they are unlucky and choose the same lock byte.
9188 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9189 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9190 ** a single byte of the file that is designated as the reserved lock byte.
9191 ** A PENDING_LOCK is obtained by locking a designated byte different from
9192 ** the RESERVED_LOCK byte.
9193 **
9194 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9195 ** which means we can use reader/writer locks.  When reader/writer locks
9196 ** are used, the lock is placed on the same range of bytes that is used
9197 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9198 ** will support two or more Win95 readers or two or more WinNT readers.
9199 ** But a single Win95 reader will lock out all WinNT readers and a single
9200 ** WinNT reader will lock out all other Win95 readers.
9201 **
9202 ** The following #defines specify the range of bytes used for locking.
9203 ** SHARED_SIZE is the number of bytes available in the pool from which
9204 ** a random byte is selected for a shared lock.  The pool of bytes for
9205 ** shared locks begins at SHARED_FIRST. 
9206 **
9207 ** The same locking strategy and
9208 ** byte ranges are used for Unix.  This leaves open the possiblity of having
9209 ** clients on win95, winNT, and unix all talking to the same shared file
9210 ** and all locking correctly.  To do so would require that samba (or whatever
9211 ** tool is being used for file sharing) implements locks correctly between
9212 ** windows and unix.  I'm guessing that isn't likely to happen, but by
9213 ** using the same locking range we are at least open to the possibility.
9214 **
9215 ** Locking in windows is manditory.  For this reason, we cannot store
9216 ** actual data in the bytes used for locking.  The pager never allocates
9217 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
9218 ** that all locks will fit on a single page even at the minimum page size.
9219 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9220 ** is set high so that we don't have to allocate an unused page except
9221 ** for very large databases.  But one should test the page skipping logic 
9222 ** by setting PENDING_BYTE low and running the entire regression suite.
9223 **
9224 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9225 ** file format.  Depending on how it is changed, you might not notice
9226 ** the incompatibility right away, even running a full regression test.
9227 ** The default location of PENDING_BYTE is the first byte past the
9228 ** 1GB boundary.
9229 **
9230 */
9231 #ifdef SQLCIPHER_OMIT_WSD
9232 # define PENDING_BYTE     (0x40000000)
9233 #else
9234 # define PENDING_BYTE      sqlcipher3PendingByte
9235 #endif
9236 #define RESERVED_BYTE     (PENDING_BYTE+1)
9237 #define SHARED_FIRST      (PENDING_BYTE+2)
9238 #define SHARED_SIZE       510
9239
9240 /*
9241 ** Wrapper around OS specific sqlcipher3_os_init() function.
9242 */
9243 SQLCIPHER_PRIVATE int sqlcipher3OsInit(void);
9244
9245 /* 
9246 ** Functions for accessing sqlcipher3_file methods 
9247 */
9248 SQLCIPHER_PRIVATE int sqlcipher3OsClose(sqlcipher3_file*);
9249 SQLCIPHER_PRIVATE int sqlcipher3OsRead(sqlcipher3_file*, void*, int amt, i64 offset);
9250 SQLCIPHER_PRIVATE int sqlcipher3OsWrite(sqlcipher3_file*, const void*, int amt, i64 offset);
9251 SQLCIPHER_PRIVATE int sqlcipher3OsTruncate(sqlcipher3_file*, i64 size);
9252 SQLCIPHER_PRIVATE int sqlcipher3OsSync(sqlcipher3_file*, int);
9253 SQLCIPHER_PRIVATE int sqlcipher3OsFileSize(sqlcipher3_file*, i64 *pSize);
9254 SQLCIPHER_PRIVATE int sqlcipher3OsLock(sqlcipher3_file*, int);
9255 SQLCIPHER_PRIVATE int sqlcipher3OsUnlock(sqlcipher3_file*, int);
9256 SQLCIPHER_PRIVATE int sqlcipher3OsCheckReservedLock(sqlcipher3_file *id, int *pResOut);
9257 SQLCIPHER_PRIVATE int sqlcipher3OsFileControl(sqlcipher3_file*,int,void*);
9258 #define SQLCIPHER_FCNTL_DB_UNCHANGED 0xca093fa0
9259 SQLCIPHER_PRIVATE int sqlcipher3OsSectorSize(sqlcipher3_file *id);
9260 SQLCIPHER_PRIVATE int sqlcipher3OsDeviceCharacteristics(sqlcipher3_file *id);
9261 SQLCIPHER_PRIVATE int sqlcipher3OsShmMap(sqlcipher3_file *,int,int,int,void volatile **);
9262 SQLCIPHER_PRIVATE int sqlcipher3OsShmLock(sqlcipher3_file *id, int, int, int);
9263 SQLCIPHER_PRIVATE void sqlcipher3OsShmBarrier(sqlcipher3_file *id);
9264 SQLCIPHER_PRIVATE int sqlcipher3OsShmUnmap(sqlcipher3_file *id, int);
9265
9266 /* 
9267 ** Functions for accessing sqlcipher3_vfs methods 
9268 */
9269 SQLCIPHER_PRIVATE int sqlcipher3OsOpen(sqlcipher3_vfs *, const char *, sqlcipher3_file*, int, int *);
9270 SQLCIPHER_PRIVATE int sqlcipher3OsDelete(sqlcipher3_vfs *, const char *, int);
9271 SQLCIPHER_PRIVATE int sqlcipher3OsAccess(sqlcipher3_vfs *, const char *, int, int *pResOut);
9272 SQLCIPHER_PRIVATE int sqlcipher3OsFullPathname(sqlcipher3_vfs *, const char *, int, char *);
9273 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
9274 SQLCIPHER_PRIVATE void *sqlcipher3OsDlOpen(sqlcipher3_vfs *, const char *);
9275 SQLCIPHER_PRIVATE void sqlcipher3OsDlError(sqlcipher3_vfs *, int, char *);
9276 SQLCIPHER_PRIVATE void (*sqlcipher3OsDlSym(sqlcipher3_vfs *, void *, const char *))(void);
9277 SQLCIPHER_PRIVATE void sqlcipher3OsDlClose(sqlcipher3_vfs *, void *);
9278 #endif /* SQLCIPHER_OMIT_LOAD_EXTENSION */
9279 SQLCIPHER_PRIVATE int sqlcipher3OsRandomness(sqlcipher3_vfs *, int, char *);
9280 SQLCIPHER_PRIVATE int sqlcipher3OsSleep(sqlcipher3_vfs *, int);
9281 SQLCIPHER_PRIVATE int sqlcipher3OsCurrentTimeInt64(sqlcipher3_vfs *, sqlcipher3_int64*);
9282
9283 /*
9284 ** Convenience functions for opening and closing files using 
9285 ** sqlcipher3_malloc() to obtain space for the file-handle structure.
9286 */
9287 SQLCIPHER_PRIVATE int sqlcipher3OsOpenMalloc(sqlcipher3_vfs *, const char *, sqlcipher3_file **, int,int*);
9288 SQLCIPHER_PRIVATE int sqlcipher3OsCloseFree(sqlcipher3_file *);
9289
9290 #endif /* _SQLCIPHER_OS_H_ */
9291
9292 /************** End of os.h **************************************************/
9293 /************** Continuing where we left off in sqlcipherInt.h ******************/
9294 /************** Include mutex.h in the middle of sqlcipherInt.h *****************/
9295 /************** Begin file mutex.h *******************************************/
9296 /*
9297 ** 2007 August 28
9298 **
9299 ** The author disclaims copyright to this source code.  In place of
9300 ** a legal notice, here is a blessing:
9301 **
9302 **    May you do good and not evil.
9303 **    May you find forgiveness for yourself and forgive others.
9304 **    May you share freely, never taking more than you give.
9305 **
9306 *************************************************************************
9307 **
9308 ** This file contains the common header for all mutex implementations.
9309 ** The sqlcipherInt.h header #includes this file so that it is available
9310 ** to all source files.  We break it out in an effort to keep the code
9311 ** better organized.
9312 **
9313 ** NOTE:  source files should *not* #include this header file directly.
9314 ** Source files should #include the sqlcipherInt.h file and let that file
9315 ** include this one indirectly.
9316 */
9317
9318
9319 /*
9320 ** Figure out what version of the code to use.  The choices are
9321 **
9322 **   SQLCIPHER_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9323 **                             mutexes implemention cannot be overridden
9324 **                             at start-time.
9325 **
9326 **   SQLCIPHER_MUTEX_NOOP         For single-threaded applications.  No
9327 **                             mutual exclusion is provided.  But this
9328 **                             implementation can be overridden at
9329 **                             start-time.
9330 **
9331 **   SQLCIPHER_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9332 **
9333 **   SQLCIPHER_MUTEX_W32          For multi-threaded applications on Win32.
9334 **
9335 **   SQLCIPHER_MUTEX_OS2          For multi-threaded applications on OS/2.
9336 */
9337 #if !SQLCIPHER_THREADSAFE
9338 # define SQLCIPHER_MUTEX_OMIT
9339 #endif
9340 #if SQLCIPHER_THREADSAFE && !defined(SQLCIPHER_MUTEX_NOOP)
9341 #  if SQLCIPHER_OS_UNIX
9342 #    define SQLCIPHER_MUTEX_PTHREADS
9343 #  elif SQLCIPHER_OS_WIN
9344 #    define SQLCIPHER_MUTEX_W32
9345 #  elif SQLCIPHER_OS_OS2
9346 #    define SQLCIPHER_MUTEX_OS2
9347 #  else
9348 #    define SQLCIPHER_MUTEX_NOOP
9349 #  endif
9350 #endif
9351
9352 #ifdef SQLCIPHER_MUTEX_OMIT
9353 /*
9354 ** If this is a no-op implementation, implement everything as macros.
9355 */
9356 #define sqlcipher3_mutex_alloc(X)    ((sqlcipher3_mutex*)8)
9357 #define sqlcipher3_mutex_free(X)
9358 #define sqlcipher3_mutex_enter(X)    
9359 #define sqlcipher3_mutex_try(X)      SQLCIPHER_OK
9360 #define sqlcipher3_mutex_leave(X)    
9361 #define sqlcipher3_mutex_held(X)     ((void)(X),1)
9362 #define sqlcipher3_mutex_notheld(X)  ((void)(X),1)
9363 #define sqlcipher3MutexAlloc(X)      ((sqlcipher3_mutex*)8)
9364 #define sqlcipher3MutexInit()        SQLCIPHER_OK
9365 #define sqlcipher3MutexEnd()
9366 #define MUTEX_LOGIC(X)
9367 #else
9368 #define MUTEX_LOGIC(X)            X
9369 #endif /* defined(SQLCIPHER_MUTEX_OMIT) */
9370
9371 /************** End of mutex.h ***********************************************/
9372 /************** Continuing where we left off in sqlcipherInt.h ******************/
9373
9374
9375 /*
9376 ** Each database file to be accessed by the system is an instance
9377 ** of the following structure.  There are normally two of these structures
9378 ** in the sqlcipher.aDb[] array.  aDb[0] is the main database file and
9379 ** aDb[1] is the database file used to hold temporary tables.  Additional
9380 ** databases may be attached.
9381 */
9382 struct Db {
9383   char *zName;         /* Name of this database */
9384   Btree *pBt;          /* The B*Tree structure for this database file */
9385   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9386   u8 safety_level;     /* How aggressive at syncing data to disk */
9387   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9388 };
9389
9390 /*
9391 ** An instance of the following structure stores a database schema.
9392 **
9393 ** Most Schema objects are associated with a Btree.  The exception is
9394 ** the Schema for the TEMP databaes (sqlcipher3.aDb[1]) which is free-standing.
9395 ** In shared cache mode, a single Schema object can be shared by multiple
9396 ** Btrees that refer to the same underlying BtShared object.
9397 ** 
9398 ** Schema objects are automatically deallocated when the last Btree that
9399 ** references them is destroyed.   The TEMP Schema is manually freed by
9400 ** sqlcipher3_close().
9401 *
9402 ** A thread must be holding a mutex on the corresponding Btree in order
9403 ** to access Schema content.  This implies that the thread must also be
9404 ** holding a mutex on the sqlcipher3 connection pointer that owns the Btree.
9405 ** For a TEMP Schema, only the connection mutex is required.
9406 */
9407 struct Schema {
9408   int schema_cookie;   /* Database schema version number for this file */
9409   int iGeneration;     /* Generation counter.  Incremented with each change */
9410   Hash tblHash;        /* All tables indexed by name */
9411   Hash idxHash;        /* All (named) indices indexed by name */
9412   Hash trigHash;       /* All triggers indexed by name */
9413   Hash fkeyHash;       /* All foreign keys by referenced table name */
9414   Table *pSeqTab;      /* The sqlcipher_sequence table used by AUTOINCREMENT */
9415   u8 file_format;      /* Schema format version for this file */
9416   u8 enc;              /* Text encoding used by this database */
9417   u16 flags;           /* Flags associated with this schema */
9418   int cache_size;      /* Number of pages to use in the cache */
9419 };
9420
9421 /*
9422 ** These macros can be used to test, set, or clear bits in the 
9423 ** Db.pSchema->flags field.
9424 */
9425 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9426 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9427 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9428 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9429
9430 /*
9431 ** Allowed values for the DB.pSchema->flags field.
9432 **
9433 ** The DB_SchemaLoaded flag is set after the database schema has been
9434 ** read into internal hash tables.
9435 **
9436 ** DB_UnresetViews means that one or more views have column names that
9437 ** have been filled out.  If the schema changes, these column names might
9438 ** changes and so the view will need to be reset.
9439 */
9440 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9441 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9442 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9443
9444 /*
9445 ** The number of different kinds of things that can be limited
9446 ** using the sqlcipher3_limit() interface.
9447 */
9448 #define SQLCIPHER_N_LIMIT (SQLCIPHER_LIMIT_TRIGGER_DEPTH+1)
9449
9450 /*
9451 ** Lookaside malloc is a set of fixed-size buffers that can be used
9452 ** to satisfy small transient memory allocation requests for objects
9453 ** associated with a particular database connection.  The use of
9454 ** lookaside malloc provides a significant performance enhancement
9455 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9456 ** SQL statements.
9457 **
9458 ** The Lookaside structure holds configuration information about the
9459 ** lookaside malloc subsystem.  Each available memory allocation in
9460 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9461 ** objects.
9462 **
9463 ** Lookaside allocations are only allowed for objects that are associated
9464 ** with a particular database connection.  Hence, schema information cannot
9465 ** be stored in lookaside because in shared cache mode the schema information
9466 ** is shared by multiple database connections.  Therefore, while parsing
9467 ** schema information, the Lookaside.bEnabled flag is cleared so that
9468 ** lookaside allocations are not used to construct the schema objects.
9469 */
9470 struct Lookaside {
9471   u16 sz;                 /* Size of each buffer in bytes */
9472   u8 bEnabled;            /* False to disable new lookaside allocations */
9473   u8 bMalloced;           /* True if pStart obtained from sqlcipher3_malloc() */
9474   int nOut;               /* Number of buffers currently checked out */
9475   int mxOut;              /* Highwater mark for nOut */
9476   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9477   LookasideSlot *pFree;   /* List of available buffers */
9478   void *pStart;           /* First byte of available memory space */
9479   void *pEnd;             /* First byte past end of available space */
9480 };
9481 struct LookasideSlot {
9482   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9483 };
9484
9485 /*
9486 ** A hash table for function definitions.
9487 **
9488 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9489 ** Collisions are on the FuncDef.pHash chain.
9490 */
9491 struct FuncDefHash {
9492   FuncDef *a[23];       /* Hash table for functions */
9493 };
9494
9495 /*
9496 ** Each database connection is an instance of the following structure.
9497 **
9498 ** The sqlcipher.lastRowid records the last insert rowid generated by an
9499 ** insert statement.  Inserts on views do not affect its value.  Each
9500 ** trigger has its own context, so that lastRowid can be updated inside
9501 ** triggers as usual.  The previous value will be restored once the trigger
9502 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
9503 ** longer (since after version 2.8.12) reset to -1.
9504 **
9505 ** The sqlcipher.nChange does not count changes within triggers and keeps no
9506 ** context.  It is reset at start of sqlcipher3_exec.
9507 ** The sqlcipher.lsChange represents the number of changes made by the last
9508 ** insert, update, or delete statement.  It remains constant throughout the
9509 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
9510 ** context stack just like lastRowid so that the count of changes
9511 ** within a trigger is not seen outside the trigger.  Changes to views do not
9512 ** affect the value of lsChange.
9513 ** The sqlcipher.csChange keeps track of the number of current changes (since
9514 ** the last statement) and is used to update sqlcipher_lsChange.
9515 **
9516 ** The member variables sqlcipher.errCode, sqlcipher.zErrMsg and sqlcipher.zErrMsg16
9517 ** store the most recent error code and, if applicable, string. The
9518 ** internal function sqlcipher3Error() is used to set these variables
9519 ** consistently.
9520 */
9521 struct sqlcipher3 {
9522   sqlcipher3_vfs *pVfs;            /* OS Interface */
9523   int nDb;                      /* Number of backends currently in use */
9524   Db *aDb;                      /* All backends */
9525   int flags;                    /* Miscellaneous flags. See below */
9526   unsigned int openFlags;       /* Flags passed to sqlcipher3_vfs.xOpen() */
9527   int errCode;                  /* Most recent error code (SQLCIPHER_*) */
9528   int errMask;                  /* & result codes with this before returning */
9529   u8 autoCommit;                /* The auto-commit flag. */
9530   u8 temp_store;                /* 1: file 2: memory 0: default */
9531   u8 mallocFailed;              /* True if we have seen a malloc failure */
9532   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9533   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9534   u8 suppressErr;               /* Do not issue error messages if true */
9535   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
9536   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9537   int nTable;                   /* Number of tables in the database */
9538   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9539   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9540   u32 magic;                    /* Magic number for detect library misuse */
9541   int nChange;                  /* Value returned by sqlcipher3_changes() */
9542   int nTotalChange;             /* Value returned by sqlcipher3_total_changes() */
9543   sqlcipher3_mutex *mutex;         /* Connection mutex */
9544   int aLimit[SQLCIPHER_N_LIMIT];   /* Limits */
9545   struct sqlcipher3InitInfo {      /* Information used during initialization */
9546     int iDb;                    /* When back is being initialized */
9547     int newTnum;                /* Rootpage of table being initialized */
9548     u8 busy;                    /* TRUE if currently initializing */
9549     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9550   } init;
9551   int nExtension;               /* Number of loaded extensions */
9552   void **aExtension;            /* Array of shared library handles */
9553   struct Vdbe *pVdbe;           /* List of active virtual machines */
9554   int activeVdbeCnt;            /* Number of VDBEs currently executing */
9555   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9556   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9557   void (*xTrace)(void*,const char*);        /* Trace function */
9558   void *pTraceArg;                          /* Argument to the trace function */
9559   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9560   void *pProfileArg;                        /* Argument to profile function */
9561   void *pCommitArg;                 /* Argument to xCommitCallback() */   
9562   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9563   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
9564   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9565   void *pUpdateArg;
9566   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlcipher_int64);
9567 #ifndef SQLCIPHER_OMIT_WAL
9568   int (*xWalCallback)(void *, sqlcipher3 *, const char *, int);
9569   void *pWalArg;
9570 #endif
9571   void(*xCollNeeded)(void*,sqlcipher3*,int eTextRep,const char*);
9572   void(*xCollNeeded16)(void*,sqlcipher3*,int eTextRep,const void*);
9573   void *pCollNeededArg;
9574   sqlcipher3_value *pErr;          /* Most recent error message */
9575   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9576   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9577   union {
9578     volatile int isInterrupted; /* True if sqlcipher3_interrupt has been called */
9579     double notUsed1;            /* Spacer */
9580   } u1;
9581   Lookaside lookaside;          /* Lookaside malloc configuration */
9582 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
9583   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9584                                 /* Access authorization function */
9585   void *pAuthArg;               /* 1st argument to the access auth function */
9586 #endif
9587 #ifndef SQLCIPHER_OMIT_PROGRESS_CALLBACK
9588   int (*xProgress)(void *);     /* The progress callback */
9589   void *pProgressArg;           /* Argument to the progress callback */
9590   int nProgressOps;             /* Number of opcodes for progress callback */
9591 #endif
9592 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
9593   Hash aModule;                 /* populated by sqlcipher3_create_module() */
9594   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
9595   VTable **aVTrans;             /* Virtual tables with open transactions */
9596   int nVTrans;                  /* Allocated size of aVTrans */
9597   VTable *pDisconnect;    /* Disconnect these in next sqlcipher3_prepare() */
9598 #endif
9599   FuncDefHash aFunc;            /* Hash table of connection functions */
9600   Hash aCollSeq;                /* All collating sequences */
9601   BusyHandler busyHandler;      /* Busy callback */
9602   int busyTimeout;              /* Busy handler timeout, in msec */
9603   Db aDbStatic[2];              /* Static space for the 2 default backends */
9604   Savepoint *pSavepoint;        /* List of active savepoints */
9605   int nSavepoint;               /* Number of non-transaction savepoints */
9606   int nStatement;               /* Number of nested statement-transactions  */
9607   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9608   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9609   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9610
9611 #ifdef SQLCIPHER_ENABLE_UNLOCK_NOTIFY
9612   /* The following variables are all protected by the STATIC_MASTER 
9613   ** mutex, not by sqlcipher3.mutex. They are used by code in notify.c. 
9614   **
9615   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9616   ** unlock so that it can proceed.
9617   **
9618   ** When X.pBlockingConnection==Y, that means that something that X tried
9619   ** tried to do recently failed with an SQLCIPHER_LOCKED error due to locks
9620   ** held by Y.
9621   */
9622   sqlcipher3 *pBlockingConnection; /* Connection that caused SQLCIPHER_LOCKED */
9623   sqlcipher3 *pUnlockConnection;           /* Connection to watch for unlock */
9624   void *pUnlockArg;                     /* Argument to xUnlockNotify */
9625   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9626   sqlcipher3 *pNextBlocked;        /* Next in list of all blocked connections */
9627 #endif
9628 };
9629
9630 /*
9631 ** A macro to discover the encoding of a database.
9632 */
9633 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9634
9635 /*
9636 ** Possible values for the sqlcipher3.flags.
9637 */
9638 #define SQLCIPHER_VdbeTrace      0x00000100  /* True to trace VDBE execution */
9639 #define SQLCIPHER_InternChanges  0x00000200  /* Uncommitted Hash table changes */
9640 #define SQLCIPHER_FullColNames   0x00000400  /* Show full column names on SELECT */
9641 #define SQLCIPHER_ShortColNames  0x00000800  /* Show short columns names */
9642 #define SQLCIPHER_CountRows      0x00001000  /* Count rows changed by INSERT, */
9643                                           /*   DELETE, or UPDATE and return */
9644                                           /*   the count using a callback. */
9645 #define SQLCIPHER_NullCallback   0x00002000  /* Invoke the callback once if the */
9646                                           /*   result set is empty */
9647 #define SQLCIPHER_SqlTrace       0x00004000  /* Debug print SQL as it executes */
9648 #define SQLCIPHER_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
9649 #define SQLCIPHER_WriteSchema    0x00010000  /* OK to update SQLCIPHER_MASTER */
9650 #define SQLCIPHER_NoReadlock     0x00020000  /* Readlocks are omitted when 
9651                                           ** accessing read-only databases */
9652 #define SQLCIPHER_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
9653 #define SQLCIPHER_ReadUncommitted 0x0080000  /* For shared-cache mode */
9654 #define SQLCIPHER_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
9655 #define SQLCIPHER_FullFSync      0x00200000  /* Use full fsync on the backend */
9656 #define SQLCIPHER_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
9657 #define SQLCIPHER_RecoveryMode   0x00800000  /* Ignore schema errors */
9658 #define SQLCIPHER_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
9659 #define SQLCIPHER_RecTriggers    0x02000000  /* Enable recursive triggers */
9660 #define SQLCIPHER_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
9661 #define SQLCIPHER_AutoIndex      0x08000000  /* Enable automatic indexes */
9662 #define SQLCIPHER_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
9663 #define SQLCIPHER_LoadExtension  0x20000000  /* Enable load_extension */
9664 #define SQLCIPHER_EnableTrigger  0x40000000  /* True to enable triggers */
9665
9666 /*
9667 ** Bits of the sqlcipher3.flags field that are used by the
9668 ** sqlcipher3_test_control(SQLCIPHER_TESTCTRL_OPTIMIZATIONS,...) interface.
9669 ** These must be the low-order bits of the flags field.
9670 */
9671 #define SQLCIPHER_QueryFlattener 0x01        /* Disable query flattening */
9672 #define SQLCIPHER_ColumnCache    0x02        /* Disable the column cache */
9673 #define SQLCIPHER_IndexSort      0x04        /* Disable indexes for sorting */
9674 #define SQLCIPHER_IndexSearch    0x08        /* Disable indexes for searching */
9675 #define SQLCIPHER_IndexCover     0x10        /* Disable index covering table */
9676 #define SQLCIPHER_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9677 #define SQLCIPHER_FactorOutConst 0x40        /* Disable factoring out constants */
9678 #define SQLCIPHER_IdxRealAsInt   0x80        /* Store REAL as INT in indices */
9679 #define SQLCIPHER_DistinctOpt    0x80        /* DISTINCT using indexes */
9680 #define SQLCIPHER_OptMask        0xff        /* Mask of all disablable opts */
9681
9682 /*
9683 ** Possible values for the sqlcipher.magic field.
9684 ** The numbers are obtained at random and have no special meaning, other
9685 ** than being distinct from one another.
9686 */
9687 #define SQLCIPHER_MAGIC_OPEN     0xa029a697  /* Database is open */
9688 #define SQLCIPHER_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9689 #define SQLCIPHER_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9690 #define SQLCIPHER_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9691 #define SQLCIPHER_MAGIC_ERROR    0xb5357930  /* An SQLCIPHER_MISUSE error occurred */
9692
9693 /*
9694 ** Each SQL function is defined by an instance of the following
9695 ** structure.  A pointer to this structure is stored in the sqlcipher.aFunc
9696 ** hash table.  When multiple functions have the same name, the hash table
9697 ** points to a linked list of these structures.
9698 */
9699 struct FuncDef {
9700   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9701   u8 iPrefEnc;         /* Preferred text encoding (SQLCIPHER_UTF8, 16LE, 16BE) */
9702   u8 flags;            /* Some combination of SQLCIPHER_FUNC_* */
9703   void *pUserData;     /* User data parameter */
9704   FuncDef *pNext;      /* Next function with same name */
9705   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**); /* Regular function */
9706   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**); /* Aggregate step */
9707   void (*xFinalize)(sqlcipher3_context*);                /* Aggregate finalizer */
9708   char *zName;         /* SQL name of the function. */
9709   FuncDef *pHash;      /* Next with a different name but the same hash */
9710   FuncDestructor *pDestructor;   /* Reference counted destructor function */
9711 };
9712
9713 /*
9714 ** This structure encapsulates a user-function destructor callback (as
9715 ** configured using create_function_v2()) and a reference counter. When
9716 ** create_function_v2() is called to create a function with a destructor,
9717 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
9718 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9719 ** or not the specified encoding is SQLCIPHER_ANY). The FuncDef.pDestructor
9720 ** member of each of the new FuncDef objects is set to point to the allocated
9721 ** FuncDestructor.
9722 **
9723 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9724 ** count on this object is decremented. When it reaches 0, the destructor
9725 ** is invoked and the FuncDestructor structure freed.
9726 */
9727 struct FuncDestructor {
9728   int nRef;
9729   void (*xDestroy)(void *);
9730   void *pUserData;
9731 };
9732
9733 /*
9734 ** Possible values for FuncDef.flags
9735 */
9736 #define SQLCIPHER_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9737 #define SQLCIPHER_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9738 #define SQLCIPHER_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
9739 #define SQLCIPHER_FUNC_NEEDCOLL 0x08 /* sqlcipher3GetFuncCollSeq() might be called */
9740 #define SQLCIPHER_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
9741 #define SQLCIPHER_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
9742 #define SQLCIPHER_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9743
9744 /*
9745 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9746 ** used to create the initializers for the FuncDef structures.
9747 **
9748 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9749 **     Used to create a scalar function definition of a function zName 
9750 **     implemented by C function xFunc that accepts nArg arguments. The
9751 **     value passed as iArg is cast to a (void*) and made available
9752 **     as the user-data (sqlcipher3_user_data()) for the function. If 
9753 **     argument bNC is true, then the SQLCIPHER_FUNC_NEEDCOLL flag is set.
9754 **
9755 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9756 **     Used to create an aggregate function definition implemented by
9757 **     the C functions xStep and xFinal. The first four parameters
9758 **     are interpreted in the same way as the first 4 parameters to
9759 **     FUNCTION().
9760 **
9761 **   LIKEFUNC(zName, nArg, pArg, flags)
9762 **     Used to create a scalar function definition of a function zName 
9763 **     that accepts nArg arguments and is implemented by a call to C 
9764 **     function likeFunc. Argument pArg is cast to a (void *) and made
9765 **     available as the function user-data (sqlcipher3_user_data()). The
9766 **     FuncDef.flags variable is set to the value passed as the flags
9767 **     parameter.
9768 */
9769 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9770   {nArg, SQLCIPHER_UTF8, bNC*SQLCIPHER_FUNC_NEEDCOLL, \
9771    SQLCIPHER_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9772 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9773   {nArg, SQLCIPHER_UTF8, bNC*SQLCIPHER_FUNC_NEEDCOLL, \
9774    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9775 #define LIKEFUNC(zName, nArg, arg, flags) \
9776   {nArg, SQLCIPHER_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9777 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9778   {nArg, SQLCIPHER_UTF8, nc*SQLCIPHER_FUNC_NEEDCOLL, \
9779    SQLCIPHER_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9780
9781 /*
9782 ** All current savepoints are stored in a linked list starting at
9783 ** sqlcipher3.pSavepoint. The first element in the list is the most recently
9784 ** opened savepoint. Savepoints are added to the list by the vdbe
9785 ** OP_Savepoint instruction.
9786 */
9787 struct Savepoint {
9788   char *zName;                        /* Savepoint name (nul-terminated) */
9789   i64 nDeferredCons;                  /* Number of deferred fk violations */
9790   Savepoint *pNext;                   /* Parent savepoint (if any) */
9791 };
9792
9793 /*
9794 ** The following are used as the second parameter to sqlcipher3Savepoint(),
9795 ** and as the P1 argument to the OP_Savepoint instruction.
9796 */
9797 #define SAVEPOINT_BEGIN      0
9798 #define SAVEPOINT_RELEASE    1
9799 #define SAVEPOINT_ROLLBACK   2
9800
9801
9802 /*
9803 ** Each SQLite module (virtual table definition) is defined by an
9804 ** instance of the following structure, stored in the sqlcipher3.aModule
9805 ** hash table.
9806 */
9807 struct Module {
9808   const sqlcipher3_module *pModule;       /* Callback pointers */
9809   const char *zName;                   /* Name passed to create_module() */
9810   void *pAux;                          /* pAux passed to create_module() */
9811   void (*xDestroy)(void *);            /* Module destructor function */
9812 };
9813
9814 /*
9815 ** information about each column of an SQL table is held in an instance
9816 ** of this structure.
9817 */
9818 struct Column {
9819   char *zName;     /* Name of this column */
9820   Expr *pDflt;     /* Default value of this column */
9821   char *zDflt;     /* Original text of the default value */
9822   char *zType;     /* Data type for this column */
9823   char *zColl;     /* Collating sequence.  If NULL, use the default */
9824   u8 notNull;      /* True if there is a NOT NULL constraint */
9825   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9826   char affinity;   /* One of the SQLCIPHER_AFF_... values */
9827 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
9828   u8 isHidden;     /* True if this column is 'hidden' */
9829 #endif
9830 };
9831
9832 /*
9833 ** A "Collating Sequence" is defined by an instance of the following
9834 ** structure. Conceptually, a collating sequence consists of a name and
9835 ** a comparison routine that defines the order of that sequence.
9836 **
9837 ** There may two separate implementations of the collation function, one
9838 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9839 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9840 ** native byte order. When a collation sequence is invoked, SQLite selects
9841 ** the version that will require the least expensive encoding
9842 ** translations, if any.
9843 **
9844 ** The CollSeq.pUser member variable is an extra parameter that passed in
9845 ** as the first argument to the UTF-8 comparison function, xCmp.
9846 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9847 ** xCmp16.
9848 **
9849 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9850 ** collating sequence is undefined.  Indices built on an undefined
9851 ** collating sequence may not be read or written.
9852 */
9853 struct CollSeq {
9854   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9855   u8 enc;               /* Text encoding handled by xCmp() */
9856   u8 type;              /* One of the SQLCIPHER_COLL_... values below */
9857   void *pUser;          /* First argument to xCmp() */
9858   int (*xCmp)(void*,int, const void*, int, const void*);
9859   void (*xDel)(void*);  /* Destructor for pUser */
9860 };
9861
9862 /*
9863 ** Allowed values of CollSeq.type:
9864 */
9865 #define SQLCIPHER_COLL_BINARY  1  /* The default memcmp() collating sequence */
9866 #define SQLCIPHER_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9867 #define SQLCIPHER_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9868 #define SQLCIPHER_COLL_USER    0  /* Any other user-defined collating sequence */
9869
9870 /*
9871 ** A sort order can be either ASC or DESC.
9872 */
9873 #define SQLCIPHER_SO_ASC       0  /* Sort in ascending order */
9874 #define SQLCIPHER_SO_DESC      1  /* Sort in ascending order */
9875
9876 /*
9877 ** Column affinity types.
9878 **
9879 ** These used to have mnemonic name like 'i' for SQLCIPHER_AFF_INTEGER and
9880 ** 't' for SQLCIPHER_AFF_TEXT.  But we can save a little space and improve
9881 ** the speed a little by numbering the values consecutively.  
9882 **
9883 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
9884 ** when multiple affinity types are concatenated into a string and
9885 ** used as the P4 operand, they will be more readable.
9886 **
9887 ** Note also that the numeric types are grouped together so that testing
9888 ** for a numeric type is a single comparison.
9889 */
9890 #define SQLCIPHER_AFF_TEXT     'a'
9891 #define SQLCIPHER_AFF_NONE     'b'
9892 #define SQLCIPHER_AFF_NUMERIC  'c'
9893 #define SQLCIPHER_AFF_INTEGER  'd'
9894 #define SQLCIPHER_AFF_REAL     'e'
9895
9896 #define sqlcipher3IsNumericAffinity(X)  ((X)>=SQLCIPHER_AFF_NUMERIC)
9897
9898 /*
9899 ** The SQLCIPHER_AFF_MASK values masks off the significant bits of an
9900 ** affinity value. 
9901 */
9902 #define SQLCIPHER_AFF_MASK     0x67
9903
9904 /*
9905 ** Additional bit values that can be ORed with an affinity without
9906 ** changing the affinity.
9907 */
9908 #define SQLCIPHER_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9909 #define SQLCIPHER_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9910 #define SQLCIPHER_NULLEQ       0x80  /* NULL=NULL */
9911
9912 /*
9913 ** An object of this type is created for each virtual table present in
9914 ** the database schema. 
9915 **
9916 ** If the database schema is shared, then there is one instance of this
9917 ** structure for each database connection (sqlcipher3*) that uses the shared
9918 ** schema. This is because each database connection requires its own unique
9919 ** instance of the sqlcipher3_vtab* handle used to access the virtual table 
9920 ** implementation. sqlcipher3_vtab* handles can not be shared between 
9921 ** database connections, even when the rest of the in-memory database 
9922 ** schema is shared, as the implementation often stores the database
9923 ** connection handle passed to it via the xConnect() or xCreate() method
9924 ** during initialization internally. This database connection handle may
9925 ** then be used by the virtual table implementation to access real tables 
9926 ** within the database. So that they appear as part of the callers 
9927 ** transaction, these accesses need to be made via the same database 
9928 ** connection as that used to execute SQL operations on the virtual table.
9929 **
9930 ** All VTable objects that correspond to a single table in a shared
9931 ** database schema are initially stored in a linked-list pointed to by
9932 ** the Table.pVTable member variable of the corresponding Table object.
9933 ** When an sqlcipher3_prepare() operation is required to access the virtual
9934 ** table, it searches the list for the VTable that corresponds to the
9935 ** database connection doing the preparing so as to use the correct
9936 ** sqlcipher3_vtab* handle in the compiled query.
9937 **
9938 ** When an in-memory Table object is deleted (for example when the
9939 ** schema is being reloaded for some reason), the VTable objects are not 
9940 ** deleted and the sqlcipher3_vtab* handles are not xDisconnect()ed 
9941 ** immediately. Instead, they are moved from the Table.pVTable list to
9942 ** another linked list headed by the sqlcipher3.pDisconnect member of the
9943 ** corresponding sqlcipher3 structure. They are then deleted/xDisconnected 
9944 ** next time a statement is prepared using said sqlcipher3*. This is done
9945 ** to avoid deadlock issues involving multiple sqlcipher3.mutex mutexes.
9946 ** Refer to comments above function sqlcipher3VtabUnlockList() for an
9947 ** explanation as to why it is safe to add an entry to an sqlcipher3.pDisconnect
9948 ** list without holding the corresponding sqlcipher3.mutex mutex.
9949 **
9950 ** The memory for objects of this type is always allocated by 
9951 ** sqlcipher3DbMalloc(), using the connection handle stored in VTable.db as 
9952 ** the first argument.
9953 */
9954 struct VTable {
9955   sqlcipher3 *db;              /* Database connection associated with this table */
9956   Module *pMod;             /* Pointer to module implementation */
9957   sqlcipher3_vtab *pVtab;      /* Pointer to vtab instance */
9958   int nRef;                 /* Number of pointers to this structure */
9959   u8 bConstraint;           /* True if constraints are supported */
9960   int iSavepoint;           /* Depth of the SAVEPOINT stack */
9961   VTable *pNext;            /* Next in linked list (see above) */
9962 };
9963
9964 /*
9965 ** Each SQL table is represented in memory by an instance of the
9966 ** following structure.
9967 **
9968 ** Table.zName is the name of the table.  The case of the original
9969 ** CREATE TABLE statement is stored, but case is not significant for
9970 ** comparisons.
9971 **
9972 ** Table.nCol is the number of columns in this table.  Table.aCol is a
9973 ** pointer to an array of Column structures, one for each column.
9974 **
9975 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9976 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9977 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9978 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9979 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9980 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9981 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9982 **
9983 ** Table.tnum is the page number for the root BTree page of the table in the
9984 ** database file.  If Table.iDb is the index of the database table backend
9985 ** in sqlcipher.aDb[].  0 is for the main database and 1 is for the file that
9986 ** holds temporary tables and indices.  If TF_Ephemeral is set
9987 ** then the table is stored in a file that is automatically deleted
9988 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9989 ** refers VDBE cursor number that holds the table open, not to the root
9990 ** page number.  Transient tables are used to hold the results of a
9991 ** sub-query that appears instead of a real table name in the FROM clause 
9992 ** of a SELECT statement.
9993 */
9994 struct Table {
9995   char *zName;         /* Name of the table or view */
9996   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9997   int nCol;            /* Number of columns in this table */
9998   Column *aCol;        /* Information about each column */
9999   Index *pIndex;       /* List of SQL indexes on this table. */
10000   int tnum;            /* Root BTree node for this table (see note above) */
10001   tRowcnt nRowEst;     /* Estimated rows in table - from sqlcipher_stat1 table */
10002   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
10003   u16 nRef;            /* Number of pointers to this Table */
10004   u8 tabFlags;         /* Mask of TF_* values */
10005   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
10006   FKey *pFKey;         /* Linked list of all foreign keys in this table */
10007   char *zColAff;       /* String defining the affinity of each column */
10008 #ifndef SQLCIPHER_OMIT_CHECK
10009   Expr *pCheck;        /* The AND of all CHECK constraints */
10010 #endif
10011 #ifndef SQLCIPHER_OMIT_ALTERTABLE
10012   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
10013 #endif
10014 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
10015   VTable *pVTable;     /* List of VTable objects. */
10016   int nModuleArg;      /* Number of arguments to the module */
10017   char **azModuleArg;  /* Text of all module args. [0] is module name */
10018 #endif
10019   Trigger *pTrigger;   /* List of triggers stored in pSchema */
10020   Schema *pSchema;     /* Schema that contains this table */
10021   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
10022 };
10023
10024 /*
10025 ** Allowed values for Tabe.tabFlags.
10026 */
10027 #define TF_Readonly        0x01    /* Read-only system table */
10028 #define TF_Ephemeral       0x02    /* An ephemeral table */
10029 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
10030 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
10031 #define TF_Virtual         0x10    /* Is a virtual table */
10032 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
10033
10034
10035
10036 /*
10037 ** Test to see whether or not a table is a virtual table.  This is
10038 ** done as a macro so that it will be optimized out when virtual
10039 ** table support is omitted from the build.
10040 */
10041 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
10042 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
10043 #  define IsHiddenColumn(X) ((X)->isHidden)
10044 #else
10045 #  define IsVirtual(X)      0
10046 #  define IsHiddenColumn(X) 0
10047 #endif
10048
10049 /*
10050 ** Each foreign key constraint is an instance of the following structure.
10051 **
10052 ** A foreign key is associated with two tables.  The "from" table is
10053 ** the table that contains the REFERENCES clause that creates the foreign
10054 ** key.  The "to" table is the table that is named in the REFERENCES clause.
10055 ** Consider this example:
10056 **
10057 **     CREATE TABLE ex1(
10058 **       a INTEGER PRIMARY KEY,
10059 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10060 **     );
10061 **
10062 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10063 **
10064 ** Each REFERENCES clause generates an instance of the following structure
10065 ** which is attached to the from-table.  The to-table need not exist when
10066 ** the from-table is created.  The existence of the to-table is not checked.
10067 */
10068 struct FKey {
10069   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
10070   FKey *pNextFrom;  /* Next foreign key in pFrom */
10071   char *zTo;        /* Name of table that the key points to (aka: Parent) */
10072   FKey *pNextTo;    /* Next foreign key on table named zTo */
10073   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
10074   int nCol;         /* Number of columns in this key */
10075   /* EV: R-30323-21917 */
10076   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
10077   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
10078   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
10079   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
10080     int iFrom;         /* Index of column in pFrom */
10081     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
10082   } aCol[1];        /* One entry for each of nCol column s */
10083 };
10084
10085 /*
10086 ** SQLite supports many different ways to resolve a constraint
10087 ** error.  ROLLBACK processing means that a constraint violation
10088 ** causes the operation in process to fail and for the current transaction
10089 ** to be rolled back.  ABORT processing means the operation in process
10090 ** fails and any prior changes from that one operation are backed out,
10091 ** but the transaction is not rolled back.  FAIL processing means that
10092 ** the operation in progress stops and returns an error code.  But prior
10093 ** changes due to the same operation are not backed out and no rollback
10094 ** occurs.  IGNORE means that the particular row that caused the constraint
10095 ** error is not inserted or updated.  Processing continues and no error
10096 ** is returned.  REPLACE means that preexisting database rows that caused
10097 ** a UNIQUE constraint violation are removed so that the new insert or
10098 ** update can proceed.  Processing continues and no error is reported.
10099 **
10100 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10101 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10102 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
10103 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
10104 ** referenced table row is propagated into the row that holds the
10105 ** foreign key.
10106 ** 
10107 ** The following symbolic values are used to record which type
10108 ** of action to take.
10109 */
10110 #define OE_None     0   /* There is no constraint to check */
10111 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
10112 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
10113 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
10114 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
10115 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
10116
10117 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10118 #define OE_SetNull  7   /* Set the foreign key value to NULL */
10119 #define OE_SetDflt  8   /* Set the foreign key value to its default */
10120 #define OE_Cascade  9   /* Cascade the changes */
10121
10122 #define OE_Default  99  /* Do whatever the default action is */
10123
10124
10125 /*
10126 ** An instance of the following structure is passed as the first
10127 ** argument to sqlcipher3VdbeKeyCompare and is used to control the 
10128 ** comparison of the two index keys.
10129 */
10130 struct KeyInfo {
10131   sqlcipher3 *db;        /* The database connection */
10132   u8 enc;             /* Text encoding - one of the SQLCIPHER_UTF* values */
10133   u16 nField;         /* Number of entries in aColl[] */
10134   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
10135   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10136 };
10137
10138 /*
10139 ** An instance of the following structure holds information about a
10140 ** single index record that has already been parsed out into individual
10141 ** values.
10142 **
10143 ** A record is an object that contains one or more fields of data.
10144 ** Records are used to store the content of a table row and to store
10145 ** the key of an index.  A blob encoding of a record is created by
10146 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10147 ** OP_Column opcode.
10148 **
10149 ** This structure holds a record that has already been disassembled
10150 ** into its constituent fields.
10151 */
10152 struct UnpackedRecord {
10153   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10154   u16 nField;         /* Number of entries in apMem[] */
10155   u16 flags;          /* Boolean settings.  UNPACKED_... below */
10156   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
10157   Mem *aMem;          /* Values */
10158 };
10159
10160 /*
10161 ** Allowed values of UnpackedRecord.flags
10162 */
10163 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlcipher3Malloc() */
10164 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
10165 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
10166 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
10167 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
10168 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
10169
10170 /*
10171 ** Each SQL index is represented in memory by an
10172 ** instance of the following structure.
10173 **
10174 ** The columns of the table that are to be indexed are described
10175 ** by the aiColumn[] field of this structure.  For example, suppose
10176 ** we have the following table and index:
10177 **
10178 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10179 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
10180 **
10181 ** In the Table structure describing Ex1, nCol==3 because there are
10182 ** three columns in the table.  In the Index structure describing
10183 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10184 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
10185 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10186 ** The second column to be indexed (c1) has an index of 0 in
10187 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10188 **
10189 ** The Index.onError field determines whether or not the indexed columns
10190 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
10191 ** it means this is not a unique index.  Otherwise it is a unique index
10192 ** and the value of Index.onError indicate the which conflict resolution 
10193 ** algorithm to employ whenever an attempt is made to insert a non-unique
10194 ** element.
10195 */
10196 struct Index {
10197   char *zName;     /* Name of this index */
10198   int nColumn;     /* Number of columns in the table used by this index */
10199   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
10200   tRowcnt *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
10201   Table *pTable;   /* The SQL table being indexed */
10202   int tnum;        /* Page containing root of this index in database file */
10203   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10204   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
10205   u8 bUnordered;   /* Use this index for == or IN queries only */
10206   char *zColAff;   /* String defining the affinity of each column */
10207   Index *pNext;    /* The next index associated with the same table */
10208   Schema *pSchema; /* Schema containing this index */
10209   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
10210   char **azColl;   /* Array of collation sequence names for index */
10211 #ifdef SQLCIPHER_ENABLE_STAT3
10212   int nSample;             /* Number of elements in aSample[] */
10213   tRowcnt avgEq;           /* Average nEq value for key values not in aSample */
10214   IndexSample *aSample;    /* Samples of the left-most key */
10215 #endif
10216 };
10217
10218 /*
10219 ** Each sample stored in the sqlcipher_stat3 table is represented in memory 
10220 ** using a structure of this type.  See documentation at the top of the
10221 ** analyze.c source file for additional information.
10222 */
10223 struct IndexSample {
10224   union {
10225     char *z;        /* Value if eType is SQLCIPHER_TEXT or SQLCIPHER_BLOB */
10226     double r;       /* Value if eType is SQLCIPHER_FLOAT */
10227     i64 i;          /* Value if eType is SQLCIPHER_INTEGER */
10228   } u;
10229   u8 eType;         /* SQLCIPHER_NULL, SQLCIPHER_INTEGER ... etc. */
10230   int nByte;        /* Size in byte of text or blob. */
10231   tRowcnt nEq;      /* Est. number of rows where the key equals this sample */
10232   tRowcnt nLt;      /* Est. number of rows where key is less than this sample */
10233   tRowcnt nDLt;     /* Est. number of distinct keys less than this sample */
10234 };
10235
10236 /*
10237 ** Each token coming out of the lexer is an instance of
10238 ** this structure.  Tokens are also used as part of an expression.
10239 **
10240 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10241 ** may contain random values.  Do not make any assumptions about Token.dyn
10242 ** and Token.n when Token.z==0.
10243 */
10244 struct Token {
10245   const char *z;     /* Text of the token.  Not NULL-terminated! */
10246   unsigned int n;    /* Number of characters in this token */
10247 };
10248
10249 /*
10250 ** An instance of this structure contains information needed to generate
10251 ** code for a SELECT that contains aggregate functions.
10252 **
10253 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10254 ** pointer to this structure.  The Expr.iColumn field is the index in
10255 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10256 ** code for that node.
10257 **
10258 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10259 ** original Select structure that describes the SELECT statement.  These
10260 ** fields do not need to be freed when deallocating the AggInfo structure.
10261 */
10262 struct AggInfo {
10263   u8 directMode;          /* Direct rendering mode means take data directly
10264                           ** from source tables rather than from accumulators */
10265   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10266                           ** than the source table */
10267   int sortingIdx;         /* Cursor number of the sorting index */
10268   int sortingIdxPTab;     /* Cursor number of pseudo-table */
10269   ExprList *pGroupBy;     /* The group by clause */
10270   int nSortingColumn;     /* Number of columns in the sorting index */
10271   struct AggInfo_col {    /* For each column used in source tables */
10272     Table *pTab;             /* Source table */
10273     int iTable;              /* Cursor number of the source table */
10274     int iColumn;             /* Column number within the source table */
10275     int iSorterColumn;       /* Column number in the sorting index */
10276     int iMem;                /* Memory location that acts as accumulator */
10277     Expr *pExpr;             /* The original expression */
10278   } *aCol;
10279   int nColumn;            /* Number of used entries in aCol[] */
10280   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
10281   int nAccumulator;       /* Number of columns that show through to the output.
10282                           ** Additional columns are used only as parameters to
10283                           ** aggregate functions */
10284   struct AggInfo_func {   /* For each aggregate function */
10285     Expr *pExpr;             /* Expression encoding the function */
10286     FuncDef *pFunc;          /* The aggregate function implementation */
10287     int iMem;                /* Memory location that acts as accumulator */
10288     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10289   } *aFunc;
10290   int nFunc;              /* Number of entries in aFunc[] */
10291   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
10292 };
10293
10294 /*
10295 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10296 ** Usually it is 16-bits.  But if SQLCIPHER_MAX_VARIABLE_NUMBER is greater
10297 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
10298 ** it uses less memory in the Expr object, which is a big memory user
10299 ** in systems with lots of prepared statements.  And few applications
10300 ** need more than about 10 or 20 variables.  But some extreme users want
10301 ** to have prepared statements with over 32767 variables, and for them
10302 ** the option is available (at compile-time).
10303 */
10304 #if SQLCIPHER_MAX_VARIABLE_NUMBER<=32767
10305 typedef i16 ynVar;
10306 #else
10307 typedef int ynVar;
10308 #endif
10309
10310 /*
10311 ** Each node of an expression in the parse tree is an instance
10312 ** of this structure.
10313 **
10314 ** Expr.op is the opcode. The integer parser token codes are reused
10315 ** as opcodes here. For example, the parser defines TK_GE to be an integer
10316 ** code representing the ">=" operator. This same integer code is reused
10317 ** to represent the greater-than-or-equal-to operator in the expression
10318 ** tree.
10319 **
10320 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
10321 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10322 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
10323 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10324 ** then Expr.token contains the name of the function.
10325 **
10326 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10327 ** binary operator. Either or both may be NULL.
10328 **
10329 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
10330 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10331 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10332 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10333 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
10334 ** valid.
10335 **
10336 ** An expression of the form ID or ID.ID refers to a column in a table.
10337 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10338 ** the integer cursor number of a VDBE cursor pointing to that table and
10339 ** Expr.iColumn is the column number for the specific column.  If the
10340 ** expression is used as a result in an aggregate SELECT, then the
10341 ** value is also stored in the Expr.iAgg column in the aggregate so that
10342 ** it can be accessed after all aggregates are computed.
10343 **
10344 ** If the expression is an unbound variable marker (a question mark 
10345 ** character '?' in the original SQL) then the Expr.iTable holds the index 
10346 ** number for that variable.
10347 **
10348 ** If the expression is a subquery then Expr.iColumn holds an integer
10349 ** register number containing the result of the subquery.  If the
10350 ** subquery gives a constant result, then iTable is -1.  If the subquery
10351 ** gives a different answer at different times during statement processing
10352 ** then iTable is the address of a subroutine that computes the subquery.
10353 **
10354 ** If the Expr is of type OP_Column, and the table it is selecting from
10355 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
10356 ** corresponding table definition.
10357 **
10358 ** ALLOCATION NOTES:
10359 **
10360 ** Expr objects can use a lot of memory space in database schema.  To
10361 ** help reduce memory requirements, sometimes an Expr object will be
10362 ** truncated.  And to reduce the number of memory allocations, sometimes
10363 ** two or more Expr objects will be stored in a single memory allocation,
10364 ** together with Expr.zToken strings.
10365 **
10366 ** If the EP_Reduced and EP_TokenOnly flags are set when
10367 ** an Expr object is truncated.  When EP_Reduced is set, then all
10368 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10369 ** are contained within the same memory allocation.  Note, however, that
10370 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10371 ** allocated, regardless of whether or not EP_Reduced is set.
10372 */
10373 struct Expr {
10374   u8 op;                 /* Operation performed by this node */
10375   char affinity;         /* The affinity of the column or 0 if not a column */
10376   u16 flags;             /* Various flags.  EP_* See below */
10377   union {
10378     char *zToken;          /* Token value. Zero terminated and dequoted */
10379     int iValue;            /* Non-negative integer value if EP_IntValue */
10380   } u;
10381
10382   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10383   ** space is allocated for the fields below this point. An attempt to
10384   ** access them will result in a segfault or malfunction. 
10385   *********************************************************************/
10386
10387   Expr *pLeft;           /* Left subnode */
10388   Expr *pRight;          /* Right subnode */
10389   union {
10390     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10391     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10392   } x;
10393   CollSeq *pColl;        /* The collation type of the column or 0 */
10394
10395   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10396   ** space is allocated for the fields below this point. An attempt to
10397   ** access them will result in a segfault or malfunction.
10398   *********************************************************************/
10399
10400   int iTable;            /* TK_COLUMN: cursor number of table holding column
10401                          ** TK_REGISTER: register number
10402                          ** TK_TRIGGER: 1 -> new, 0 -> old */
10403   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10404                          ** TK_VARIABLE: variable number (always >= 1). */
10405   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10406   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10407   u8 flags2;             /* Second set of flags.  EP2_... */
10408   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
10409   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10410   Table *pTab;           /* Table for TK_COLUMN expressions. */
10411 #if SQLCIPHER_MAX_EXPR_DEPTH>0
10412   int nHeight;           /* Height of the tree headed by this node */
10413 #endif
10414 };
10415
10416 /*
10417 ** The following are the meanings of bits in the Expr.flags field.
10418 */
10419 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10420 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10421 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10422 #define EP_Error      0x0008  /* Expression contains one or more errors */
10423 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10424 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10425 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10426 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10427 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
10428 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
10429 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10430 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10431
10432 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10433 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10434 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
10435
10436 /*
10437 ** The following are the meanings of bits in the Expr.flags2 field.
10438 */
10439 #define EP2_MallocedToken  0x0001  /* Need to sqlcipher3DbFree() Expr.zToken */
10440 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10441
10442 /*
10443 ** The pseudo-routine sqlcipher3ExprSetIrreducible sets the EP2_Irreducible
10444 ** flag on an expression structure.  This flag is used for VV&A only.  The
10445 ** routine is implemented as a macro that only works when in debugging mode,
10446 ** so as not to burden production code.
10447 */
10448 #ifdef SQLCIPHER_DEBUG
10449 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10450 #else
10451 # define ExprSetIrreducible(X)
10452 #endif
10453
10454 /*
10455 ** These macros can be used to test, set, or clear bits in the 
10456 ** Expr.flags field.
10457 */
10458 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10459 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10460 #define ExprSetProperty(E,P)     (E)->flags|=(P)
10461 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
10462
10463 /*
10464 ** Macros to determine the number of bytes required by a normal Expr 
10465 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
10466 ** and an Expr struct with the EP_TokenOnly flag set.
10467 */
10468 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10469 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10470 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10471
10472 /*
10473 ** Flags passed to the sqlcipher3ExprDup() function. See the header comment 
10474 ** above sqlcipher3ExprDup() for details.
10475 */
10476 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10477
10478 /*
10479 ** A list of expressions.  Each expression may optionally have a
10480 ** name.  An expr/name combination can be used in several ways, such
10481 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10482 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
10483 ** also be used as the argument to a function, in which case the a.zName
10484 ** field is not used.
10485 */
10486 struct ExprList {
10487   int nExpr;             /* Number of expressions on the list */
10488   int nAlloc;            /* Number of entries allocated below */
10489   int iECursor;          /* VDBE Cursor associated with this ExprList */
10490   struct ExprList_item {
10491     Expr *pExpr;           /* The list of expressions */
10492     char *zName;           /* Token associated with this expression */
10493     char *zSpan;           /* Original text of the expression */
10494     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
10495     u8 done;               /* A flag to indicate when processing is finished */
10496     u16 iCol;              /* For ORDER BY, column number in result set */
10497     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
10498   } *a;                  /* One entry for each expression */
10499 };
10500
10501 /*
10502 ** An instance of this structure is used by the parser to record both
10503 ** the parse tree for an expression and the span of input text for an
10504 ** expression.
10505 */
10506 struct ExprSpan {
10507   Expr *pExpr;          /* The expression parse tree */
10508   const char *zStart;   /* First character of input text */
10509   const char *zEnd;     /* One character past the end of input text */
10510 };
10511
10512 /*
10513 ** An instance of this structure can hold a simple list of identifiers,
10514 ** such as the list "a,b,c" in the following statements:
10515 **
10516 **      INSERT INTO t(a,b,c) VALUES ...;
10517 **      CREATE INDEX idx ON t(a,b,c);
10518 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10519 **
10520 ** The IdList.a.idx field is used when the IdList represents the list of
10521 ** column names after a table name in an INSERT statement.  In the statement
10522 **
10523 **     INSERT INTO t(a,b,c) ...
10524 **
10525 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10526 */
10527 struct IdList {
10528   struct IdList_item {
10529     char *zName;      /* Name of the identifier */
10530     int idx;          /* Index in some Table.aCol[] of a column named zName */
10531   } *a;
10532   int nId;         /* Number of identifiers on the list */
10533   int nAlloc;      /* Number of entries allocated for a[] below */
10534 };
10535
10536 /*
10537 ** The bitmask datatype defined below is used for various optimizations.
10538 **
10539 ** Changing this from a 64-bit to a 32-bit type limits the number of
10540 ** tables in a join to 32 instead of 64.  But it also reduces the size
10541 ** of the library by 738 bytes on ix86.
10542 */
10543 typedef u64 Bitmask;
10544
10545 /*
10546 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10547 */
10548 #define BMS  ((int)(sizeof(Bitmask)*8))
10549
10550 /*
10551 ** The following structure describes the FROM clause of a SELECT statement.
10552 ** Each table or subquery in the FROM clause is a separate element of
10553 ** the SrcList.a[] array.
10554 **
10555 ** With the addition of multiple database support, the following structure
10556 ** can also be used to describe a particular table such as the table that
10557 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10558 ** such a table must be a simple name: ID.  But in SQLite, the table can
10559 ** now be identified by a database name, a dot, then the table name: ID.ID.
10560 **
10561 ** The jointype starts out showing the join type between the current table
10562 ** and the next table on the list.  The parser builds the list this way.
10563 ** But sqlcipher3SrcListShiftJoinType() later shifts the jointypes so that each
10564 ** jointype expresses the join between the table and the previous table.
10565 **
10566 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10567 ** contains more than 63 columns and the 64-th or later column is used.
10568 */
10569 struct SrcList {
10570   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10571   i16 nAlloc;      /* Number of entries allocated in a[] below */
10572   struct SrcList_item {
10573     char *zDatabase;  /* Name of database holding this table */
10574     char *zName;      /* Name of the table */
10575     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10576     Table *pTab;      /* An SQL table corresponding to zName */
10577     Select *pSelect;  /* A SELECT statement used in place of a table name */
10578     int addrFillSub;  /* Address of subroutine to manifest a subquery */
10579     int regReturn;    /* Register holding return address of addrFillSub */
10580     u8 jointype;      /* Type of join between this able and the previous */
10581     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
10582     u8 isCorrelated;  /* True if sub-query is correlated */
10583 #ifndef SQLCIPHER_OMIT_EXPLAIN
10584     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10585 #endif
10586     int iCursor;      /* The VDBE cursor number used to access this table */
10587     Expr *pOn;        /* The ON clause of a join */
10588     IdList *pUsing;   /* The USING clause of a join */
10589     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10590     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10591     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10592   } a[1];             /* One entry for each identifier on the list */
10593 };
10594
10595 /*
10596 ** Permitted values of the SrcList.a.jointype field
10597 */
10598 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
10599 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10600 #define JT_NATURAL   0x0004    /* True for a "natural" join */
10601 #define JT_LEFT      0x0008    /* Left outer join */
10602 #define JT_RIGHT     0x0010    /* Right outer join */
10603 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10604 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
10605
10606
10607 /*
10608 ** A WherePlan object holds information that describes a lookup
10609 ** strategy.
10610 **
10611 ** This object is intended to be opaque outside of the where.c module.
10612 ** It is included here only so that that compiler will know how big it
10613 ** is.  None of the fields in this object should be used outside of
10614 ** the where.c module.
10615 **
10616 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10617 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10618 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10619 ** case that more than one of these conditions is true.
10620 */
10621 struct WherePlan {
10622   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10623   u32 nEq;                       /* Number of == constraints */
10624   double nRow;                   /* Estimated number of rows (for EQP) */
10625   union {
10626     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10627     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10628     sqlcipher3_index_info *pVtabIdx;  /* Virtual table index to use */
10629   } u;
10630 };
10631
10632 /*
10633 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10634 ** structure contains a single instance of this structure.  This structure
10635 ** is intended to be private the the where.c module and should not be
10636 ** access or modified by other modules.
10637 **
10638 ** The pIdxInfo field is used to help pick the best index on a
10639 ** virtual table.  The pIdxInfo pointer contains indexing
10640 ** information for the i-th table in the FROM clause before reordering.
10641 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10642 ** All other information in the i-th WhereLevel object for the i-th table
10643 ** after FROM clause ordering.
10644 */
10645 struct WhereLevel {
10646   WherePlan plan;       /* query plan for this element of the FROM clause */
10647   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10648   int iTabCur;          /* The VDBE cursor used to access the table */
10649   int iIdxCur;          /* The VDBE cursor used to access pIdx */
10650   int addrBrk;          /* Jump here to break out of the loop */
10651   int addrNxt;          /* Jump here to start the next IN combination */
10652   int addrCont;         /* Jump here to continue with the next loop cycle */
10653   int addrFirst;        /* First instruction of interior of the loop */
10654   u8 iFrom;             /* Which entry in the FROM clause */
10655   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10656   int p1, p2;           /* Operands of the opcode used to ends the loop */
10657   union {               /* Information that depends on plan.wsFlags */
10658     struct {
10659       int nIn;              /* Number of entries in aInLoop[] */
10660       struct InLoop {
10661         int iCur;              /* The VDBE cursor used by this IN operator */
10662         int addrInTop;         /* Top of the IN loop */
10663       } *aInLoop;           /* Information about each nested IN operator */
10664     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10665   } u;
10666
10667   /* The following field is really not part of the current level.  But
10668   ** we need a place to cache virtual table index information for each
10669   ** virtual table in the FROM clause and the WhereLevel structure is
10670   ** a convenient place since there is one WhereLevel for each FROM clause
10671   ** element.
10672   */
10673   sqlcipher3_index_info *pIdxInfo;  /* Index info for n-th source table */
10674 };
10675
10676 /*
10677 ** Flags appropriate for the wctrlFlags parameter of sqlcipher3WhereBegin()
10678 ** and the WhereInfo.wctrlFlags member.
10679 */
10680 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10681 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10682 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10683 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10684 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
10685 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
10686 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
10687 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
10688 #define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
10689
10690 /*
10691 ** The WHERE clause processing routine has two halves.  The
10692 ** first part does the start of the WHERE loop and the second
10693 ** half does the tail of the WHERE loop.  An instance of
10694 ** this structure is returned by the first half and passed
10695 ** into the second half to give some continuity.
10696 */
10697 struct WhereInfo {
10698   Parse *pParse;       /* Parsing and code generating context */
10699   u16 wctrlFlags;      /* Flags originally passed to sqlcipher3WhereBegin() */
10700   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10701   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10702   u8 eDistinct;
10703   SrcList *pTabList;             /* List of tables in the join */
10704   int iTop;                      /* The very beginning of the WHERE loop */
10705   int iContinue;                 /* Jump here to continue with next record */
10706   int iBreak;                    /* Jump here to break out of the loop */
10707   int nLevel;                    /* Number of nested loop */
10708   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10709   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10710   double nRowOut;                /* Estimated number of output rows */
10711   WhereLevel a[1];               /* Information about each nest loop in WHERE */
10712 };
10713
10714 #define WHERE_DISTINCT_UNIQUE 1
10715 #define WHERE_DISTINCT_ORDERED 2
10716
10717 /*
10718 ** A NameContext defines a context in which to resolve table and column
10719 ** names.  The context consists of a list of tables (the pSrcList) field and
10720 ** a list of named expression (pEList).  The named expression list may
10721 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10722 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10723 ** pEList corresponds to the result set of a SELECT and is NULL for
10724 ** other statements.
10725 **
10726 ** NameContexts can be nested.  When resolving names, the inner-most 
10727 ** context is searched first.  If no match is found, the next outer
10728 ** context is checked.  If there is still no match, the next context
10729 ** is checked.  This process continues until either a match is found
10730 ** or all contexts are check.  When a match is found, the nRef member of
10731 ** the context containing the match is incremented. 
10732 **
10733 ** Each subquery gets a new NameContext.  The pNext field points to the
10734 ** NameContext in the parent query.  Thus the process of scanning the
10735 ** NameContext list corresponds to searching through successively outer
10736 ** subqueries looking for a match.
10737 */
10738 struct NameContext {
10739   Parse *pParse;       /* The parser */
10740   SrcList *pSrcList;   /* One or more tables used to resolve names */
10741   ExprList *pEList;    /* Optional list of named expressions */
10742   int nRef;            /* Number of names resolved by this context */
10743   int nErr;            /* Number of errors encountered while resolving names */
10744   u8 allowAgg;         /* Aggregate functions allowed here */
10745   u8 hasAgg;           /* True if aggregates are seen */
10746   u8 isCheck;          /* True if resolving names in a CHECK constraint */
10747   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10748   AggInfo *pAggInfo;   /* Information about aggregates at this level */
10749   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10750 };
10751
10752 /*
10753 ** An instance of the following structure contains all information
10754 ** needed to generate code for a single SELECT statement.
10755 **
10756 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10757 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10758 ** limit and nOffset to the value of the offset (or 0 if there is not
10759 ** offset).  But later on, nLimit and nOffset become the memory locations
10760 ** in the VDBE that record the limit and offset counters.
10761 **
10762 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10763 ** These addresses must be stored so that we can go back and fill in
10764 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10765 ** the number of columns in P2 can be computed at the same time
10766 ** as the OP_OpenEphm instruction is coded because not
10767 ** enough information about the compound query is known at that point.
10768 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10769 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10770 ** sequences for the ORDER BY clause.
10771 */
10772 struct Select {
10773   ExprList *pEList;      /* The fields of the result */
10774   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10775   char affinity;         /* MakeRecord with this affinity for SRT_Set */
10776   u16 selFlags;          /* Various SF_* values */
10777   SrcList *pSrc;         /* The FROM clause */
10778   Expr *pWhere;          /* The WHERE clause */
10779   ExprList *pGroupBy;    /* The GROUP BY clause */
10780   Expr *pHaving;         /* The HAVING clause */
10781   ExprList *pOrderBy;    /* The ORDER BY clause */
10782   Select *pPrior;        /* Prior select in a compound select statement */
10783   Select *pNext;         /* Next select to the left in a compound */
10784   Select *pRightmost;    /* Right-most select in a compound select statement */
10785   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10786   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10787   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10788   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10789   double nSelectRow;     /* Estimated number of result rows */
10790 };
10791
10792 /*
10793 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
10794 ** "Select Flag".
10795 */
10796 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
10797 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
10798 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
10799 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
10800 #define SF_Expanded        0x0010  /* sqlcipher3SelectExpand() called on this */
10801 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
10802 #define SF_UseSorter       0x0040  /* Sort using a sorter */
10803
10804
10805 /*
10806 ** The results of a select can be distributed in several ways.  The
10807 ** "SRT" prefix means "SELECT Result Type".
10808 */
10809 #define SRT_Union        1  /* Store result as keys in an index */
10810 #define SRT_Except       2  /* Remove result from a UNION index */
10811 #define SRT_Exists       3  /* Store 1 if the result is not empty */
10812 #define SRT_Discard      4  /* Do not save the results anywhere */
10813
10814 /* The ORDER BY clause is ignored for all of the above */
10815 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10816
10817 #define SRT_Output       5  /* Output each row of result */
10818 #define SRT_Mem          6  /* Store result in a memory cell */
10819 #define SRT_Set          7  /* Store results as keys in an index */
10820 #define SRT_Table        8  /* Store result as data with an automatic rowid */
10821 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10822 #define SRT_Coroutine   10  /* Generate a single row of result */
10823
10824 /*
10825 ** A structure used to customize the behavior of sqlcipher3Select(). See
10826 ** comments above sqlcipher3Select() for details.
10827 */
10828 typedef struct SelectDest SelectDest;
10829 struct SelectDest {
10830   u8 eDest;         /* How to dispose of the results */
10831   u8 affinity;      /* Affinity used when eDest==SRT_Set */
10832   int iParm;        /* A parameter used by the eDest disposal method */
10833   int iMem;         /* Base register where results are written */
10834   int nMem;         /* Number of registers allocated */
10835 };
10836
10837 /*
10838 ** During code generation of statements that do inserts into AUTOINCREMENT 
10839 ** tables, the following information is attached to the Table.u.autoInc.p
10840 ** pointer of each autoincrement table to record some side information that
10841 ** the code generator needs.  We have to keep per-table autoincrement
10842 ** information in case inserts are down within triggers.  Triggers do not
10843 ** normally coordinate their activities, but we do need to coordinate the
10844 ** loading and saving of autoincrement information.
10845 */
10846 struct AutoincInfo {
10847   AutoincInfo *pNext;   /* Next info block in a list of them all */
10848   Table *pTab;          /* Table this info block refers to */
10849   int iDb;              /* Index in sqlcipher3.aDb[] of database holding pTab */
10850   int regCtr;           /* Memory register holding the rowid counter */
10851 };
10852
10853 /*
10854 ** Size of the column cache
10855 */
10856 #ifndef SQLCIPHER_N_COLCACHE
10857 # define SQLCIPHER_N_COLCACHE 10
10858 #endif
10859
10860 /*
10861 ** At least one instance of the following structure is created for each 
10862 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
10863 ** statement. All such objects are stored in the linked list headed at
10864 ** Parse.pTriggerPrg and deleted once statement compilation has been
10865 ** completed.
10866 **
10867 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
10868 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
10869 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
10870 ** The Parse.pTriggerPrg list never contains two entries with the same
10871 ** values for both pTrigger and orconf.
10872 **
10873 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
10874 ** accessed (or set to 0 for triggers fired as a result of INSERT 
10875 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
10876 ** a mask of new.* columns used by the program.
10877 */
10878 struct TriggerPrg {
10879   Trigger *pTrigger;      /* Trigger this program was coded from */
10880   int orconf;             /* Default ON CONFLICT policy */
10881   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
10882   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
10883   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
10884 };
10885
10886 /*
10887 ** The yDbMask datatype for the bitmask of all attached databases.
10888 */
10889 #if SQLCIPHER_MAX_ATTACHED>30
10890   typedef sqlcipher3_uint64 yDbMask;
10891 #else
10892   typedef unsigned int yDbMask;
10893 #endif
10894
10895 /*
10896 ** An SQL parser context.  A copy of this structure is passed through
10897 ** the parser and down into all the parser action routine in order to
10898 ** carry around information that is global to the entire parse.
10899 **
10900 ** The structure is divided into two parts.  When the parser and code
10901 ** generate call themselves recursively, the first part of the structure
10902 ** is constant but the second part is reset at the beginning and end of
10903 ** each recursion.
10904 **
10905 ** The nTableLock and aTableLock variables are only used if the shared-cache 
10906 ** feature is enabled (if sqlcipher3Tsd()->useSharedData is true). They are
10907 ** used to store the set of table-locks required by the statement being
10908 ** compiled. Function sqlcipher3TableLock() is used to add entries to the
10909 ** list.
10910 */
10911 struct Parse {
10912   sqlcipher3 *db;         /* The main database structure */
10913   int rc;              /* Return code from execution */
10914   char *zErrMsg;       /* An error message */
10915   Vdbe *pVdbe;         /* An engine for executing database bytecode */
10916   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
10917   u8 nameClash;        /* A permanent table name clashes with temp table name */
10918   u8 checkSchema;      /* Causes schema cookie check after an error */
10919   u8 nested;           /* Number of nested calls to the parser/code generator */
10920   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
10921   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
10922   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
10923   int aTempReg[8];     /* Holding area for temporary registers */
10924   int nRangeReg;       /* Size of the temporary register block */
10925   int iRangeReg;       /* First register in temporary register block */
10926   int nErr;            /* Number of errors seen */
10927   int nTab;            /* Number of previously allocated VDBE cursors */
10928   int nMem;            /* Number of memory cells used so far */
10929   int nSet;            /* Number of sets used so far */
10930   int ckBase;          /* Base register of data during check constraints */
10931   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
10932   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
10933   u8 nColCache;        /* Number of entries in the column cache */
10934   u8 iColCache;        /* Next entry of the cache to replace */
10935   struct yColCache {
10936     int iTable;           /* Table cursor number */
10937     int iColumn;          /* Table column number */
10938     u8 tempReg;           /* iReg is a temp register that needs to be freed */
10939     int iLevel;           /* Nesting level */
10940     int iReg;             /* Reg with value of this column. 0 means none. */
10941     int lru;              /* Least recently used entry has the smallest value */
10942   } aColCache[SQLCIPHER_N_COLCACHE];  /* One for each column cache entry */
10943   yDbMask writeMask;   /* Start a write transaction on these databases */
10944   yDbMask cookieMask;  /* Bitmask of schema verified databases */
10945   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
10946   u8 mayAbort;         /* True if statement may throw an ABORT exception */
10947   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
10948   int cookieValue[SQLCIPHER_MAX_ATTACHED+2];  /* Values of cookies to verify */
10949 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
10950   int nTableLock;        /* Number of locks in aTableLock */
10951   TableLock *aTableLock; /* Required table locks for shared-cache mode */
10952 #endif
10953   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
10954   int regRoot;         /* Register holding root page number for new objects */
10955   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
10956   int nMaxArg;         /* Max args passed to user function by sub-program */
10957
10958   /* Information used while coding trigger programs. */
10959   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
10960   Table *pTriggerTab;  /* Table triggers are being coded for */
10961   u32 oldmask;         /* Mask of old.* columns referenced */
10962   u32 newmask;         /* Mask of new.* columns referenced */
10963   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
10964   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
10965   u8 disableTriggers;  /* True to disable triggers */
10966   double nQueryLoop;   /* Estimated number of iterations of a query */
10967
10968   /* Above is constant between recursions.  Below is reset before and after
10969   ** each recursion */
10970
10971   int nVar;            /* Number of '?' variables seen in the SQL so far */
10972   int nzVar;           /* Number of available slots in azVar[] */
10973   char **azVar;        /* Pointers to names of parameters */
10974   Vdbe *pReprepare;    /* VM being reprepared (sqlcipher3Reprepare()) */
10975   int nAlias;          /* Number of aliased result set columns */
10976   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
10977   int *aAlias;         /* Register used to hold aliased result */
10978   u8 explain;          /* True if the EXPLAIN flag is found on the query */
10979   Token sNameToken;    /* Token with unqualified schema object name */
10980   Token sLastToken;    /* The last token parsed */
10981   const char *zTail;   /* All SQL text past the last semicolon parsed */
10982   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10983   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10984   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10985 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
10986   Token sArg;                /* Complete text of a module argument */
10987   u8 declareVtab;            /* True if inside sqlcipher3_declare_vtab() */
10988   int nVtabLock;             /* Number of virtual tables to lock */
10989   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10990 #endif
10991   int nHeight;            /* Expression tree height of current sub-select */
10992   Table *pZombieTab;      /* List of Table objects to delete after code gen */
10993   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
10994
10995 #ifndef SQLCIPHER_OMIT_EXPLAIN
10996   int iSelectId;
10997   int iNextSelectId;
10998 #endif
10999 };
11000
11001 #ifdef SQLCIPHER_OMIT_VIRTUALTABLE
11002   #define IN_DECLARE_VTAB 0
11003 #else
11004   #define IN_DECLARE_VTAB (pParse->declareVtab)
11005 #endif
11006
11007 /*
11008 ** An instance of the following structure can be declared on a stack and used
11009 ** to save the Parse.zAuthContext value so that it can be restored later.
11010 */
11011 struct AuthContext {
11012   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
11013   Parse *pParse;              /* The Parse structure */
11014 };
11015
11016 /*
11017 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
11018 */
11019 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
11020 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
11021 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
11022 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
11023 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
11024 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
11025
11026 /*
11027  * Each trigger present in the database schema is stored as an instance of
11028  * struct Trigger. 
11029  *
11030  * Pointers to instances of struct Trigger are stored in two ways.
11031  * 1. In the "trigHash" hash table (part of the sqlcipher3* that represents the 
11032  *    database). This allows Trigger structures to be retrieved by name.
11033  * 2. All triggers associated with a single table form a linked list, using the
11034  *    pNext member of struct Trigger. A pointer to the first element of the
11035  *    linked list is stored as the "pTrigger" member of the associated
11036  *    struct Table.
11037  *
11038  * The "step_list" member points to the first element of a linked list
11039  * containing the SQL statements specified as the trigger program.
11040  */
11041 struct Trigger {
11042   char *zName;            /* The name of the trigger                        */
11043   char *table;            /* The table or view to which the trigger applies */
11044   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
11045   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11046   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
11047   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
11048                              the <column-list> is stored here */
11049   Schema *pSchema;        /* Schema containing the trigger */
11050   Schema *pTabSchema;     /* Schema containing the table */
11051   TriggerStep *step_list; /* Link list of trigger program steps             */
11052   Trigger *pNext;         /* Next trigger associated with the table */
11053 };
11054
11055 /*
11056 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
11057 ** determine which. 
11058 **
11059 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
11060 ** In that cases, the constants below can be ORed together.
11061 */
11062 #define TRIGGER_BEFORE  1
11063 #define TRIGGER_AFTER   2
11064
11065 /*
11066  * An instance of struct TriggerStep is used to store a single SQL statement
11067  * that is a part of a trigger-program. 
11068  *
11069  * Instances of struct TriggerStep are stored in a singly linked list (linked
11070  * using the "pNext" member) referenced by the "step_list" member of the 
11071  * associated struct Trigger instance. The first element of the linked list is
11072  * the first step of the trigger-program.
11073  * 
11074  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11075  * "SELECT" statement. The meanings of the other members is determined by the 
11076  * value of "op" as follows:
11077  *
11078  * (op == TK_INSERT)
11079  * orconf    -> stores the ON CONFLICT algorithm
11080  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
11081  *              this stores a pointer to the SELECT statement. Otherwise NULL.
11082  * target    -> A token holding the quoted name of the table to insert into.
11083  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11084  *              this stores values to be inserted. Otherwise NULL.
11085  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
11086  *              statement, then this stores the column-names to be
11087  *              inserted into.
11088  *
11089  * (op == TK_DELETE)
11090  * target    -> A token holding the quoted name of the table to delete from.
11091  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
11092  *              Otherwise NULL.
11093  * 
11094  * (op == TK_UPDATE)
11095  * target    -> A token holding the quoted name of the table to update rows of.
11096  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
11097  *              Otherwise NULL.
11098  * pExprList -> A list of the columns to update and the expressions to update
11099  *              them to. See sqlcipher3Update() documentation of "pChanges"
11100  *              argument.
11101  * 
11102  */
11103 struct TriggerStep {
11104   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11105   u8 orconf;           /* OE_Rollback etc. */
11106   Trigger *pTrig;      /* The trigger that this step is a part of */
11107   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11108   Token target;        /* Target table for DELETE, UPDATE, INSERT */
11109   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
11110   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
11111   IdList *pIdList;     /* Column names for INSERT */
11112   TriggerStep *pNext;  /* Next in the link-list */
11113   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
11114 };
11115
11116 /*
11117 ** The following structure contains information used by the sqlcipherFix...
11118 ** routines as they walk the parse tree to make database references
11119 ** explicit.  
11120 */
11121 typedef struct DbFixer DbFixer;
11122 struct DbFixer {
11123   Parse *pParse;      /* The parsing context.  Error messages written here */
11124   const char *zDb;    /* Make sure all objects are contained in this database */
11125   const char *zType;  /* Type of the container - used for error messages */
11126   const Token *pName; /* Name of the container - used for error messages */
11127 };
11128
11129 /*
11130 ** An objected used to accumulate the text of a string where we
11131 ** do not necessarily know how big the string will be in the end.
11132 */
11133 struct StrAccum {
11134   sqlcipher3 *db;         /* Optional database for lookaside.  Can be NULL */
11135   char *zBase;         /* A base allocation.  Not from malloc. */
11136   char *zText;         /* The string collected so far */
11137   int  nChar;          /* Length of the string so far */
11138   int  nAlloc;         /* Amount of space allocated in zText */
11139   int  mxAlloc;        /* Maximum allowed string length */
11140   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
11141   u8   useMalloc;      /* 0: none,  1: sqlcipher3DbMalloc,  2: sqlcipher3_malloc */
11142   u8   tooBig;         /* Becomes true if string size exceeds limits */
11143 };
11144
11145 /*
11146 ** A pointer to this structure is used to communicate information
11147 ** from sqlcipher3Init and OP_ParseSchema into the sqlcipher3InitCallback.
11148 */
11149 typedef struct {
11150   sqlcipher3 *db;        /* The database being initialized */
11151   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11152   char **pzErrMsg;    /* Error message stored here */
11153   int rc;             /* Result code stored here */
11154 } InitData;
11155
11156 /*
11157 ** Structure containing global configuration data for the SQLite library.
11158 **
11159 ** This structure also contains some state information.
11160 */
11161 struct Sqlite3Config {
11162   int bMemstat;                     /* True to enable memory status */
11163   int bCoreMutex;                   /* True to enable core mutexing */
11164   int bFullMutex;                   /* True to enable full mutexing */
11165   int bOpenUri;                     /* True to interpret filenames as URIs */
11166   int mxStrlen;                     /* Maximum string length */
11167   int szLookaside;                  /* Default lookaside buffer size */
11168   int nLookaside;                   /* Default lookaside buffer count */
11169   sqlcipher3_mem_methods m;            /* Low-level memory allocation interface */
11170   sqlcipher3_mutex_methods mutex;      /* Low-level mutex interface */
11171   sqlcipher3_pcache_methods pcache;    /* Low-level page-cache interface */
11172   void *pHeap;                      /* Heap storage space */
11173   int nHeap;                        /* Size of pHeap[] */
11174   int mnReq, mxReq;                 /* Min and max heap requests sizes */
11175   void *pScratch;                   /* Scratch memory */
11176   int szScratch;                    /* Size of each scratch buffer */
11177   int nScratch;                     /* Number of scratch buffers */
11178   void *pPage;                      /* Page cache memory */
11179   int szPage;                       /* Size of each page in pPage[] */
11180   int nPage;                        /* Number of pages in pPage[] */
11181   int mxParserStack;                /* maximum depth of the parser stack */
11182   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11183   /* The above might be initialized to non-zero.  The following need to always
11184   ** initially be zero, however. */
11185   int isInit;                       /* True after initialization has finished */
11186   int inProgress;                   /* True while initialization in progress */
11187   int isMutexInit;                  /* True after mutexes are initialized */
11188   int isMallocInit;                 /* True after malloc is initialized */
11189   int isPCacheInit;                 /* True after malloc is initialized */
11190   sqlcipher3_mutex *pInitMutex;        /* Mutex used by sqlcipher3_initialize() */
11191   int nRefInitMutex;                /* Number of users of pInitMutex */
11192   void (*xLog)(void*,int,const char*); /* Function for logging */
11193   void *pLogArg;                       /* First argument to xLog() */
11194   int bLocaltimeFault;              /* True to fail localtime() calls */
11195 };
11196
11197 /*
11198 ** Context pointer passed down through the tree-walk.
11199 */
11200 struct Walker {
11201   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11202   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11203   Parse *pParse;                            /* Parser context.  */
11204   union {                                   /* Extra data for callback */
11205     NameContext *pNC;                          /* Naming context */
11206     int i;                                     /* Integer value */
11207   } u;
11208 };
11209
11210 /* Forward declarations */
11211 SQLCIPHER_PRIVATE int sqlcipher3WalkExpr(Walker*, Expr*);
11212 SQLCIPHER_PRIVATE int sqlcipher3WalkExprList(Walker*, ExprList*);
11213 SQLCIPHER_PRIVATE int sqlcipher3WalkSelect(Walker*, Select*);
11214 SQLCIPHER_PRIVATE int sqlcipher3WalkSelectExpr(Walker*, Select*);
11215 SQLCIPHER_PRIVATE int sqlcipher3WalkSelectFrom(Walker*, Select*);
11216
11217 /*
11218 ** Return code from the parse-tree walking primitives and their
11219 ** callbacks.
11220 */
11221 #define WRC_Continue    0   /* Continue down into children */
11222 #define WRC_Prune       1   /* Omit children but continue walking siblings */
11223 #define WRC_Abort       2   /* Abandon the tree walk */
11224
11225 /*
11226 ** Assuming zIn points to the first byte of a UTF-8 character,
11227 ** advance zIn to point to the first byte of the next UTF-8 character.
11228 */
11229 #define SQLCIPHER_SKIP_UTF8(zIn) {                        \
11230   if( (*(zIn++))>=0xc0 ){                              \
11231     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11232   }                                                    \
11233 }
11234
11235 /*
11236 ** The SQLCIPHER_*_BKPT macros are substitutes for the error codes with
11237 ** the same name but without the _BKPT suffix.  These macros invoke
11238 ** routines that report the line-number on which the error originated
11239 ** using sqlcipher3_log().  The routines also provide a convenient place
11240 ** to set a debugger breakpoint.
11241 */
11242 SQLCIPHER_PRIVATE int sqlcipher3CorruptError(int);
11243 SQLCIPHER_PRIVATE int sqlcipher3MisuseError(int);
11244 SQLCIPHER_PRIVATE int sqlcipher3CantopenError(int);
11245 #define SQLCIPHER_CORRUPT_BKPT sqlcipher3CorruptError(__LINE__)
11246 #define SQLCIPHER_MISUSE_BKPT sqlcipher3MisuseError(__LINE__)
11247 #define SQLCIPHER_CANTOPEN_BKPT sqlcipher3CantopenError(__LINE__)
11248
11249
11250 /*
11251 ** FTS4 is really an extension for FTS3.  It is enabled using the
11252 ** SQLCIPHER_ENABLE_FTS3 macro.  But to avoid confusion we also all
11253 ** the SQLCIPHER_ENABLE_FTS4 macro to serve as an alisse for SQLCIPHER_ENABLE_FTS3.
11254 */
11255 #if defined(SQLCIPHER_ENABLE_FTS4) && !defined(SQLCIPHER_ENABLE_FTS3)
11256 # define SQLCIPHER_ENABLE_FTS3
11257 #endif
11258
11259 /*
11260 ** The ctype.h header is needed for non-ASCII systems.  It is also
11261 ** needed by FTS3 when FTS3 is included in the amalgamation.
11262 */
11263 #if !defined(SQLCIPHER_ASCII) || \
11264     (defined(SQLCIPHER_ENABLE_FTS3) && defined(SQLCIPHER_AMALGAMATION))
11265 # include <ctype.h>
11266 #endif
11267
11268 /*
11269 ** The following macros mimic the standard library functions toupper(),
11270 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11271 ** sqlcipher versions only work for ASCII characters, regardless of locale.
11272 */
11273 #ifdef SQLCIPHER_ASCII
11274 # define sqlcipher3Toupper(x)  ((x)&~(sqlcipher3CtypeMap[(unsigned char)(x)]&0x20))
11275 # define sqlcipher3Isspace(x)   (sqlcipher3CtypeMap[(unsigned char)(x)]&0x01)
11276 # define sqlcipher3Isalnum(x)   (sqlcipher3CtypeMap[(unsigned char)(x)]&0x06)
11277 # define sqlcipher3Isalpha(x)   (sqlcipher3CtypeMap[(unsigned char)(x)]&0x02)
11278 # define sqlcipher3Isdigit(x)   (sqlcipher3CtypeMap[(unsigned char)(x)]&0x04)
11279 # define sqlcipher3Isxdigit(x)  (sqlcipher3CtypeMap[(unsigned char)(x)]&0x08)
11280 # define sqlcipher3Tolower(x)   (sqlcipher3UpperToLower[(unsigned char)(x)])
11281 #else
11282 # define sqlcipher3Toupper(x)   toupper((unsigned char)(x))
11283 # define sqlcipher3Isspace(x)   isspace((unsigned char)(x))
11284 # define sqlcipher3Isalnum(x)   isalnum((unsigned char)(x))
11285 # define sqlcipher3Isalpha(x)   isalpha((unsigned char)(x))
11286 # define sqlcipher3Isdigit(x)   isdigit((unsigned char)(x))
11287 # define sqlcipher3Isxdigit(x)  isxdigit((unsigned char)(x))
11288 # define sqlcipher3Tolower(x)   tolower((unsigned char)(x))
11289 #endif
11290
11291 /*
11292 ** Internal function prototypes
11293 */
11294 SQLCIPHER_PRIVATE int sqlcipher3StrICmp(const char *, const char *);
11295 SQLCIPHER_PRIVATE int sqlcipher3Strlen30(const char*);
11296 #define sqlcipher3StrNICmp sqlcipher3_strnicmp
11297
11298 SQLCIPHER_PRIVATE int sqlcipher3MallocInit(void);
11299 SQLCIPHER_PRIVATE void sqlcipher3MallocEnd(void);
11300 SQLCIPHER_PRIVATE void *sqlcipher3Malloc(int);
11301 SQLCIPHER_PRIVATE void *sqlcipher3MallocZero(int);
11302 SQLCIPHER_PRIVATE void *sqlcipher3DbMallocZero(sqlcipher3*, int);
11303 SQLCIPHER_PRIVATE void *sqlcipher3DbMallocRaw(sqlcipher3*, int);
11304 SQLCIPHER_PRIVATE char *sqlcipher3DbStrDup(sqlcipher3*,const char*);
11305 SQLCIPHER_PRIVATE char *sqlcipher3DbStrNDup(sqlcipher3*,const char*, int);
11306 SQLCIPHER_PRIVATE void *sqlcipher3Realloc(void*, int);
11307 SQLCIPHER_PRIVATE void *sqlcipher3DbReallocOrFree(sqlcipher3 *, void *, int);
11308 SQLCIPHER_PRIVATE void *sqlcipher3DbRealloc(sqlcipher3 *, void *, int);
11309 SQLCIPHER_PRIVATE void sqlcipher3DbFree(sqlcipher3*, void*);
11310 SQLCIPHER_PRIVATE int sqlcipher3MallocSize(void*);
11311 SQLCIPHER_PRIVATE int sqlcipher3DbMallocSize(sqlcipher3*, void*);
11312 SQLCIPHER_PRIVATE void *sqlcipher3ScratchMalloc(int);
11313 SQLCIPHER_PRIVATE void sqlcipher3ScratchFree(void*);
11314 SQLCIPHER_PRIVATE void *sqlcipher3PageMalloc(int);
11315 SQLCIPHER_PRIVATE void sqlcipher3PageFree(void*);
11316 SQLCIPHER_PRIVATE void sqlcipher3MemSetDefault(void);
11317 SQLCIPHER_PRIVATE void sqlcipher3BenignMallocHooks(void (*)(void), void (*)(void));
11318 SQLCIPHER_PRIVATE int sqlcipher3HeapNearlyFull(void);
11319
11320 /*
11321 ** On systems with ample stack space and that support alloca(), make
11322 ** use of alloca() to obtain space for large automatic objects.  By default,
11323 ** obtain space from malloc().
11324 **
11325 ** The alloca() routine never returns NULL.  This will cause code paths
11326 ** that deal with sqlcipher3StackAlloc() failures to be unreachable.
11327 */
11328 #ifdef SQLCIPHER_USE_ALLOCA
11329 # define sqlcipher3StackAllocRaw(D,N)   alloca(N)
11330 # define sqlcipher3StackAllocZero(D,N)  memset(alloca(N), 0, N)
11331 # define sqlcipher3StackFree(D,P)       
11332 #else
11333 # define sqlcipher3StackAllocRaw(D,N)   sqlcipher3DbMallocRaw(D,N)
11334 # define sqlcipher3StackAllocZero(D,N)  sqlcipher3DbMallocZero(D,N)
11335 # define sqlcipher3StackFree(D,P)       sqlcipher3DbFree(D,P)
11336 #endif
11337
11338 #ifdef SQLCIPHER_ENABLE_MEMSYS3
11339 SQLCIPHER_PRIVATE const sqlcipher3_mem_methods *sqlcipher3MemGetMemsys3(void);
11340 #endif
11341 #ifdef SQLCIPHER_ENABLE_MEMSYS5
11342 SQLCIPHER_PRIVATE const sqlcipher3_mem_methods *sqlcipher3MemGetMemsys5(void);
11343 #endif
11344
11345
11346 #ifndef SQLCIPHER_MUTEX_OMIT
11347 SQLCIPHER_PRIVATE   sqlcipher3_mutex_methods const *sqlcipher3DefaultMutex(void);
11348 SQLCIPHER_PRIVATE   sqlcipher3_mutex_methods const *sqlcipher3NoopMutex(void);
11349 SQLCIPHER_PRIVATE   sqlcipher3_mutex *sqlcipher3MutexAlloc(int);
11350 SQLCIPHER_PRIVATE   int sqlcipher3MutexInit(void);
11351 SQLCIPHER_PRIVATE   int sqlcipher3MutexEnd(void);
11352 #endif
11353
11354 SQLCIPHER_PRIVATE int sqlcipher3StatusValue(int);
11355 SQLCIPHER_PRIVATE void sqlcipher3StatusAdd(int, int);
11356 SQLCIPHER_PRIVATE void sqlcipher3StatusSet(int, int);
11357
11358 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
11359 SQLCIPHER_PRIVATE   int sqlcipher3IsNaN(double);
11360 #else
11361 # define sqlcipher3IsNaN(X)  0
11362 #endif
11363
11364 SQLCIPHER_PRIVATE void sqlcipher3VXPrintf(StrAccum*, int, const char*, va_list);
11365 #ifndef SQLCIPHER_OMIT_TRACE
11366 SQLCIPHER_PRIVATE void sqlcipher3XPrintf(StrAccum*, const char*, ...);
11367 #endif
11368 SQLCIPHER_PRIVATE char *sqlcipher3MPrintf(sqlcipher3*,const char*, ...);
11369 SQLCIPHER_PRIVATE char *sqlcipher3VMPrintf(sqlcipher3*,const char*, va_list);
11370 SQLCIPHER_PRIVATE char *sqlcipher3MAppendf(sqlcipher3*,char*,const char*,...);
11371 #if defined(SQLCIPHER_TEST) || defined(SQLCIPHER_DEBUG)
11372 SQLCIPHER_PRIVATE   void sqlcipher3DebugPrintf(const char*, ...);
11373 #endif
11374 #if defined(SQLCIPHER_TEST)
11375 SQLCIPHER_PRIVATE   void *sqlcipher3TestTextToPtr(const char*);
11376 #endif
11377 SQLCIPHER_PRIVATE void sqlcipher3SetString(char **, sqlcipher3*, const char*, ...);
11378 SQLCIPHER_PRIVATE void sqlcipher3ErrorMsg(Parse*, const char*, ...);
11379 SQLCIPHER_PRIVATE int sqlcipher3Dequote(char*);
11380 SQLCIPHER_PRIVATE int sqlcipher3KeywordCode(const unsigned char*, int);
11381 SQLCIPHER_PRIVATE int sqlcipher3RunParser(Parse*, const char*, char **);
11382 SQLCIPHER_PRIVATE void sqlcipher3FinishCoding(Parse*);
11383 SQLCIPHER_PRIVATE int sqlcipher3GetTempReg(Parse*);
11384 SQLCIPHER_PRIVATE void sqlcipher3ReleaseTempReg(Parse*,int);
11385 SQLCIPHER_PRIVATE int sqlcipher3GetTempRange(Parse*,int);
11386 SQLCIPHER_PRIVATE void sqlcipher3ReleaseTempRange(Parse*,int,int);
11387 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprAlloc(sqlcipher3*,int,const Token*,int);
11388 SQLCIPHER_PRIVATE Expr *sqlcipher3Expr(sqlcipher3*,int,const char*);
11389 SQLCIPHER_PRIVATE void sqlcipher3ExprAttachSubtrees(sqlcipher3*,Expr*,Expr*,Expr*);
11390 SQLCIPHER_PRIVATE Expr *sqlcipher3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11391 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprAnd(sqlcipher3*,Expr*, Expr*);
11392 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprFunction(Parse*,ExprList*, Token*);
11393 SQLCIPHER_PRIVATE void sqlcipher3ExprAssignVarNumber(Parse*, Expr*);
11394 SQLCIPHER_PRIVATE void sqlcipher3ExprDelete(sqlcipher3*, Expr*);
11395 SQLCIPHER_PRIVATE ExprList *sqlcipher3ExprListAppend(Parse*,ExprList*,Expr*);
11396 SQLCIPHER_PRIVATE void sqlcipher3ExprListSetName(Parse*,ExprList*,Token*,int);
11397 SQLCIPHER_PRIVATE void sqlcipher3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11398 SQLCIPHER_PRIVATE void sqlcipher3ExprListDelete(sqlcipher3*, ExprList*);
11399 SQLCIPHER_PRIVATE int sqlcipher3Init(sqlcipher3*, char**);
11400 SQLCIPHER_PRIVATE int sqlcipher3InitCallback(void*, int, char**, char**);
11401 SQLCIPHER_PRIVATE void sqlcipher3Pragma(Parse*,Token*,Token*,Token*,int);
11402 SQLCIPHER_PRIVATE void sqlcipher3ResetInternalSchema(sqlcipher3*, int);
11403 SQLCIPHER_PRIVATE void sqlcipher3BeginParse(Parse*,int);
11404 SQLCIPHER_PRIVATE void sqlcipher3CommitInternalChanges(sqlcipher3*);
11405 SQLCIPHER_PRIVATE Table *sqlcipher3ResultSetOfSelect(Parse*,Select*);
11406 SQLCIPHER_PRIVATE void sqlcipher3OpenMasterTable(Parse *, int);
11407 SQLCIPHER_PRIVATE void sqlcipher3StartTable(Parse*,Token*,Token*,int,int,int,int);
11408 SQLCIPHER_PRIVATE void sqlcipher3AddColumn(Parse*,Token*);
11409 SQLCIPHER_PRIVATE void sqlcipher3AddNotNull(Parse*, int);
11410 SQLCIPHER_PRIVATE void sqlcipher3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11411 SQLCIPHER_PRIVATE void sqlcipher3AddCheckConstraint(Parse*, Expr*);
11412 SQLCIPHER_PRIVATE void sqlcipher3AddColumnType(Parse*,Token*);
11413 SQLCIPHER_PRIVATE void sqlcipher3AddDefaultValue(Parse*,ExprSpan*);
11414 SQLCIPHER_PRIVATE void sqlcipher3AddCollateType(Parse*, Token*);
11415 SQLCIPHER_PRIVATE void sqlcipher3EndTable(Parse*,Token*,Token*,Select*);
11416 SQLCIPHER_PRIVATE int sqlcipher3ParseUri(const char*,const char*,unsigned int*,
11417                     sqlcipher3_vfs**,char**,char **);
11418
11419 SQLCIPHER_PRIVATE Bitvec *sqlcipher3BitvecCreate(u32);
11420 SQLCIPHER_PRIVATE int sqlcipher3BitvecTest(Bitvec*, u32);
11421 SQLCIPHER_PRIVATE int sqlcipher3BitvecSet(Bitvec*, u32);
11422 SQLCIPHER_PRIVATE void sqlcipher3BitvecClear(Bitvec*, u32, void*);
11423 SQLCIPHER_PRIVATE void sqlcipher3BitvecDestroy(Bitvec*);
11424 SQLCIPHER_PRIVATE u32 sqlcipher3BitvecSize(Bitvec*);
11425 SQLCIPHER_PRIVATE int sqlcipher3BitvecBuiltinTest(int,int*);
11426
11427 SQLCIPHER_PRIVATE RowSet *sqlcipher3RowSetInit(sqlcipher3*, void*, unsigned int);
11428 SQLCIPHER_PRIVATE void sqlcipher3RowSetClear(RowSet*);
11429 SQLCIPHER_PRIVATE void sqlcipher3RowSetInsert(RowSet*, i64);
11430 SQLCIPHER_PRIVATE int sqlcipher3RowSetTest(RowSet*, u8 iBatch, i64);
11431 SQLCIPHER_PRIVATE int sqlcipher3RowSetNext(RowSet*, i64*);
11432
11433 SQLCIPHER_PRIVATE void sqlcipher3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11434
11435 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_VIRTUALTABLE)
11436 SQLCIPHER_PRIVATE   int sqlcipher3ViewGetColumnNames(Parse*,Table*);
11437 #else
11438 # define sqlcipher3ViewGetColumnNames(A,B) 0
11439 #endif
11440
11441 SQLCIPHER_PRIVATE void sqlcipher3DropTable(Parse*, SrcList*, int, int);
11442 SQLCIPHER_PRIVATE void sqlcipher3CodeDropTable(Parse*, Table*, int, int);
11443 SQLCIPHER_PRIVATE void sqlcipher3DeleteTable(sqlcipher3*, Table*);
11444 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
11445 SQLCIPHER_PRIVATE   void sqlcipher3AutoincrementBegin(Parse *pParse);
11446 SQLCIPHER_PRIVATE   void sqlcipher3AutoincrementEnd(Parse *pParse);
11447 #else
11448 # define sqlcipher3AutoincrementBegin(X)
11449 # define sqlcipher3AutoincrementEnd(X)
11450 #endif
11451 SQLCIPHER_PRIVATE void sqlcipher3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11452 SQLCIPHER_PRIVATE void *sqlcipher3ArrayAllocate(sqlcipher3*,void*,int,int,int*,int*,int*);
11453 SQLCIPHER_PRIVATE IdList *sqlcipher3IdListAppend(sqlcipher3*, IdList*, Token*);
11454 SQLCIPHER_PRIVATE int sqlcipher3IdListIndex(IdList*,const char*);
11455 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListEnlarge(sqlcipher3*, SrcList*, int, int);
11456 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListAppend(sqlcipher3*, SrcList*, Token*, Token*);
11457 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11458                                       Token*, Select*, Expr*, IdList*);
11459 SQLCIPHER_PRIVATE void sqlcipher3SrcListIndexedBy(Parse *, SrcList *, Token *);
11460 SQLCIPHER_PRIVATE int sqlcipher3IndexedByLookup(Parse *, struct SrcList_item *);
11461 SQLCIPHER_PRIVATE void sqlcipher3SrcListShiftJoinType(SrcList*);
11462 SQLCIPHER_PRIVATE void sqlcipher3SrcListAssignCursors(Parse*, SrcList*);
11463 SQLCIPHER_PRIVATE void sqlcipher3IdListDelete(sqlcipher3*, IdList*);
11464 SQLCIPHER_PRIVATE void sqlcipher3SrcListDelete(sqlcipher3*, SrcList*);
11465 SQLCIPHER_PRIVATE Index *sqlcipher3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11466                         Token*, int, int);
11467 SQLCIPHER_PRIVATE void sqlcipher3DropIndex(Parse*, SrcList*, int);
11468 SQLCIPHER_PRIVATE int sqlcipher3Select(Parse*, Select*, SelectDest*);
11469 SQLCIPHER_PRIVATE Select *sqlcipher3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11470                          Expr*,ExprList*,int,Expr*,Expr*);
11471 SQLCIPHER_PRIVATE void sqlcipher3SelectDelete(sqlcipher3*, Select*);
11472 SQLCIPHER_PRIVATE Table *sqlcipher3SrcListLookup(Parse*, SrcList*);
11473 SQLCIPHER_PRIVATE int sqlcipher3IsReadOnly(Parse*, Table*, int);
11474 SQLCIPHER_PRIVATE void sqlcipher3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11475 #if defined(SQLCIPHER_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLCIPHER_OMIT_SUBQUERY)
11476 SQLCIPHER_PRIVATE Expr *sqlcipher3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11477 #endif
11478 SQLCIPHER_PRIVATE void sqlcipher3DeleteFrom(Parse*, SrcList*, Expr*);
11479 SQLCIPHER_PRIVATE void sqlcipher3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11480 SQLCIPHER_PRIVATE WhereInfo *sqlcipher3WhereBegin(Parse*, SrcList*, Expr*, ExprList**,ExprList*,u16);
11481 SQLCIPHER_PRIVATE void sqlcipher3WhereEnd(WhereInfo*);
11482 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeGetColumn(Parse*, Table*, int, int, int);
11483 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11484 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeMove(Parse*, int, int, int);
11485 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeCopy(Parse*, int, int, int);
11486 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheStore(Parse*, int, int, int);
11487 SQLCIPHER_PRIVATE void sqlcipher3ExprCachePush(Parse*);
11488 SQLCIPHER_PRIVATE void sqlcipher3ExprCachePop(Parse*, int);
11489 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheRemove(Parse*, int, int);
11490 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheClear(Parse*);
11491 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheAffinityChange(Parse*, int, int);
11492 SQLCIPHER_PRIVATE int sqlcipher3ExprCode(Parse*, Expr*, int);
11493 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeTemp(Parse*, Expr*, int*);
11494 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeTarget(Parse*, Expr*, int);
11495 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeAndCache(Parse*, Expr*, int);
11496 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeConstants(Parse*, Expr*);
11497 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeExprList(Parse*, ExprList*, int, int);
11498 SQLCIPHER_PRIVATE void sqlcipher3ExprIfTrue(Parse*, Expr*, int, int);
11499 SQLCIPHER_PRIVATE void sqlcipher3ExprIfFalse(Parse*, Expr*, int, int);
11500 SQLCIPHER_PRIVATE Table *sqlcipher3FindTable(sqlcipher3*,const char*, const char*);
11501 SQLCIPHER_PRIVATE Table *sqlcipher3LocateTable(Parse*,int isView,const char*, const char*);
11502 SQLCIPHER_PRIVATE Index *sqlcipher3FindIndex(sqlcipher3*,const char*, const char*);
11503 SQLCIPHER_PRIVATE void sqlcipher3UnlinkAndDeleteTable(sqlcipher3*,int,const char*);
11504 SQLCIPHER_PRIVATE void sqlcipher3UnlinkAndDeleteIndex(sqlcipher3*,int,const char*);
11505 SQLCIPHER_PRIVATE void sqlcipher3Vacuum(Parse*);
11506 SQLCIPHER_PRIVATE int sqlcipher3RunVacuum(char**, sqlcipher3*);
11507 SQLCIPHER_PRIVATE char *sqlcipher3NameFromToken(sqlcipher3*, Token*);
11508 SQLCIPHER_PRIVATE int sqlcipher3ExprCompare(Expr*, Expr*);
11509 SQLCIPHER_PRIVATE int sqlcipher3ExprListCompare(ExprList*, ExprList*);
11510 SQLCIPHER_PRIVATE void sqlcipher3ExprAnalyzeAggregates(NameContext*, Expr*);
11511 SQLCIPHER_PRIVATE void sqlcipher3ExprAnalyzeAggList(NameContext*,ExprList*);
11512 SQLCIPHER_PRIVATE Vdbe *sqlcipher3GetVdbe(Parse*);
11513 SQLCIPHER_PRIVATE void sqlcipher3PrngSaveState(void);
11514 SQLCIPHER_PRIVATE void sqlcipher3PrngRestoreState(void);
11515 SQLCIPHER_PRIVATE void sqlcipher3PrngResetState(void);
11516 SQLCIPHER_PRIVATE void sqlcipher3RollbackAll(sqlcipher3*);
11517 SQLCIPHER_PRIVATE void sqlcipher3CodeVerifySchema(Parse*, int);
11518 SQLCIPHER_PRIVATE void sqlcipher3CodeVerifyNamedSchema(Parse*, const char *zDb);
11519 SQLCIPHER_PRIVATE void sqlcipher3BeginTransaction(Parse*, int);
11520 SQLCIPHER_PRIVATE void sqlcipher3CommitTransaction(Parse*);
11521 SQLCIPHER_PRIVATE void sqlcipher3RollbackTransaction(Parse*);
11522 SQLCIPHER_PRIVATE void sqlcipher3Savepoint(Parse*, int, Token*);
11523 SQLCIPHER_PRIVATE void sqlcipher3CloseSavepoints(sqlcipher3 *);
11524 SQLCIPHER_PRIVATE int sqlcipher3ExprIsConstant(Expr*);
11525 SQLCIPHER_PRIVATE int sqlcipher3ExprIsConstantNotJoin(Expr*);
11526 SQLCIPHER_PRIVATE int sqlcipher3ExprIsConstantOrFunction(Expr*);
11527 SQLCIPHER_PRIVATE int sqlcipher3ExprIsInteger(Expr*, int*);
11528 SQLCIPHER_PRIVATE int sqlcipher3ExprCanBeNull(const Expr*);
11529 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11530 SQLCIPHER_PRIVATE int sqlcipher3ExprNeedsNoAffinityChange(const Expr*, char);
11531 SQLCIPHER_PRIVATE int sqlcipher3IsRowid(const char*);
11532 SQLCIPHER_PRIVATE void sqlcipher3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11533 SQLCIPHER_PRIVATE void sqlcipher3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11534 SQLCIPHER_PRIVATE int sqlcipher3GenerateIndexKey(Parse*, Index*, int, int, int);
11535 SQLCIPHER_PRIVATE void sqlcipher3GenerateConstraintChecks(Parse*,Table*,int,int,
11536                                      int*,int,int,int,int,int*);
11537 SQLCIPHER_PRIVATE void sqlcipher3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11538 SQLCIPHER_PRIVATE int sqlcipher3OpenTableAndIndices(Parse*, Table*, int, int);
11539 SQLCIPHER_PRIVATE void sqlcipher3BeginWriteOperation(Parse*, int, int);
11540 SQLCIPHER_PRIVATE void sqlcipher3MultiWrite(Parse*);
11541 SQLCIPHER_PRIVATE void sqlcipher3MayAbort(Parse*);
11542 SQLCIPHER_PRIVATE void sqlcipher3HaltConstraint(Parse*, int, char*, int);
11543 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprDup(sqlcipher3*,Expr*,int);
11544 SQLCIPHER_PRIVATE ExprList *sqlcipher3ExprListDup(sqlcipher3*,ExprList*,int);
11545 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListDup(sqlcipher3*,SrcList*,int);
11546 SQLCIPHER_PRIVATE IdList *sqlcipher3IdListDup(sqlcipher3*,IdList*);
11547 SQLCIPHER_PRIVATE Select *sqlcipher3SelectDup(sqlcipher3*,Select*,int);
11548 SQLCIPHER_PRIVATE void sqlcipher3FuncDefInsert(FuncDefHash*, FuncDef*);
11549 SQLCIPHER_PRIVATE FuncDef *sqlcipher3FindFunction(sqlcipher3*,const char*,int,int,u8,int);
11550 SQLCIPHER_PRIVATE void sqlcipher3RegisterBuiltinFunctions(sqlcipher3*);
11551 SQLCIPHER_PRIVATE void sqlcipher3RegisterDateTimeFunctions(void);
11552 SQLCIPHER_PRIVATE void sqlcipher3RegisterGlobalFunctions(void);
11553 SQLCIPHER_PRIVATE int sqlcipher3SafetyCheckOk(sqlcipher3*);
11554 SQLCIPHER_PRIVATE int sqlcipher3SafetyCheckSickOrOk(sqlcipher3*);
11555 SQLCIPHER_PRIVATE void sqlcipher3ChangeCookie(Parse*, int);
11556
11557 #if !defined(SQLCIPHER_OMIT_VIEW) && !defined(SQLCIPHER_OMIT_TRIGGER)
11558 SQLCIPHER_PRIVATE void sqlcipher3MaterializeView(Parse*, Table*, Expr*, int);
11559 #endif
11560
11561 #ifndef SQLCIPHER_OMIT_TRIGGER
11562 SQLCIPHER_PRIVATE   void sqlcipher3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11563                            Expr*,int, int);
11564 SQLCIPHER_PRIVATE   void sqlcipher3FinishTrigger(Parse*, TriggerStep*, Token*);
11565 SQLCIPHER_PRIVATE   void sqlcipher3DropTrigger(Parse*, SrcList*, int);
11566 SQLCIPHER_PRIVATE   void sqlcipher3DropTriggerPtr(Parse*, Trigger*);
11567 SQLCIPHER_PRIVATE   Trigger *sqlcipher3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11568 SQLCIPHER_PRIVATE   Trigger *sqlcipher3TriggerList(Parse *, Table *);
11569 SQLCIPHER_PRIVATE   void sqlcipher3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11570                             int, int, int);
11571 SQLCIPHER_PRIVATE   void sqlcipher3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11572   void sqlcipherViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11573 SQLCIPHER_PRIVATE   void sqlcipher3DeleteTriggerStep(sqlcipher3*, TriggerStep*);
11574 SQLCIPHER_PRIVATE   TriggerStep *sqlcipher3TriggerSelectStep(sqlcipher3*,Select*);
11575 SQLCIPHER_PRIVATE   TriggerStep *sqlcipher3TriggerInsertStep(sqlcipher3*,Token*, IdList*,
11576                                         ExprList*,Select*,u8);
11577 SQLCIPHER_PRIVATE   TriggerStep *sqlcipher3TriggerUpdateStep(sqlcipher3*,Token*,ExprList*, Expr*, u8);
11578 SQLCIPHER_PRIVATE   TriggerStep *sqlcipher3TriggerDeleteStep(sqlcipher3*,Token*, Expr*);
11579 SQLCIPHER_PRIVATE   void sqlcipher3DeleteTrigger(sqlcipher3*, Trigger*);
11580 SQLCIPHER_PRIVATE   void sqlcipher3UnlinkAndDeleteTrigger(sqlcipher3*,int,const char*);
11581 SQLCIPHER_PRIVATE   u32 sqlcipher3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11582 # define sqlcipher3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11583 #else
11584 # define sqlcipher3TriggersExist(B,C,D,E,F) 0
11585 # define sqlcipher3DeleteTrigger(A,B)
11586 # define sqlcipher3DropTriggerPtr(A,B)
11587 # define sqlcipher3UnlinkAndDeleteTrigger(A,B,C)
11588 # define sqlcipher3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11589 # define sqlcipher3CodeRowTriggerDirect(A,B,C,D,E,F)
11590 # define sqlcipher3TriggerList(X, Y) 0
11591 # define sqlcipher3ParseToplevel(p) p
11592 # define sqlcipher3TriggerColmask(A,B,C,D,E,F,G) 0
11593 #endif
11594
11595 SQLCIPHER_PRIVATE int sqlcipher3JoinType(Parse*, Token*, Token*, Token*);
11596 SQLCIPHER_PRIVATE void sqlcipher3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11597 SQLCIPHER_PRIVATE void sqlcipher3DeferForeignKey(Parse*, int);
11598 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
11599 SQLCIPHER_PRIVATE   void sqlcipher3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11600 SQLCIPHER_PRIVATE   int sqlcipher3AuthCheck(Parse*,int, const char*, const char*, const char*);
11601 SQLCIPHER_PRIVATE   void sqlcipher3AuthContextPush(Parse*, AuthContext*, const char*);
11602 SQLCIPHER_PRIVATE   void sqlcipher3AuthContextPop(AuthContext*);
11603 SQLCIPHER_PRIVATE   int sqlcipher3AuthReadCol(Parse*, const char *, const char *, int);
11604 #else
11605 # define sqlcipher3AuthRead(a,b,c,d)
11606 # define sqlcipher3AuthCheck(a,b,c,d,e)    SQLCIPHER_OK
11607 # define sqlcipher3AuthContextPush(a,b,c)
11608 # define sqlcipher3AuthContextPop(a)  ((void)(a))
11609 #endif
11610 SQLCIPHER_PRIVATE void sqlcipher3Attach(Parse*, Expr*, Expr*, Expr*);
11611 SQLCIPHER_PRIVATE void sqlcipher3Detach(Parse*, Expr*);
11612 SQLCIPHER_PRIVATE int sqlcipher3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11613 SQLCIPHER_PRIVATE int sqlcipher3FixSrcList(DbFixer*, SrcList*);
11614 SQLCIPHER_PRIVATE int sqlcipher3FixSelect(DbFixer*, Select*);
11615 SQLCIPHER_PRIVATE int sqlcipher3FixExpr(DbFixer*, Expr*);
11616 SQLCIPHER_PRIVATE int sqlcipher3FixExprList(DbFixer*, ExprList*);
11617 SQLCIPHER_PRIVATE int sqlcipher3FixTriggerStep(DbFixer*, TriggerStep*);
11618 SQLCIPHER_PRIVATE int sqlcipher3AtoF(const char *z, double*, int, u8);
11619 SQLCIPHER_PRIVATE int sqlcipher3GetInt32(const char *, int*);
11620 SQLCIPHER_PRIVATE int sqlcipher3Atoi(const char*);
11621 SQLCIPHER_PRIVATE int sqlcipher3Utf16ByteLen(const void *pData, int nChar);
11622 SQLCIPHER_PRIVATE int sqlcipher3Utf8CharLen(const char *pData, int nByte);
11623 SQLCIPHER_PRIVATE u32 sqlcipher3Utf8Read(const u8*, const u8**);
11624
11625 /*
11626 ** Routines to read and write variable-length integers.  These used to
11627 ** be defined locally, but now we use the varint routines in the util.c
11628 ** file.  Code should use the MACRO forms below, as the Varint32 versions
11629 ** are coded to assume the single byte case is already handled (which 
11630 ** the MACRO form does).
11631 */
11632 SQLCIPHER_PRIVATE int sqlcipher3PutVarint(unsigned char*, u64);
11633 SQLCIPHER_PRIVATE int sqlcipher3PutVarint32(unsigned char*, u32);
11634 SQLCIPHER_PRIVATE u8 sqlcipher3GetVarint(const unsigned char *, u64 *);
11635 SQLCIPHER_PRIVATE u8 sqlcipher3GetVarint32(const unsigned char *, u32 *);
11636 SQLCIPHER_PRIVATE int sqlcipher3VarintLen(u64 v);
11637
11638 /*
11639 ** The header of a record consists of a sequence variable-length integers.
11640 ** These integers are almost always small and are encoded as a single byte.
11641 ** The following macros take advantage this fact to provide a fast encode
11642 ** and decode of the integers in a record header.  It is faster for the common
11643 ** case where the integer is a single byte.  It is a little slower when the
11644 ** integer is two or more bytes.  But overall it is faster.
11645 **
11646 ** The following expressions are equivalent:
11647 **
11648 **     x = sqlcipher3GetVarint32( A, &B );
11649 **     x = sqlcipher3PutVarint32( A, B );
11650 **
11651 **     x = getVarint32( A, B );
11652 **     x = putVarint32( A, B );
11653 **
11654 */
11655 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlcipher3GetVarint32((A), (u32 *)&(B)))
11656 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlcipher3PutVarint32((A), (B)))
11657 #define getVarint    sqlcipher3GetVarint
11658 #define putVarint    sqlcipher3PutVarint
11659
11660
11661 SQLCIPHER_PRIVATE const char *sqlcipher3IndexAffinityStr(Vdbe *, Index *);
11662 SQLCIPHER_PRIVATE void sqlcipher3TableAffinityStr(Vdbe *, Table *);
11663 SQLCIPHER_PRIVATE char sqlcipher3CompareAffinity(Expr *pExpr, char aff2);
11664 SQLCIPHER_PRIVATE int sqlcipher3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11665 SQLCIPHER_PRIVATE char sqlcipher3ExprAffinity(Expr *pExpr);
11666 SQLCIPHER_PRIVATE int sqlcipher3Atoi64(const char*, i64*, int, u8);
11667 SQLCIPHER_PRIVATE void sqlcipher3Error(sqlcipher3*, int, const char*,...);
11668 SQLCIPHER_PRIVATE void *sqlcipher3HexToBlob(sqlcipher3*, const char *z, int n);
11669 SQLCIPHER_PRIVATE u8 sqlcipher3HexToInt(int h);
11670 SQLCIPHER_PRIVATE int sqlcipher3TwoPartName(Parse *, Token *, Token *, Token **);
11671 SQLCIPHER_PRIVATE const char *sqlcipher3ErrStr(int);
11672 SQLCIPHER_PRIVATE int sqlcipher3ReadSchema(Parse *pParse);
11673 SQLCIPHER_PRIVATE CollSeq *sqlcipher3FindCollSeq(sqlcipher3*,u8 enc, const char*,int);
11674 SQLCIPHER_PRIVATE CollSeq *sqlcipher3LocateCollSeq(Parse *pParse, const char*zName);
11675 SQLCIPHER_PRIVATE CollSeq *sqlcipher3ExprCollSeq(Parse *pParse, Expr *pExpr);
11676 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprSetColl(Expr*, CollSeq*);
11677 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11678 SQLCIPHER_PRIVATE int sqlcipher3CheckCollSeq(Parse *, CollSeq *);
11679 SQLCIPHER_PRIVATE int sqlcipher3CheckObjectName(Parse *, const char *);
11680 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetChanges(sqlcipher3 *, int);
11681 SQLCIPHER_PRIVATE int sqlcipher3AddInt64(i64*,i64);
11682 SQLCIPHER_PRIVATE int sqlcipher3SubInt64(i64*,i64);
11683 SQLCIPHER_PRIVATE int sqlcipher3MulInt64(i64*,i64);
11684 SQLCIPHER_PRIVATE int sqlcipher3AbsInt32(int);
11685 #ifdef SQLCIPHER_ENABLE_8_3_NAMES
11686 SQLCIPHER_PRIVATE void sqlcipher3FileSuffix3(const char*, char*);
11687 #else
11688 # define sqlcipher3FileSuffix3(X,Y)
11689 #endif
11690 SQLCIPHER_PRIVATE u8 sqlcipher3GetBoolean(const char *z);
11691
11692 SQLCIPHER_PRIVATE const void *sqlcipher3ValueText(sqlcipher3_value*, u8);
11693 SQLCIPHER_PRIVATE int sqlcipher3ValueBytes(sqlcipher3_value*, u8);
11694 SQLCIPHER_PRIVATE void sqlcipher3ValueSetStr(sqlcipher3_value*, int, const void *,u8, 
11695                         void(*)(void*));
11696 SQLCIPHER_PRIVATE void sqlcipher3ValueFree(sqlcipher3_value*);
11697 SQLCIPHER_PRIVATE sqlcipher3_value *sqlcipher3ValueNew(sqlcipher3 *);
11698 SQLCIPHER_PRIVATE char *sqlcipher3Utf16to8(sqlcipher3 *, const void*, int, u8);
11699 #ifdef SQLCIPHER_ENABLE_STAT3
11700 SQLCIPHER_PRIVATE char *sqlcipher3Utf8to16(sqlcipher3 *, u8, char *, int, int *);
11701 #endif
11702 SQLCIPHER_PRIVATE int sqlcipher3ValueFromExpr(sqlcipher3 *, Expr *, u8, u8, sqlcipher3_value **);
11703 SQLCIPHER_PRIVATE void sqlcipher3ValueApplyAffinity(sqlcipher3_value *, u8, u8);
11704 #ifndef SQLCIPHER_AMALGAMATION
11705 SQLCIPHER_PRIVATE const unsigned char sqlcipher3OpcodeProperty[];
11706 SQLCIPHER_PRIVATE const unsigned char sqlcipher3UpperToLower[];
11707 SQLCIPHER_PRIVATE const unsigned char sqlcipher3CtypeMap[];
11708 SQLCIPHER_PRIVATE const Token sqlcipher3IntTokens[];
11709 SQLCIPHER_PRIVATE SQLCIPHER_WSD struct Sqlite3Config sqlcipher3Config;
11710 SQLCIPHER_PRIVATE SQLCIPHER_WSD FuncDefHash sqlcipher3GlobalFunctions;
11711 #ifndef SQLCIPHER_OMIT_WSD
11712 SQLCIPHER_PRIVATE int sqlcipher3PendingByte;
11713 #endif
11714 #endif
11715 SQLCIPHER_PRIVATE void sqlcipher3RootPageMoved(sqlcipher3*, int, int, int);
11716 SQLCIPHER_PRIVATE void sqlcipher3Reindex(Parse*, Token*, Token*);
11717 SQLCIPHER_PRIVATE void sqlcipher3AlterFunctions(void);
11718 SQLCIPHER_PRIVATE void sqlcipher3AlterRenameTable(Parse*, SrcList*, Token*);
11719 SQLCIPHER_PRIVATE int sqlcipher3GetToken(const unsigned char *, int *);
11720 SQLCIPHER_PRIVATE void sqlcipher3NestedParse(Parse*, const char*, ...);
11721 SQLCIPHER_PRIVATE void sqlcipher3ExpirePreparedStatements(sqlcipher3*);
11722 SQLCIPHER_PRIVATE int sqlcipher3CodeSubselect(Parse *, Expr *, int, int);
11723 SQLCIPHER_PRIVATE void sqlcipher3SelectPrep(Parse*, Select*, NameContext*);
11724 SQLCIPHER_PRIVATE int sqlcipher3ResolveExprNames(NameContext*, Expr*);
11725 SQLCIPHER_PRIVATE void sqlcipher3ResolveSelectNames(Parse*, Select*, NameContext*);
11726 SQLCIPHER_PRIVATE int sqlcipher3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11727 SQLCIPHER_PRIVATE void sqlcipher3ColumnDefault(Vdbe *, Table *, int, int);
11728 SQLCIPHER_PRIVATE void sqlcipher3AlterFinishAddColumn(Parse *, Token *);
11729 SQLCIPHER_PRIVATE void sqlcipher3AlterBeginAddColumn(Parse *, SrcList *);
11730 SQLCIPHER_PRIVATE CollSeq *sqlcipher3GetCollSeq(sqlcipher3*, u8, CollSeq *, const char*);
11731 SQLCIPHER_PRIVATE char sqlcipher3AffinityType(const char*);
11732 SQLCIPHER_PRIVATE void sqlcipher3Analyze(Parse*, Token*, Token*);
11733 SQLCIPHER_PRIVATE int sqlcipher3InvokeBusyHandler(BusyHandler*);
11734 SQLCIPHER_PRIVATE int sqlcipher3FindDb(sqlcipher3*, Token*);
11735 SQLCIPHER_PRIVATE int sqlcipher3FindDbName(sqlcipher3 *, const char *);
11736 SQLCIPHER_PRIVATE int sqlcipher3AnalysisLoad(sqlcipher3*,int iDB);
11737 SQLCIPHER_PRIVATE void sqlcipher3DeleteIndexSamples(sqlcipher3*,Index*);
11738 SQLCIPHER_PRIVATE void sqlcipher3DefaultRowEst(Index*);
11739 SQLCIPHER_PRIVATE void sqlcipher3RegisterLikeFunctions(sqlcipher3*, int);
11740 SQLCIPHER_PRIVATE int sqlcipher3IsLikeFunction(sqlcipher3*,Expr*,int*,char*);
11741 SQLCIPHER_PRIVATE void sqlcipher3MinimumFileFormat(Parse*, int, int);
11742 SQLCIPHER_PRIVATE void sqlcipher3SchemaClear(void *);
11743 SQLCIPHER_PRIVATE Schema *sqlcipher3SchemaGet(sqlcipher3 *, Btree *);
11744 SQLCIPHER_PRIVATE int sqlcipher3SchemaToIndex(sqlcipher3 *db, Schema *);
11745 SQLCIPHER_PRIVATE KeyInfo *sqlcipher3IndexKeyinfo(Parse *, Index *);
11746 SQLCIPHER_PRIVATE int sqlcipher3CreateFunc(sqlcipher3 *, const char *, int, int, void *, 
11747   void (*)(sqlcipher3_context*,int,sqlcipher3_value **),
11748   void (*)(sqlcipher3_context*,int,sqlcipher3_value **), void (*)(sqlcipher3_context*),
11749   FuncDestructor *pDestructor
11750 );
11751 SQLCIPHER_PRIVATE int sqlcipher3ApiExit(sqlcipher3 *db, int);
11752 SQLCIPHER_PRIVATE int sqlcipher3OpenTempDatabase(Parse *);
11753
11754 SQLCIPHER_PRIVATE void sqlcipher3StrAccumInit(StrAccum*, char*, int, int);
11755 SQLCIPHER_PRIVATE void sqlcipher3StrAccumAppend(StrAccum*,const char*,int);
11756 SQLCIPHER_PRIVATE char *sqlcipher3StrAccumFinish(StrAccum*);
11757 SQLCIPHER_PRIVATE void sqlcipher3StrAccumReset(StrAccum*);
11758 SQLCIPHER_PRIVATE void sqlcipher3SelectDestInit(SelectDest*,int,int);
11759 SQLCIPHER_PRIVATE Expr *sqlcipher3CreateColumnExpr(sqlcipher3 *, SrcList *, int, int);
11760
11761 SQLCIPHER_PRIVATE void sqlcipher3BackupRestart(sqlcipher3_backup *);
11762 SQLCIPHER_PRIVATE void sqlcipher3BackupUpdate(sqlcipher3_backup *, Pgno, const u8 *);
11763
11764 /*
11765 ** The interface to the LEMON-generated parser
11766 */
11767 SQLCIPHER_PRIVATE void *sqlcipher3ParserAlloc(void*(*)(size_t));
11768 SQLCIPHER_PRIVATE void sqlcipher3ParserFree(void*, void(*)(void*));
11769 SQLCIPHER_PRIVATE void sqlcipher3Parser(void*, int, Token, Parse*);
11770 #ifdef YYTRACKMAXSTACKDEPTH
11771 SQLCIPHER_PRIVATE   int sqlcipher3ParserStackPeak(void*);
11772 #endif
11773
11774 SQLCIPHER_PRIVATE void sqlcipher3AutoLoadExtensions(sqlcipher3*);
11775 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
11776 SQLCIPHER_PRIVATE   void sqlcipher3CloseExtensions(sqlcipher3*);
11777 #else
11778 # define sqlcipher3CloseExtensions(X)
11779 #endif
11780
11781 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
11782 SQLCIPHER_PRIVATE   void sqlcipher3TableLock(Parse *, int, int, u8, const char *);
11783 #else
11784   #define sqlcipher3TableLock(v,w,x,y,z)
11785 #endif
11786
11787 #ifdef SQLCIPHER_TEST
11788 SQLCIPHER_PRIVATE   int sqlcipher3Utf8To8(unsigned char*);
11789 #endif
11790
11791 #ifdef SQLCIPHER_OMIT_VIRTUALTABLE
11792 #  define sqlcipher3VtabClear(Y)
11793 #  define sqlcipher3VtabSync(X,Y) SQLCIPHER_OK
11794 #  define sqlcipher3VtabRollback(X)
11795 #  define sqlcipher3VtabCommit(X)
11796 #  define sqlcipher3VtabInSync(db) 0
11797 #  define sqlcipher3VtabLock(X) 
11798 #  define sqlcipher3VtabUnlock(X)
11799 #  define sqlcipher3VtabUnlockList(X)
11800 #  define sqlcipher3VtabSavepoint(X, Y, Z) SQLCIPHER_OK
11801 #  define sqlcipher3GetVTable(X,Y)  ((VTable*)0)
11802 #else
11803 SQLCIPHER_PRIVATE    void sqlcipher3VtabClear(sqlcipher3 *db, Table*);
11804 SQLCIPHER_PRIVATE    int sqlcipher3VtabSync(sqlcipher3 *db, char **);
11805 SQLCIPHER_PRIVATE    int sqlcipher3VtabRollback(sqlcipher3 *db);
11806 SQLCIPHER_PRIVATE    int sqlcipher3VtabCommit(sqlcipher3 *db);
11807 SQLCIPHER_PRIVATE    void sqlcipher3VtabLock(VTable *);
11808 SQLCIPHER_PRIVATE    void sqlcipher3VtabUnlock(VTable *);
11809 SQLCIPHER_PRIVATE    void sqlcipher3VtabUnlockList(sqlcipher3*);
11810 SQLCIPHER_PRIVATE    int sqlcipher3VtabSavepoint(sqlcipher3 *, int, int);
11811 SQLCIPHER_PRIVATE    VTable *sqlcipher3GetVTable(sqlcipher3*, Table*);
11812 #  define sqlcipher3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11813 #endif
11814 SQLCIPHER_PRIVATE void sqlcipher3VtabMakeWritable(Parse*,Table*);
11815 SQLCIPHER_PRIVATE void sqlcipher3VtabBeginParse(Parse*, Token*, Token*, Token*);
11816 SQLCIPHER_PRIVATE void sqlcipher3VtabFinishParse(Parse*, Token*);
11817 SQLCIPHER_PRIVATE void sqlcipher3VtabArgInit(Parse*);
11818 SQLCIPHER_PRIVATE void sqlcipher3VtabArgExtend(Parse*, Token*);
11819 SQLCIPHER_PRIVATE int sqlcipher3VtabCallCreate(sqlcipher3*, int, const char *, char **);
11820 SQLCIPHER_PRIVATE int sqlcipher3VtabCallConnect(Parse*, Table*);
11821 SQLCIPHER_PRIVATE int sqlcipher3VtabCallDestroy(sqlcipher3*, int, const char *);
11822 SQLCIPHER_PRIVATE int sqlcipher3VtabBegin(sqlcipher3 *, VTable *);
11823 SQLCIPHER_PRIVATE FuncDef *sqlcipher3VtabOverloadFunction(sqlcipher3 *,FuncDef*, int nArg, Expr*);
11824 SQLCIPHER_PRIVATE void sqlcipher3InvalidFunction(sqlcipher3_context*,int,sqlcipher3_value**);
11825 SQLCIPHER_PRIVATE int sqlcipher3VdbeParameterIndex(Vdbe*, const char*, int);
11826 SQLCIPHER_PRIVATE int sqlcipher3TransferBindings(sqlcipher3_stmt *, sqlcipher3_stmt *);
11827 SQLCIPHER_PRIVATE int sqlcipher3Reprepare(Vdbe*);
11828 SQLCIPHER_PRIVATE void sqlcipher3ExprListCheckLength(Parse*, ExprList*, const char*);
11829 SQLCIPHER_PRIVATE CollSeq *sqlcipher3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11830 SQLCIPHER_PRIVATE int sqlcipher3TempInMemory(const sqlcipher3*);
11831 SQLCIPHER_PRIVATE const char *sqlcipher3JournalModename(int);
11832 SQLCIPHER_PRIVATE int sqlcipher3Checkpoint(sqlcipher3*, int, int, int*, int*);
11833 SQLCIPHER_PRIVATE int sqlcipher3WalDefaultHook(void*,sqlcipher3*,const char*,int);
11834
11835 /* Declarations for functions in fkey.c. All of these are replaced by
11836 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
11837 ** key functionality is available. If OMIT_TRIGGER is defined but
11838 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
11839 ** this case foreign keys are parsed, but no other functionality is 
11840 ** provided (enforcement of FK constraints requires the triggers sub-system).
11841 */
11842 #if !defined(SQLCIPHER_OMIT_FOREIGN_KEY) && !defined(SQLCIPHER_OMIT_TRIGGER)
11843 SQLCIPHER_PRIVATE   void sqlcipher3FkCheck(Parse*, Table*, int, int);
11844 SQLCIPHER_PRIVATE   void sqlcipher3FkDropTable(Parse*, SrcList *, Table*);
11845 SQLCIPHER_PRIVATE   void sqlcipher3FkActions(Parse*, Table*, ExprList*, int);
11846 SQLCIPHER_PRIVATE   int sqlcipher3FkRequired(Parse*, Table*, int*, int);
11847 SQLCIPHER_PRIVATE   u32 sqlcipher3FkOldmask(Parse*, Table*);
11848 SQLCIPHER_PRIVATE   FKey *sqlcipher3FkReferences(Table *);
11849 #else
11850   #define sqlcipher3FkActions(a,b,c,d)
11851   #define sqlcipher3FkCheck(a,b,c,d)
11852   #define sqlcipher3FkDropTable(a,b,c)
11853   #define sqlcipher3FkOldmask(a,b)      0
11854   #define sqlcipher3FkRequired(a,b,c,d) 0
11855 #endif
11856 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
11857 SQLCIPHER_PRIVATE   void sqlcipher3FkDelete(sqlcipher3 *, Table*);
11858 #else
11859   #define sqlcipher3FkDelete(a,b)
11860 #endif
11861
11862
11863 /*
11864 ** Available fault injectors.  Should be numbered beginning with 0.
11865 */
11866 #define SQLCIPHER_FAULTINJECTOR_MALLOC     0
11867 #define SQLCIPHER_FAULTINJECTOR_COUNT      1
11868
11869 /*
11870 ** The interface to the code in fault.c used for identifying "benign"
11871 ** malloc failures. This is only present if SQLCIPHER_OMIT_BUILTIN_TEST
11872 ** is not defined.
11873 */
11874 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
11875 SQLCIPHER_PRIVATE   void sqlcipher3BeginBenignMalloc(void);
11876 SQLCIPHER_PRIVATE   void sqlcipher3EndBenignMalloc(void);
11877 #else
11878   #define sqlcipher3BeginBenignMalloc()
11879   #define sqlcipher3EndBenignMalloc()
11880 #endif
11881
11882 #define IN_INDEX_ROWID           1
11883 #define IN_INDEX_EPH             2
11884 #define IN_INDEX_INDEX           3
11885 SQLCIPHER_PRIVATE int sqlcipher3FindInIndex(Parse *, Expr *, int*);
11886
11887 #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
11888 SQLCIPHER_PRIVATE   int sqlcipher3JournalOpen(sqlcipher3_vfs *, const char *, sqlcipher3_file *, int, int);
11889 SQLCIPHER_PRIVATE   int sqlcipher3JournalSize(sqlcipher3_vfs *);
11890 SQLCIPHER_PRIVATE   int sqlcipher3JournalCreate(sqlcipher3_file *);
11891 #else
11892   #define sqlcipher3JournalSize(pVfs) ((pVfs)->szOsFile)
11893 #endif
11894
11895 SQLCIPHER_PRIVATE void sqlcipher3MemJournalOpen(sqlcipher3_file *);
11896 SQLCIPHER_PRIVATE int sqlcipher3MemJournalSize(void);
11897 SQLCIPHER_PRIVATE int sqlcipher3IsMemJournal(sqlcipher3_file *);
11898
11899 #if SQLCIPHER_MAX_EXPR_DEPTH>0
11900 SQLCIPHER_PRIVATE   void sqlcipher3ExprSetHeight(Parse *pParse, Expr *p);
11901 SQLCIPHER_PRIVATE   int sqlcipher3SelectExprHeight(Select *);
11902 SQLCIPHER_PRIVATE   int sqlcipher3ExprCheckHeight(Parse*, int);
11903 #else
11904   #define sqlcipher3ExprSetHeight(x,y)
11905   #define sqlcipher3SelectExprHeight(x) 0
11906   #define sqlcipher3ExprCheckHeight(x,y)
11907 #endif
11908
11909 SQLCIPHER_PRIVATE u32 sqlcipher3Get4byte(const u8*);
11910 SQLCIPHER_PRIVATE void sqlcipher3Put4byte(u8*, u32);
11911
11912 #ifdef SQLCIPHER_ENABLE_UNLOCK_NOTIFY
11913 SQLCIPHER_PRIVATE   void sqlcipher3ConnectionBlocked(sqlcipher3 *, sqlcipher3 *);
11914 SQLCIPHER_PRIVATE   void sqlcipher3ConnectionUnlocked(sqlcipher3 *db);
11915 SQLCIPHER_PRIVATE   void sqlcipher3ConnectionClosed(sqlcipher3 *db);
11916 #else
11917   #define sqlcipher3ConnectionBlocked(x,y)
11918   #define sqlcipher3ConnectionUnlocked(x)
11919   #define sqlcipher3ConnectionClosed(x)
11920 #endif
11921
11922 #ifdef SQLCIPHER_DEBUG
11923 SQLCIPHER_PRIVATE   void sqlcipher3ParserTrace(FILE*, char *);
11924 #endif
11925
11926 /*
11927 ** If the SQLCIPHER_ENABLE IOTRACE exists then the global variable
11928 ** sqlcipher3IoTrace is a pointer to a printf-like routine used to
11929 ** print I/O tracing messages. 
11930 */
11931 #ifdef SQLCIPHER_ENABLE_IOTRACE
11932 # define IOTRACE(A)  if( sqlcipher3IoTrace ){ sqlcipher3IoTrace A; }
11933 SQLCIPHER_PRIVATE   void sqlcipher3VdbeIOTraceSql(Vdbe*);
11934 SQLCIPHER_PRIVATE void (*sqlcipher3IoTrace)(const char*,...);
11935 #else
11936 # define IOTRACE(A)
11937 # define sqlcipher3VdbeIOTraceSql(X)
11938 #endif
11939
11940 /*
11941 ** These routines are available for the mem2.c debugging memory allocator
11942 ** only.  They are used to verify that different "types" of memory
11943 ** allocations are properly tracked by the system.
11944 **
11945 ** sqlcipher3MemdebugSetType() sets the "type" of an allocation to one of
11946 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
11947 ** a single bit set.
11948 **
11949 ** sqlcipher3MemdebugHasType() returns true if any of the bits in its second
11950 ** argument match the type set by the previous sqlcipher3MemdebugSetType().
11951 ** sqlcipher3MemdebugHasType() is intended for use inside assert() statements.
11952 **
11953 ** sqlcipher3MemdebugNoType() returns true if none of the bits in its second
11954 ** argument match the type set by the previous sqlcipher3MemdebugSetType().
11955 **
11956 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
11957 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
11958 ** it might have been allocated by lookaside, except the allocation was
11959 ** too large or lookaside was already full.  It is important to verify
11960 ** that allocations that might have been satisfied by lookaside are not
11961 ** passed back to non-lookaside free() routines.  Asserts such as the
11962 ** example above are placed on the non-lookaside free() routines to verify
11963 ** this constraint. 
11964 **
11965 ** All of this is no-op for a production build.  It only comes into
11966 ** play when the SQLCIPHER_MEMDEBUG compile-time option is used.
11967 */
11968 #ifdef SQLCIPHER_MEMDEBUG
11969 SQLCIPHER_PRIVATE   void sqlcipher3MemdebugSetType(void*,u8);
11970 SQLCIPHER_PRIVATE   int sqlcipher3MemdebugHasType(void*,u8);
11971 SQLCIPHER_PRIVATE   int sqlcipher3MemdebugNoType(void*,u8);
11972 #else
11973 # define sqlcipher3MemdebugSetType(X,Y)  /* no-op */
11974 # define sqlcipher3MemdebugHasType(X,Y)  1
11975 # define sqlcipher3MemdebugNoType(X,Y)   1
11976 #endif
11977 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
11978 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
11979 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
11980 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
11981 #define MEMTYPE_DB         0x10  /* Uses sqlcipher3DbMalloc, not sqlcipher_malloc */
11982
11983 #endif /* _SQLCIPHERINT_H_ */
11984
11985 /************** End of sqlcipherInt.h *******************************************/
11986 /************** Begin file crypto.c ******************************************/
11987 /* 
11988 ** SQLCipher
11989 ** crypto.c developed by Stephen Lombardo (Zetetic LLC) 
11990 ** sjlombardo at zetetic dot net
11991 ** http://zetetic.net
11992 ** 
11993 ** Copyright (c) 2009, ZETETIC LLC
11994 ** All rights reserved.
11995 ** 
11996 ** Redistribution and use in source and binary forms, with or without
11997 ** modification, are permitted provided that the following conditions are met:
11998 **     * Redistributions of source code must retain the above copyright
11999 **       notice, this list of conditions and the following disclaimer.
12000 **     * Redistributions in binary form must reproduce the above copyright
12001 **       notice, this list of conditions and the following disclaimer in the
12002 **       documentation and/or other materials provided with the distribution.
12003 **     * Neither the name of the ZETETIC LLC nor the
12004 **       names of its contributors may be used to endorse or promote products
12005 **       derived from this software without specific prior written permission.
12006 ** 
12007 ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
12008 ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
12009 ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
12010 ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
12011 ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
12012 ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
12013 ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
12014 ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12015 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
12016 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12017 **  
12018 */
12019 /* BEGIN CRYPTO */
12020 #ifdef SQLCIPHER_HAS_CODEC
12021
12022 /* #include <assert.h> */
12023 /************** Include btreeInt.h in the middle of crypto.c *****************/
12024 /************** Begin file btreeInt.h ****************************************/
12025 /*
12026 ** 2004 April 6
12027 **
12028 ** The author disclaims copyright to this source code.  In place of
12029 ** a legal notice, here is a blessing:
12030 **
12031 **    May you do good and not evil.
12032 **    May you find forgiveness for yourself and forgive others.
12033 **    May you share freely, never taking more than you give.
12034 **
12035 *************************************************************************
12036 ** This file implements a external (disk-based) database using BTrees.
12037 ** For a detailed discussion of BTrees, refer to
12038 **
12039 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
12040 **     "Sorting And Searching", pages 473-480. Addison-Wesley
12041 **     Publishing Company, Reading, Massachusetts.
12042 **
12043 ** The basic idea is that each page of the file contains N database
12044 ** entries and N+1 pointers to subpages.
12045 **
12046 **   ----------------------------------------------------------------
12047 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
12048 **   ----------------------------------------------------------------
12049 **
12050 ** All of the keys on the page that Ptr(0) points to have values less
12051 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
12052 ** values greater than Key(0) and less than Key(1).  All of the keys
12053 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
12054 ** so forth.
12055 **
12056 ** Finding a particular key requires reading O(log(M)) pages from the 
12057 ** disk where M is the number of entries in the tree.
12058 **
12059 ** In this implementation, a single file can hold one or more separate 
12060 ** BTrees.  Each BTree is identified by the index of its root page.  The
12061 ** key and data for any entry are combined to form the "payload".  A
12062 ** fixed amount of payload can be carried directly on the database
12063 ** page.  If the payload is larger than the preset amount then surplus
12064 ** bytes are stored on overflow pages.  The payload for an entry
12065 ** and the preceding pointer are combined to form a "Cell".  Each 
12066 ** page has a small header which contains the Ptr(N) pointer and other
12067 ** information such as the size of key and data.
12068 **
12069 ** FORMAT DETAILS
12070 **
12071 ** The file is divided into pages.  The first page is called page 1,
12072 ** the second is page 2, and so forth.  A page number of zero indicates
12073 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
12074 ** Each page can be either a btree page, a freelist page, an overflow
12075 ** page, or a pointer-map page.
12076 **
12077 ** The first page is always a btree page.  The first 100 bytes of the first
12078 ** page contain a special header (the "file header") that describes the file.
12079 ** The format of the file header is as follows:
12080 **
12081 **   OFFSET   SIZE    DESCRIPTION
12082 **      0      16     Header string: "SQLite format 3\000"
12083 **     16       2     Page size in bytes.  
12084 **     18       1     File format write version
12085 **     19       1     File format read version
12086 **     20       1     Bytes of unused space at the end of each page
12087 **     21       1     Max embedded payload fraction
12088 **     22       1     Min embedded payload fraction
12089 **     23       1     Min leaf payload fraction
12090 **     24       4     File change counter
12091 **     28       4     Reserved for future use
12092 **     32       4     First freelist page
12093 **     36       4     Number of freelist pages in the file
12094 **     40      60     15 4-byte meta values passed to higher layers
12095 **
12096 **     40       4     Schema cookie
12097 **     44       4     File format of schema layer
12098 **     48       4     Size of page cache
12099 **     52       4     Largest root-page (auto/incr_vacuum)
12100 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
12101 **     60       4     User version
12102 **     64       4     Incremental vacuum mode
12103 **     68       4     unused
12104 **     72       4     unused
12105 **     76       4     unused
12106 **
12107 ** All of the integer values are big-endian (most significant byte first).
12108 **
12109 ** The file change counter is incremented when the database is changed
12110 ** This counter allows other processes to know when the file has changed
12111 ** and thus when they need to flush their cache.
12112 **
12113 ** The max embedded payload fraction is the amount of the total usable
12114 ** space in a page that can be consumed by a single cell for standard
12115 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
12116 ** is to limit the maximum cell size so that at least 4 cells will fit
12117 ** on one page.  Thus the default max embedded payload fraction is 64.
12118 **
12119 ** If the payload for a cell is larger than the max payload, then extra
12120 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
12121 ** as many bytes as possible are moved into the overflow pages without letting
12122 ** the cell size drop below the min embedded payload fraction.
12123 **
12124 ** The min leaf payload fraction is like the min embedded payload fraction
12125 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
12126 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
12127 ** not specified in the header.
12128 **
12129 ** Each btree pages is divided into three sections:  The header, the
12130 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
12131 ** file header that occurs before the page header.
12132 **
12133 **      |----------------|
12134 **      | file header    |   100 bytes.  Page 1 only.
12135 **      |----------------|
12136 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
12137 **      |----------------|
12138 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
12139 **      | array          |   |  Grows downward
12140 **      |                |   v
12141 **      |----------------|
12142 **      | unallocated    |
12143 **      | space          |
12144 **      |----------------|   ^  Grows upwards
12145 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
12146 **      | area           |   |  and free space fragments.
12147 **      |----------------|
12148 **
12149 ** The page headers looks like this:
12150 **
12151 **   OFFSET   SIZE     DESCRIPTION
12152 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
12153 **      1       2      byte offset to the first freeblock
12154 **      3       2      number of cells on this page
12155 **      5       2      first byte of the cell content area
12156 **      7       1      number of fragmented free bytes
12157 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
12158 **
12159 ** The flags define the format of this btree page.  The leaf flag means that
12160 ** this page has no children.  The zerodata flag means that this page carries
12161 ** only keys and no data.  The intkey flag means that the key is a integer
12162 ** which is stored in the key size entry of the cell header rather than in
12163 ** the payload area.
12164 **
12165 ** The cell pointer array begins on the first byte after the page header.
12166 ** The cell pointer array contains zero or more 2-byte numbers which are
12167 ** offsets from the beginning of the page to the cell content in the cell
12168 ** content area.  The cell pointers occur in sorted order.  The system strives
12169 ** to keep free space after the last cell pointer so that new cells can
12170 ** be easily added without having to defragment the page.
12171 **
12172 ** Cell content is stored at the very end of the page and grows toward the
12173 ** beginning of the page.
12174 **
12175 ** Unused space within the cell content area is collected into a linked list of
12176 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
12177 ** to the first freeblock is given in the header.  Freeblocks occur in
12178 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
12179 ** any group of 3 or fewer unused bytes in the cell content area cannot
12180 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
12181 ** a fragment.  The total number of bytes in all fragments is recorded.
12182 ** in the page header at offset 7.
12183 **
12184 **    SIZE    DESCRIPTION
12185 **      2     Byte offset of the next freeblock
12186 **      2     Bytes in this freeblock
12187 **
12188 ** Cells are of variable length.  Cells are stored in the cell content area at
12189 ** the end of the page.  Pointers to the cells are in the cell pointer array
12190 ** that immediately follows the page header.  Cells is not necessarily
12191 ** contiguous or in order, but cell pointers are contiguous and in order.
12192 **
12193 ** Cell content makes use of variable length integers.  A variable
12194 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
12195 ** byte are used.  The integer consists of all bytes that have bit 8 set and
12196 ** the first byte with bit 8 clear.  The most significant byte of the integer
12197 ** appears first.  A variable-length integer may not be more than 9 bytes long.
12198 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
12199 ** allows a 64-bit integer to be encoded in 9 bytes.
12200 **
12201 **    0x00                      becomes  0x00000000
12202 **    0x7f                      becomes  0x0000007f
12203 **    0x81 0x00                 becomes  0x00000080
12204 **    0x82 0x00                 becomes  0x00000100
12205 **    0x80 0x7f                 becomes  0x0000007f
12206 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
12207 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
12208 **
12209 ** Variable length integers are used for rowids and to hold the number of
12210 ** bytes of key and data in a btree cell.
12211 **
12212 ** The content of a cell looks like this:
12213 **
12214 **    SIZE    DESCRIPTION
12215 **      4     Page number of the left child. Omitted if leaf flag is set.
12216 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
12217 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
12218 **      *     Payload
12219 **      4     First page of the overflow chain.  Omitted if no overflow
12220 **
12221 ** Overflow pages form a linked list.  Each page except the last is completely
12222 ** filled with data (pagesize - 4 bytes).  The last page can have as little
12223 ** as 1 byte of data.
12224 **
12225 **    SIZE    DESCRIPTION
12226 **      4     Page number of next overflow page
12227 **      *     Data
12228 **
12229 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
12230 ** file header points to the first in a linked list of trunk page.  Each trunk
12231 ** page points to multiple leaf pages.  The content of a leaf page is
12232 ** unspecified.  A trunk page looks like this:
12233 **
12234 **    SIZE    DESCRIPTION
12235 **      4     Page number of next trunk page
12236 **      4     Number of leaf pointers on this page
12237 **      *     zero or more pages numbers of leaves
12238 */
12239
12240
12241 /* The following value is the maximum cell size assuming a maximum page
12242 ** size give above.
12243 */
12244 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
12245
12246 /* The maximum number of cells on a single page of the database.  This
12247 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
12248 ** plus 2 bytes for the index to the cell in the page header).  Such
12249 ** small cells will be rare, but they are possible.
12250 */
12251 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
12252
12253 /* Forward declarations */
12254 typedef struct MemPage MemPage;
12255 typedef struct BtLock BtLock;
12256
12257 /*
12258 ** This is a magic string that appears at the beginning of every
12259 ** SQLite database in order to identify the file as a real database.
12260 **
12261 ** You can change this value at compile-time by specifying a
12262 ** -DSQLCIPHER_FILE_HEADER="..." on the compiler command-line.  The
12263 ** header must be exactly 16 bytes including the zero-terminator so
12264 ** the string itself should be 15 characters long.  If you change
12265 ** the header, then your custom library will not be able to read 
12266 ** databases generated by the standard tools and the standard tools
12267 ** will not be able to read databases created by your custom library.
12268 */
12269 #ifndef SQLCIPHER_FILE_HEADER /* 123456789 123456 */
12270 #  define SQLCIPHER_FILE_HEADER "SQLite format 3"
12271 #endif
12272
12273 /*
12274 ** Page type flags.  An ORed combination of these flags appear as the
12275 ** first byte of on-disk image of every BTree page.
12276 */
12277 #define PTF_INTKEY    0x01
12278 #define PTF_ZERODATA  0x02
12279 #define PTF_LEAFDATA  0x04
12280 #define PTF_LEAF      0x08
12281
12282 /*
12283 ** As each page of the file is loaded into memory, an instance of the following
12284 ** structure is appended and initialized to zero.  This structure stores
12285 ** information about the page that is decoded from the raw file page.
12286 **
12287 ** The pParent field points back to the parent page.  This allows us to
12288 ** walk up the BTree from any leaf to the root.  Care must be taken to
12289 ** unref() the parent page pointer when this page is no longer referenced.
12290 ** The pageDestructor() routine handles that chore.
12291 **
12292 ** Access to all fields of this structure is controlled by the mutex
12293 ** stored in MemPage.pBt->mutex.
12294 */
12295 struct MemPage {
12296   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
12297   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
12298   u8 intKey;           /* True if intkey flag is set */
12299   u8 leaf;             /* True if leaf flag is set */
12300   u8 hasData;          /* True if this page stores data */
12301   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
12302   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
12303   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
12304   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
12305   u16 cellOffset;      /* Index in aData of first cell pointer */
12306   u16 nFree;           /* Number of free bytes on the page */
12307   u16 nCell;           /* Number of cells on this page, local and ovfl */
12308   u16 maskPage;        /* Mask for page offset */
12309   struct _OvflCell {   /* Cells that will not fit on aData[] */
12310     u8 *pCell;          /* Pointers to the body of the overflow cell */
12311     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
12312   } aOvfl[5];
12313   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
12314   u8 *aData;           /* Pointer to disk image of the page data */
12315   DbPage *pDbPage;     /* Pager page handle */
12316   Pgno pgno;           /* Page number for this page */
12317 };
12318
12319 /*
12320 ** The in-memory image of a disk page has the auxiliary information appended
12321 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
12322 ** that extra information.
12323 */
12324 #define EXTRA_SIZE sizeof(MemPage)
12325
12326 /*
12327 ** A linked list of the following structures is stored at BtShared.pLock.
12328 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
12329 ** is opened on the table with root page BtShared.iTable. Locks are removed
12330 ** from this list when a transaction is committed or rolled back, or when
12331 ** a btree handle is closed.
12332 */
12333 struct BtLock {
12334   Btree *pBtree;        /* Btree handle holding this lock */
12335   Pgno iTable;          /* Root page of table */
12336   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
12337   BtLock *pNext;        /* Next in BtShared.pLock list */
12338 };
12339
12340 /* Candidate values for BtLock.eLock */
12341 #define READ_LOCK     1
12342 #define WRITE_LOCK    2
12343
12344 /* A Btree handle
12345 **
12346 ** A database connection contains a pointer to an instance of
12347 ** this object for every database file that it has open.  This structure
12348 ** is opaque to the database connection.  The database connection cannot
12349 ** see the internals of this structure and only deals with pointers to
12350 ** this structure.
12351 **
12352 ** For some database files, the same underlying database cache might be 
12353 ** shared between multiple connections.  In that case, each connection
12354 ** has it own instance of this object.  But each instance of this object
12355 ** points to the same BtShared object.  The database cache and the
12356 ** schema associated with the database file are all contained within
12357 ** the BtShared object.
12358 **
12359 ** All fields in this structure are accessed under sqlcipher3.mutex.
12360 ** The pBt pointer itself may not be changed while there exists cursors 
12361 ** in the referenced BtShared that point back to this Btree since those
12362 ** cursors have to go through this Btree to find their BtShared and
12363 ** they often do so without holding sqlcipher3.mutex.
12364 */
12365 struct Btree {
12366   sqlcipher3 *db;       /* The database connection holding this btree */
12367   BtShared *pBt;     /* Sharable content of this btree */
12368   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
12369   u8 sharable;       /* True if we can share pBt with another db */
12370   u8 locked;         /* True if db currently has pBt locked */
12371   int wantToLock;    /* Number of nested calls to sqlcipher3BtreeEnter() */
12372   int nBackup;       /* Number of backup operations reading this btree */
12373   Btree *pNext;      /* List of other sharable Btrees from the same db */
12374   Btree *pPrev;      /* Back pointer of the same list */
12375 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
12376   BtLock lock;       /* Object used to lock page 1 */
12377 #endif
12378 };
12379
12380 /*
12381 ** Btree.inTrans may take one of the following values.
12382 **
12383 ** If the shared-data extension is enabled, there may be multiple users
12384 ** of the Btree structure. At most one of these may open a write transaction,
12385 ** but any number may have active read transactions.
12386 */
12387 #define TRANS_NONE  0
12388 #define TRANS_READ  1
12389 #define TRANS_WRITE 2
12390
12391 /*
12392 ** An instance of this object represents a single database file.
12393 ** 
12394 ** A single database file can be in use as the same time by two
12395 ** or more database connections.  When two or more connections are
12396 ** sharing the same database file, each connection has it own
12397 ** private Btree object for the file and each of those Btrees points
12398 ** to this one BtShared object.  BtShared.nRef is the number of
12399 ** connections currently sharing this database file.
12400 **
12401 ** Fields in this structure are accessed under the BtShared.mutex
12402 ** mutex, except for nRef and pNext which are accessed under the
12403 ** global SQLCIPHER_MUTEX_STATIC_MASTER mutex.  The pPager field
12404 ** may not be modified once it is initially set as long as nRef>0.
12405 ** The pSchema field may be set once under BtShared.mutex and
12406 ** thereafter is unchanged as long as nRef>0.
12407 **
12408 ** isPending:
12409 **
12410 **   If a BtShared client fails to obtain a write-lock on a database
12411 **   table (because there exists one or more read-locks on the table),
12412 **   the shared-cache enters 'pending-lock' state and isPending is
12413 **   set to true.
12414 **
12415 **   The shared-cache leaves the 'pending lock' state when either of
12416 **   the following occur:
12417 **
12418 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
12419 **     2) The number of locks held by other connections drops to zero.
12420 **
12421 **   while in the 'pending-lock' state, no connection may start a new
12422 **   transaction.
12423 **
12424 **   This feature is included to help prevent writer-starvation.
12425 */
12426 struct BtShared {
12427   Pager *pPager;        /* The page cache */
12428   sqlcipher3 *db;          /* Database connection currently using this Btree */
12429   BtCursor *pCursor;    /* A list of all open cursors */
12430   MemPage *pPage1;      /* First page of the database */
12431   u8 readOnly;          /* True if the underlying file is readonly */
12432   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
12433   u8 secureDelete;      /* True if secure_delete is enabled */
12434   u8 initiallyEmpty;    /* Database is empty at start of transaction */
12435   u8 openFlags;         /* Flags to sqlcipher3BtreeOpen() */
12436 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
12437   u8 autoVacuum;        /* True if auto-vacuum is enabled */
12438   u8 incrVacuum;        /* True if incr-vacuum is enabled */
12439 #endif
12440   u8 inTransaction;     /* Transaction state */
12441   u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
12442   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
12443   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
12444   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
12445   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
12446   u32 pageSize;         /* Total number of bytes on a page */
12447   u32 usableSize;       /* Number of usable bytes on each page */
12448   int nTransaction;     /* Number of open transactions (read + write) */
12449   u32 nPage;            /* Number of pages in the database */
12450   void *pSchema;        /* Pointer to space allocated by sqlcipher3BtreeSchema() */
12451   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
12452   sqlcipher3_mutex *mutex; /* Non-recursive mutex required to access this object */
12453   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
12454 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
12455   int nRef;             /* Number of references to this structure */
12456   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
12457   BtLock *pLock;        /* List of locks held on this shared-btree struct */
12458   Btree *pWriter;       /* Btree with currently open write transaction */
12459   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
12460   u8 isPending;         /* If waiting for read-locks to clear */
12461 #endif
12462   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
12463 };
12464
12465 /*
12466 ** An instance of the following structure is used to hold information
12467 ** about a cell.  The parseCellPtr() function fills in this structure
12468 ** based on information extract from the raw disk page.
12469 */
12470 typedef struct CellInfo CellInfo;
12471 struct CellInfo {
12472   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
12473   u8 *pCell;     /* Pointer to the start of cell content */
12474   u32 nData;     /* Number of bytes of data */
12475   u32 nPayload;  /* Total amount of payload */
12476   u16 nHeader;   /* Size of the cell content header in bytes */
12477   u16 nLocal;    /* Amount of payload held locally */
12478   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
12479   u16 nSize;     /* Size of the cell content on the main b-tree page */
12480 };
12481
12482 /*
12483 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
12484 ** this will be declared corrupt. This value is calculated based on a
12485 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
12486 ** root-node and 3 for all other internal nodes.
12487 **
12488 ** If a tree that appears to be taller than this is encountered, it is
12489 ** assumed that the database is corrupt.
12490 */
12491 #define BTCURSOR_MAX_DEPTH 20
12492
12493 /*
12494 ** A cursor is a pointer to a particular entry within a particular
12495 ** b-tree within a database file.
12496 **
12497 ** The entry is identified by its MemPage and the index in
12498 ** MemPage.aCell[] of the entry.
12499 **
12500 ** A single database file can shared by two more database connections,
12501 ** but cursors cannot be shared.  Each cursor is associated with a
12502 ** particular database connection identified BtCursor.pBtree.db.
12503 **
12504 ** Fields in this structure are accessed under the BtShared.mutex
12505 ** found at self->pBt->mutex. 
12506 */
12507 struct BtCursor {
12508   Btree *pBtree;            /* The Btree to which this cursor belongs */
12509   BtShared *pBt;            /* The BtShared this cursor points to */
12510   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
12511   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
12512   Pgno pgnoRoot;            /* The root page of this tree */
12513   sqlcipher3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
12514   CellInfo info;            /* A parse of the cell we are pointing at */
12515   i64 nKey;        /* Size of pKey, or last integer key */
12516   void *pKey;      /* Saved key that was cursor's last known position */
12517   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
12518   u8 wrFlag;                /* True if writable */
12519   u8 atLast;                /* Cursor pointing to the last entry */
12520   u8 validNKey;             /* True if info.nKey is valid */
12521   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
12522 #ifndef SQLCIPHER_OMIT_INCRBLOB
12523   Pgno *aOverflow;          /* Cache of overflow page locations */
12524   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
12525 #endif
12526   i16 iPage;                            /* Index of current page in apPage */
12527   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
12528   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
12529 };
12530
12531 /*
12532 ** Potential values for BtCursor.eState.
12533 **
12534 ** CURSOR_VALID:
12535 **   Cursor points to a valid entry. getPayload() etc. may be called.
12536 **
12537 ** CURSOR_INVALID:
12538 **   Cursor does not point to a valid entry. This can happen (for example) 
12539 **   because the table is empty or because BtreeCursorFirst() has not been
12540 **   called.
12541 **
12542 ** CURSOR_REQUIRESEEK:
12543 **   The table that this cursor was opened on still exists, but has been 
12544 **   modified since the cursor was last used. The cursor position is saved
12545 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
12546 **   this state, restoreCursorPosition() can be called to attempt to
12547 **   seek the cursor to the saved position.
12548 **
12549 ** CURSOR_FAULT:
12550 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
12551 **   on a different connection that shares the BtShared cache with this
12552 **   cursor.  The error has left the cache in an inconsistent state.
12553 **   Do nothing else with this cursor.  Any attempt to use the cursor
12554 **   should return the error code stored in BtCursor.skip
12555 */
12556 #define CURSOR_INVALID           0
12557 #define CURSOR_VALID             1
12558 #define CURSOR_REQUIRESEEK       2
12559 #define CURSOR_FAULT             3
12560
12561 /* 
12562 ** The database page the PENDING_BYTE occupies. This page is never used.
12563 */
12564 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
12565
12566 /*
12567 ** These macros define the location of the pointer-map entry for a 
12568 ** database page. The first argument to each is the number of usable
12569 ** bytes on each page of the database (often 1024). The second is the
12570 ** page number to look up in the pointer map.
12571 **
12572 ** PTRMAP_PAGENO returns the database page number of the pointer-map
12573 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
12574 ** the offset of the requested map entry.
12575 **
12576 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
12577 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
12578 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
12579 ** this test.
12580 */
12581 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
12582 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
12583 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
12584
12585 /*
12586 ** The pointer map is a lookup table that identifies the parent page for
12587 ** each child page in the database file.  The parent page is the page that
12588 ** contains a pointer to the child.  Every page in the database contains
12589 ** 0 or 1 parent pages.  (In this context 'database page' refers
12590 ** to any page that is not part of the pointer map itself.)  Each pointer map
12591 ** entry consists of a single byte 'type' and a 4 byte parent page number.
12592 ** The PTRMAP_XXX identifiers below are the valid types.
12593 **
12594 ** The purpose of the pointer map is to facility moving pages from one
12595 ** position in the file to another as part of autovacuum.  When a page
12596 ** is moved, the pointer in its parent must be updated to point to the
12597 ** new location.  The pointer map is used to locate the parent page quickly.
12598 **
12599 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
12600 **                  used in this case.
12601 **
12602 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
12603 **                  is not used in this case.
12604 **
12605 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
12606 **                   overflow pages. The page number identifies the page that
12607 **                   contains the cell with a pointer to this overflow page.
12608 **
12609 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
12610 **                   overflow pages. The page-number identifies the previous
12611 **                   page in the overflow page list.
12612 **
12613 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
12614 **               identifies the parent page in the btree.
12615 */
12616 #define PTRMAP_ROOTPAGE 1
12617 #define PTRMAP_FREEPAGE 2
12618 #define PTRMAP_OVERFLOW1 3
12619 #define PTRMAP_OVERFLOW2 4
12620 #define PTRMAP_BTREE 5
12621
12622 /* A bunch of assert() statements to check the transaction state variables
12623 ** of handle p (type Btree*) are internally consistent.
12624 */
12625 #define btreeIntegrity(p) \
12626   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
12627   assert( p->pBt->inTransaction>=p->inTrans ); 
12628
12629
12630 /*
12631 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
12632 ** if the database supports auto-vacuum or not. Because it is used
12633 ** within an expression that is an argument to another macro 
12634 ** (sqlcipherMallocRaw), it is not possible to use conditional compilation.
12635 ** So, this macro is defined instead.
12636 */
12637 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
12638 #define ISAUTOVACUUM (pBt->autoVacuum)
12639 #else
12640 #define ISAUTOVACUUM 0
12641 #endif
12642
12643
12644 /*
12645 ** This structure is passed around through all the sanity checking routines
12646 ** in order to keep track of some global state information.
12647 */
12648 typedef struct IntegrityCk IntegrityCk;
12649 struct IntegrityCk {
12650   BtShared *pBt;    /* The tree being checked out */
12651   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
12652   Pgno nPage;       /* Number of pages in the database */
12653   int *anRef;       /* Number of times each page is referenced */
12654   int mxErr;        /* Stop accumulating errors when this reaches zero */
12655   int nErr;         /* Number of messages written to zErrMsg so far */
12656   int mallocFailed; /* A memory allocation error has occurred */
12657   StrAccum errMsg;  /* Accumulate the error message text here */
12658 };
12659
12660 /*
12661 ** Read or write a two- and four-byte big-endian integer values.
12662 */
12663 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
12664 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
12665 #define get4byte sqlcipher3Get4byte
12666 #define put4byte sqlcipher3Put4byte
12667
12668 /************** End of btreeInt.h ********************************************/
12669 /************** Continuing where we left off in crypto.c *********************/
12670 /************** Include crypto.h in the middle of crypto.c *******************/
12671 /************** Begin file crypto.h ******************************************/
12672 /* 
12673 ** SQLCipher
12674 ** crypto.h developed by Stephen Lombardo (Zetetic LLC) 
12675 ** sjlombardo at zetetic dot net
12676 ** http://zetetic.net
12677 ** 
12678 ** Copyright (c) 2008, ZETETIC LLC
12679 ** All rights reserved.
12680 ** 
12681 ** Redistribution and use in source and binary forms, with or without
12682 ** modification, are permitted provided that the following conditions are met:
12683 **     * Redistributions of source code must retain the above copyright
12684 **       notice, this list of conditions and the following disclaimer.
12685 **     * Redistributions in binary form must reproduce the above copyright
12686 **       notice, this list of conditions and the following disclaimer in the
12687 **       documentation and/or other materials provided with the distribution.
12688 **     * Neither the name of the ZETETIC LLC nor the
12689 **       names of its contributors may be used to endorse or promote products
12690 **       derived from this software without specific prior written permission.
12691 ** 
12692 ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
12693 ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
12694 ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
12695 ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
12696 ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
12697 ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
12698 ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
12699 ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12700 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
12701 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12702 **  
12703 */
12704 /* BEGIN CRYPTO */
12705 #ifdef SQLCIPHER_HAS_CODEC
12706 #ifndef CRYPTO_H
12707 #define CRYPTO_H
12708
12709 #define FILE_HEADER_SZ 16
12710
12711 #ifndef CIPHER
12712 #define CIPHER "aes-256-cbc"
12713 #endif
12714
12715 #define CIPHER_DECRYPT 0
12716 #define CIPHER_ENCRYPT 1
12717
12718 #define CIPHER_READ_CTX 0
12719 #define CIPHER_WRITE_CTX 1
12720 #define CIPHER_READWRITE_CTX 2
12721
12722 #ifndef PBKDF2_ITER
12723 #define PBKDF2_ITER 4000
12724 #endif
12725
12726 #ifndef DEFAULT_USE_HMAC
12727 #define DEFAULT_USE_HMAC 1
12728 #endif
12729
12730 /* by default, sqlcipher will use a reduced number of iterations to generate
12731    the HMAC key / or transform a raw cipher key 
12732    */
12733 #ifndef FAST_PBKDF2_ITER
12734 #define FAST_PBKDF2_ITER 2
12735 #endif
12736
12737 /* this if a fixed random array that will be xor'd with the database salt to ensure that the
12738    salt passed to the HMAC key derivation function is not the same as that used to derive
12739    the encryption key. This can be overridden at compile time but it will make the resulting
12740    binary incompatible with the default builds when using HMAC. A future version of SQLcipher
12741    will likely allow this to be defined at runtime via pragma */ 
12742 #ifndef HMAC_SALT_MASK
12743 #define HMAC_SALT_MASK 0x3a
12744 #endif
12745
12746 #ifdef CODEC_DEBUG
12747 #define CODEC_TRACE(X)  {printf X;fflush(stdout);}
12748 #else
12749 #define CODEC_TRACE(X)
12750 #endif
12751
12752
12753 /* extensions defined in pragma.c */ 
12754    
12755 SQLCIPHER_PRIVATE void sqlcipher3pager_get_codec(Pager *pPager, void **ctx);
12756 SQLCIPHER_PRIVATE int sqlcipher3pager_is_mj_pgno(Pager *pPager, Pgno pgno);
12757 SQLCIPHER_PRIVATE sqlcipher3_file *sqlcipher3Pager_get_fd(Pager *pPager);
12758 SQLCIPHER_PRIVATE void sqlcipher3pager_sqlcipher3PagerSetCodec(
12759   Pager *pPager,
12760   void *(*xCodec)(void*,void*,Pgno,int),
12761   void (*xCodecSizeChng)(void*,int,int),
12762   void (*xCodecFree)(void*),
12763   void *pCodec
12764 );
12765 /* end extensions defined in pragma.c */
12766  
12767 /*
12768 **  Simple shared routines for converting hex char strings to binary data
12769  */
12770 static int cipher_hex2int(char c) {
12771   return (c>='0' && c<='9') ? (c)-'0' :
12772          (c>='A' && c<='F') ? (c)-'A'+10 :
12773          (c>='a' && c<='f') ? (c)-'a'+10 : 0;
12774 }
12775
12776 static void cipher_hex2bin(const char *hex, int sz, unsigned char *out){
12777   int i;
12778   for(i = 0; i < sz; i += 2){
12779     out[i/2] = (cipher_hex2int(hex[i])<<4) | cipher_hex2int(hex[i+1]);
12780   }
12781 }
12782
12783 /* extensions defined in crypto_impl.c */
12784
12785 typedef struct codec_ctx codec_ctx;
12786
12787 /* utility functions */
12788 int sqlcipher_memcmp(const unsigned char *a0, const unsigned char *a1, int len);
12789 int sqlcipher_pseudorandom(void *, int);
12790 void sqlcipher_free(void *, int);
12791
12792 /* activation and initialization */
12793 void sqlcipher_activate();
12794 int sqlcipher_codec_ctx_init(codec_ctx **, Db *, Pager *, sqlcipher3_file *, const void *, int);
12795 void sqlcipher_codec_ctx_free(codec_ctx **);
12796 int sqlcipher_codec_key_derive(codec_ctx *);
12797 int sqlcipher_codec_key_copy(codec_ctx *, int);
12798
12799 /* page cipher implementation */
12800 int sqlcipher_page_cipher(codec_ctx *, int, Pgno, int, int, unsigned char *, unsigned char *);
12801
12802 /* context setters & getters */
12803 void sqlcipher_codec_ctx_set_error(codec_ctx *, int);
12804
12805 int sqlcipher_codec_ctx_set_pass(codec_ctx *, const void *, int, int);
12806 void sqlcipher_codec_get_pass(codec_ctx *, void **zKey, int *nKey);
12807
12808 int sqlcipher_codec_ctx_set_pagesize(codec_ctx *, int);
12809 int sqlcipher_codec_ctx_get_pagesize(codec_ctx *);
12810 int sqlcipher_codec_ctx_get_reservesize(codec_ctx *);
12811
12812 int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *, int, int);
12813 void* sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx);
12814
12815 int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *, int, int);
12816
12817 int sqlcipher_codec_ctx_set_cipher(codec_ctx *, const char *, int);
12818
12819 void* sqlcipher_codec_ctx_get_data(codec_ctx *);
12820
12821 void sqlcipher_exportFunc(sqlcipher3_context *, int, sqlcipher3_value **);
12822
12823 int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use);
12824 /* end extensions defined in crypto_impl.c */
12825
12826 #endif
12827 #endif
12828 /* END CRYPTO */
12829
12830 /************** End of crypto.h **********************************************/
12831 /************** Continuing where we left off in crypto.c *********************/
12832
12833 int codec_set_kdf_iter(sqlcipher3* db, int nDb, int kdf_iter, int for_ctx) {
12834   struct Db *pDb = &db->aDb[nDb];
12835   CODEC_TRACE(("codec_set_kdf_iter: entered db=%d nDb=%d kdf_iter=%d for_ctx=%d\n", db, nDb, kdf_iter, for_ctx));
12836
12837   if(pDb->pBt) {
12838     codec_ctx *ctx;
12839     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
12840     if(ctx) return sqlcipher_codec_ctx_set_kdf_iter(ctx, kdf_iter, for_ctx);
12841   }
12842   return SQLCIPHER_ERROR;
12843 }
12844
12845 int codec_set_fast_kdf_iter(sqlcipher3* db, int nDb, int kdf_iter, int for_ctx) {
12846   struct Db *pDb = &db->aDb[nDb];
12847   CODEC_TRACE(("codec_set_kdf_iter: entered db=%d nDb=%d kdf_iter=%d for_ctx=%d\n", db, nDb, kdf_iter, for_ctx));
12848
12849   if(pDb->pBt) {
12850     codec_ctx *ctx;
12851     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
12852     if(ctx) return sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, kdf_iter, for_ctx);
12853   }
12854   return SQLCIPHER_ERROR;
12855 }
12856
12857 static int codec_set_btree_to_codec_pagesize(sqlcipher3 *db, Db *pDb, codec_ctx *ctx) {
12858   int rc, page_sz, reserve_sz; 
12859
12860   page_sz = sqlcipher_codec_ctx_get_pagesize(ctx);
12861   reserve_sz = sqlcipher_codec_ctx_get_reservesize(ctx);
12862
12863   sqlcipher3_mutex_enter(db->mutex);
12864   db->nextPagesize = page_sz; 
12865   pDb->pBt->pBt->pageSizeFixed = 0; 
12866   CODEC_TRACE(("codec_set_btree_to_codec_pagesize: sqlcipher3BtreeSetPageSize() size=%d reserve=%d\n", page_sz, reserve_sz));
12867   rc = sqlcipher3BtreeSetPageSize(pDb->pBt, page_sz, reserve_sz, 0);
12868   sqlcipher3_mutex_leave(db->mutex);
12869   return rc;
12870 }
12871
12872 int codec_set_use_hmac(sqlcipher3* db, int nDb, int use) {
12873   struct Db *pDb = &db->aDb[nDb];
12874
12875   CODEC_TRACE(("codec_set_use_hmac: entered db=%d nDb=%d use=%d\n", db, nDb, use));
12876
12877   if(pDb->pBt) {
12878     int rc;
12879     codec_ctx *ctx;
12880     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
12881     if(ctx) {
12882       rc = sqlcipher_codec_ctx_set_use_hmac(ctx, use);
12883       if(rc != SQLCIPHER_OK) return rc;
12884       /* since the use of hmac has changed, the page size may also change */
12885       /* Note: before forcing the page size we need to force pageSizeFixed to 0, else  
12886              sqlcipherBtreeSetPageSize will block the change  */
12887       return codec_set_btree_to_codec_pagesize(db, pDb, ctx);
12888     }
12889   }
12890   return SQLCIPHER_ERROR;
12891 }
12892
12893 int codec_set_page_size(sqlcipher3* db, int nDb, int size) {
12894   struct Db *pDb = &db->aDb[nDb];
12895   CODEC_TRACE(("codec_set_page_size: entered db=%d nDb=%d size=%d\n", db, nDb, size));
12896
12897   if(pDb->pBt) {
12898     int rc;
12899     codec_ctx *ctx;
12900     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
12901
12902     if(ctx) {
12903       rc = sqlcipher_codec_ctx_set_pagesize(ctx, size);
12904       if(rc != SQLCIPHER_OK) return rc;
12905       return codec_set_btree_to_codec_pagesize(db, pDb, ctx);
12906     }
12907   }
12908   return SQLCIPHER_ERROR;
12909 }
12910
12911 /**
12912   * 
12913   * when for_ctx == 0 then it will change for read
12914   * when for_ctx == 1 then it will change for write
12915   * when for_ctx == 2 then it will change for both
12916   */
12917 int codec_set_cipher_name(sqlcipher3* db, int nDb, const char *cipher_name, int for_ctx) {
12918   struct Db *pDb = &db->aDb[nDb];
12919   CODEC_TRACE(("codec_set_cipher_name: entered db=%d nDb=%d cipher_name=%s for_ctx=%d\n", db, nDb, cipher_name, for_ctx));
12920
12921   if(pDb->pBt) {
12922     codec_ctx *ctx;
12923     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
12924     if(ctx) return sqlcipher_codec_ctx_set_cipher(ctx, cipher_name, for_ctx);
12925   }
12926   return SQLCIPHER_ERROR;
12927 }
12928
12929 int codec_set_pass_key(sqlcipher3* db, int nDb, const void *zKey, int nKey, int for_ctx) {
12930   struct Db *pDb = &db->aDb[nDb];
12931   CODEC_TRACE(("codec_set_pass_key: entered db=%d nDb=%d cipher_name=%s nKey=%d for_ctx=%d\n", db, nDb, zKey, nKey, for_ctx));
12932   if(pDb->pBt) {
12933     codec_ctx *ctx;
12934     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
12935     if(ctx) return sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, for_ctx);
12936   }
12937   return SQLCIPHER_ERROR;
12938
12939
12940 /*
12941  * sqlcipher3Codec can be called in multiple modes.
12942  * encrypt mode - expected to return a pointer to the 
12943  *   encrypted data without altering pData.
12944  * decrypt mode - expected to return a pointer to pData, with
12945  *   the data decrypted in the input buffer
12946  */
12947 void* sqlcipher3Codec(void *iCtx, void *data, Pgno pgno, int mode) {
12948   codec_ctx *ctx = (codec_ctx *) iCtx;
12949   int offset = 0, rc = 0;
12950   int page_sz = sqlcipher_codec_ctx_get_pagesize(ctx); 
12951   unsigned char *pData = (unsigned char *) data;
12952   void *buffer = sqlcipher_codec_ctx_get_data(ctx);
12953   void *kdf_salt = sqlcipher_codec_ctx_get_kdf_salt(ctx);
12954   CODEC_TRACE(("sqlcipher3Codec: entered pgno=%d, mode=%d, page_sz=%d\n", pgno, mode, page_sz));
12955
12956   /* call to derive keys if not present yet */
12957   if((rc = sqlcipher_codec_key_derive(ctx)) != SQLCIPHER_OK) {
12958    sqlcipher_codec_ctx_set_error(ctx, rc); 
12959    return NULL;
12960   }
12961
12962   if(pgno == 1) offset = FILE_HEADER_SZ; /* adjust starting pointers in data page for header offset on first page*/
12963
12964   CODEC_TRACE(("sqlcipher3Codec: switch mode=%d offset=%d\n",  mode, offset));
12965   switch(mode) {
12966     case 0: /* decrypt */
12967     case 2:
12968     case 3:
12969       if(pgno == 1) memcpy(buffer, SQLCIPHER_FILE_HEADER, FILE_HEADER_SZ); /* copy file header to the first 16 bytes of the page */ 
12970       rc = sqlcipher_page_cipher(ctx, CIPHER_READ_CTX, pgno, CIPHER_DECRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
12971       if(rc != SQLCIPHER_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
12972       memcpy(pData, buffer, page_sz); /* copy buffer data back to pData and return */
12973       return pData;
12974       break;
12975     case 6: /* encrypt */
12976       if(pgno == 1) memcpy(buffer, kdf_salt, FILE_HEADER_SZ); /* copy salt to output buffer */ 
12977       rc = sqlcipher_page_cipher(ctx, CIPHER_WRITE_CTX, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
12978       if(rc != SQLCIPHER_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
12979       return buffer; /* return persistent buffer data, pData remains intact */
12980       break;
12981     case 7:
12982       if(pgno == 1) memcpy(buffer, kdf_salt, FILE_HEADER_SZ); /* copy salt to output buffer */ 
12983       rc = sqlcipher_page_cipher(ctx, CIPHER_READ_CTX, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
12984       if(rc != SQLCIPHER_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
12985       return buffer; /* return persistent buffer data, pData remains intact */
12986       break;
12987     default:
12988       return pData;
12989       break;
12990   }
12991 }
12992
12993 SQLCIPHER_PRIVATE void sqlcipher3FreeCodecArg(void *pCodecArg) {
12994   codec_ctx *ctx = (codec_ctx *) pCodecArg;
12995   if(pCodecArg == NULL) return;
12996   sqlcipher_codec_ctx_free(&ctx); // wipe and free allocated memory for the context 
12997 }
12998
12999 SQLCIPHER_PRIVATE int sqlcipher3CodecAttach(sqlcipher3* db, int nDb, const void *zKey, int nKey) {
13000   struct Db *pDb = &db->aDb[nDb];
13001
13002   CODEC_TRACE(("sqlcipher3CodecAttach: entered nDb=%d zKey=%s, nKey=%d\n", nDb, zKey, nKey));
13003
13004   sqlcipher_activate();
13005
13006   if(nKey && zKey && pDb->pBt) {
13007     Pager *pPager = pDb->pBt->pBt->pPager;
13008     sqlcipher3_file *fd = sqlcipher3Pager_get_fd(pPager);
13009     codec_ctx *ctx;
13010
13011     /* point the internal codec argument against the contet to be prepared */
13012     sqlcipher_codec_ctx_init(&ctx, pDb, pDb->pBt->pBt->pPager, fd, zKey, nKey); 
13013
13014     sqlcipher3pager_sqlcipher3PagerSetCodec(sqlcipher3BtreePager(pDb->pBt), sqlcipher3Codec, NULL, sqlcipher3FreeCodecArg, (void *) ctx);
13015
13016     codec_set_btree_to_codec_pagesize(db, pDb, ctx);
13017
13018     /* if fd is null, then this is an in-memory database and
13019        we dont' want to overwrite the AutoVacuum settings
13020        if not null, then set to the default */
13021     sqlcipher3_mutex_enter(db->mutex);
13022     if(fd != NULL) { 
13023       sqlcipher3BtreeSetAutoVacuum(pDb->pBt, SQLCIPHER_DEFAULT_AUTOVACUUM);
13024     }
13025     sqlcipher3_mutex_leave(db->mutex);
13026   }
13027   return SQLCIPHER_OK;
13028 }
13029
13030 SQLCIPHER_API void sqlcipher3_activate_see(const char* in) {
13031     (void) in;
13032   /* do nothing, security enhancements are always active */
13033 }
13034
13035 SQLCIPHER_API int sqlcipher3_key(sqlcipher3 *db, const void *pKey, int nKey) {
13036   CODEC_TRACE(("sqlcipher3_key: entered db=%d pKey=%s nKey=%d\n", db, pKey, nKey));
13037   /* attach key if db and pKey are not null and nKey is > 0 */
13038   if(db && pKey && nKey) {
13039     sqlcipher3CodecAttach(db, 0, pKey, nKey); // operate only on the main db 
13040     return SQLCIPHER_OK;
13041   }
13042   return SQLCIPHER_ERROR;
13043 }
13044
13045 /* sqlcipher3_rekey 
13046 ** Given a database, this will reencrypt the database using a new key.
13047 ** There is only one possible modes of operation - to encrypt a database
13048 ** that is already encrpyted. If the database is not already encrypted
13049 ** this should do nothing
13050 ** The proposed logic for this function follows:
13051 ** 1. Determine if the database is already encryptped
13052 ** 2. If there is NOT already a key present do nothing
13053 ** 3. If there is a key present, re-encrypt the database with the new key
13054 */
13055 SQLCIPHER_API int sqlcipher3_rekey(sqlcipher3 *db, const void *pKey, int nKey) {
13056   CODEC_TRACE(("sqlcipher3_rekey: entered db=%d pKey=%s, nKey=%d\n", db, pKey, nKey));
13057   sqlcipher_activate();
13058   if(db && pKey && nKey) {
13059     struct Db *pDb = &db->aDb[0];
13060     CODEC_TRACE(("sqlcipher3_rekey: database pDb=%d\n", pDb));
13061     if(pDb->pBt) {
13062       codec_ctx *ctx;
13063       int rc, page_count;
13064       Pgno pgno;
13065       PgHdr *page;
13066       Pager *pPager = pDb->pBt->pBt->pPager;
13067
13068       sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
13069      
13070       if(ctx == NULL) { 
13071         /* there was no codec attached to this database, so this should do nothing! */ 
13072         CODEC_TRACE(("sqlcipher3_rekey: no codec attached to db, exiting\n"));
13073         return SQLCIPHER_OK;
13074       }
13075
13076       sqlcipher3_mutex_enter(db->mutex);
13077
13078       codec_set_pass_key(db, 0, pKey, nKey, CIPHER_WRITE_CTX);
13079     
13080       /* do stuff here to rewrite the database 
13081       ** 1. Create a transaction on the database
13082       ** 2. Iterate through each page, reading it and then writing it.
13083       ** 3. If that goes ok then commit and put ctx->rekey into ctx->key
13084       **    note: don't deallocate rekey since it may be used in a subsequent iteration 
13085       */
13086       rc = sqlcipher3BtreeBeginTrans(pDb->pBt, 1); /* begin write transaction */
13087       sqlcipher3PagerPagecount(pPager, &page_count);
13088       for(pgno = 1; rc == SQLCIPHER_OK && (int)pgno <= page_count; pgno++) { /* pgno's start at 1 see pager.c:pagerAcquire */
13089         if(!sqlcipher3pager_is_mj_pgno(pPager, pgno)) { /* skip this page (see pager.c:pagerAcquire for reasoning) */
13090           rc = sqlcipher3PagerGet(pPager, pgno, &page);
13091           if(rc == SQLCIPHER_OK) { /* write page see pager_incr_changecounter for example */
13092             rc = sqlcipher3PagerWrite(page);
13093             //printf("sqlcipher3PagerWrite(%d)\n", pgno);
13094             if(rc == SQLCIPHER_OK) {
13095               sqlcipher3PagerUnref(page);
13096             } 
13097           } 
13098         } 
13099       }
13100
13101       /* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */
13102       if(rc == SQLCIPHER_OK) { 
13103         CODEC_TRACE(("sqlcipher3_rekey: committing\n"));
13104         rc = sqlcipher3BtreeCommit(pDb->pBt); 
13105         sqlcipher_codec_key_copy(ctx, CIPHER_WRITE_CTX);
13106       } else {
13107         CODEC_TRACE(("sqlcipher3_rekey: rollback\n"));
13108         sqlcipher3BtreeRollback(pDb->pBt);
13109       }
13110
13111       sqlcipher3_mutex_leave(db->mutex);
13112     }
13113     return SQLCIPHER_OK;
13114   }
13115   return SQLCIPHER_ERROR;
13116 }
13117
13118 SQLCIPHER_PRIVATE void sqlcipher3CodecGetKey(sqlcipher3* db, int nDb, void **zKey, int *nKey) {
13119   struct Db *pDb = &db->aDb[nDb];
13120   CODEC_TRACE(("sqlcipher3CodecGetKey: entered db=%d, nDb=%d\n", db, nDb));
13121   
13122   if( pDb->pBt ) {
13123     codec_ctx *ctx;
13124     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
13125
13126     if(ctx) { /* if the codec has an attached codec_context user the raw key data */
13127       sqlcipher_codec_get_pass(ctx, zKey, nKey);
13128     } else {
13129       *zKey = NULL;
13130       *nKey = 0;
13131     }
13132   }
13133 }
13134
13135
13136 /* END CRYPTO */
13137 #endif
13138
13139 /************** End of crypto.c **********************************************/
13140 /************** Begin file crypto_impl.c *************************************/
13141 /* 
13142 ** SQLCipher
13143 ** crypto_impl.c developed by Stephen Lombardo (Zetetic LLC) 
13144 ** sjlombardo at zetetic dot net
13145 ** http://zetetic.net
13146 ** 
13147 ** Copyright (c) 2011, ZETETIC LLC
13148 ** All rights reserved.
13149 ** 
13150 ** Redistribution and use in source and binary forms, with or without
13151 ** modification, are permitted provided that the following conditions are met:
13152 **     * Redistributions of source code must retain the above copyright
13153 **       notice, this list of conditions and the following disclaimer.
13154 **     * Redistributions in binary form must reproduce the above copyright
13155 **       notice, this list of conditions and the following disclaimer in the
13156 **       documentation and/or other materials provided with the distribution.
13157 **     * Neither the name of the ZETETIC LLC nor the
13158 **       names of its contributors may be used to endorse or promote products
13159 **       derived from this software without specific prior written permission.
13160 ** 
13161 ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
13162 ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
13163 ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
13164 ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
13165 ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
13166 ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
13167 ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
13168 ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
13169 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
13170 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13171 **  
13172 */
13173 /* BEGIN CRYPTO */
13174 #ifdef SQLCIPHER_HAS_CODEC
13175
13176 #include <openssl/rand.h>
13177 #include <openssl/evp.h>
13178 #include <openssl/hmac.h>
13179 #ifndef OMIT_MEMLOCK
13180 #if defined(__unix__) || defined(__APPLE__) 
13181 #include <sys/mman.h>
13182 #elif defined(_WIN32)
13183 /* # include <windows.h> */
13184 #endif
13185 #endif
13186
13187 /* the default implementation of SQLCipher uses a cipher_ctx
13188    to keep track of read / write state separately. The following
13189    struct and associated functions are defined here */
13190 typedef struct {
13191   int derive_key;
13192   EVP_CIPHER *evp_cipher;
13193   EVP_CIPHER_CTX ectx;
13194   HMAC_CTX hctx;
13195   int kdf_iter;
13196   int fast_kdf_iter;
13197   int key_sz;
13198   int iv_sz;
13199   int block_sz;
13200   int pass_sz;
13201   int reserve_sz;
13202   int hmac_sz;
13203   int use_hmac;
13204   unsigned char *key;
13205   unsigned char *hmac_key;
13206   char *pass;
13207 } cipher_ctx;
13208
13209 void sqlcipher_cipher_ctx_free(cipher_ctx **);
13210 int sqlcipher_cipher_ctx_cmp(cipher_ctx *, cipher_ctx *);
13211 int sqlcipher_cipher_ctx_copy(cipher_ctx *, cipher_ctx *);
13212 int sqlcipher_cipher_ctx_init(cipher_ctx **);
13213 int sqlcipher_cipher_ctx_set_pass(cipher_ctx *, const void *, int);
13214 int sqlcipher_cipher_ctx_key_derive(codec_ctx *, cipher_ctx *);
13215
13216 /* prototype for pager HMAC function */
13217 int sqlcipher_page_hmac(cipher_ctx *, Pgno, unsigned char *, int, unsigned char *);
13218
13219 struct codec_ctx {
13220   int kdf_salt_sz;
13221   int page_sz;
13222   unsigned char *kdf_salt;
13223   unsigned char *hmac_kdf_salt;
13224   unsigned char *buffer;
13225   Btree *pBt;
13226   cipher_ctx *read_ctx;
13227   cipher_ctx *write_ctx;
13228 };
13229
13230 void sqlcipher_activate() {
13231   sqlcipher3_mutex_enter(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
13232   if(EVP_get_cipherbyname(CIPHER) == NULL) {
13233     OpenSSL_add_all_algorithms();
13234   } 
13235   sqlcipher3_mutex_leave(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
13236 }
13237
13238 /* fixed time memory comparison routine */
13239 int sqlcipher_memcmp(const unsigned char *a0, const unsigned char *a1, int len) {
13240   int i = 0, noMatch = 0;
13241
13242   for(i = 0; i < len; i++) {
13243     noMatch = (noMatch || (a0[i] != a1[i]));
13244   }
13245   
13246   return noMatch;
13247 }
13248
13249 /* generate a defined number of pseudorandom bytes */
13250 int sqlcipher_random (void *buffer, int length) {
13251   return RAND_bytes((unsigned char *)buffer, length);
13252 }
13253
13254 /**
13255   * Free and wipe memory. Uses SQLites internal sqlcipher3_free so that memory
13256   * can be countend and memory leak detection works in the tet suite. 
13257   * If ptr is not null memory will be freed. 
13258   * If sz is greater than zero, the memory will be overwritten with zero before it is freed
13259   * If sz is > 0, and not compiled with OMIT_MEMLOCK, system will attempt to unlock the
13260   * memory segment so it can be paged
13261   */
13262 void sqlcipher_free(void *ptr, int sz) {
13263   if(ptr) {
13264     if(sz > 0) {
13265       memset(ptr, 0, sz);
13266 #ifndef OMIT_MEMLOCK
13267 #if defined(__unix__) || defined(__APPLE__) 
13268       munlock(ptr, sz);
13269 #elif defined(_WIN32)
13270       VirtualUnlock(ptr, sz);
13271 #endif
13272 #endif
13273     }
13274     sqlcipher3_free(ptr);
13275   }
13276 }
13277
13278 /**
13279   * allocate memory. Uses sqlcipher's internall malloc wrapper so memory can be 
13280   * reference counted and leak detection works. Unless compiled with OMIT_MEMLOCK
13281   * attempts to lock the memory pages so sensitive information won't be swapped
13282   */
13283 void* sqlcipher_malloc(int sz) {
13284   void *ptr = sqlcipher3Malloc(sz);
13285 #ifndef OMIT_MEMLOCK
13286   if(ptr) {
13287 #if defined(__unix__) || defined(__APPLE__) 
13288     mlock(ptr, sz);
13289 #elif defined(_WIN32)
13290     VirtualLock(ptr, sz);
13291 #endif
13292   }
13293 #endif
13294   return ptr;
13295 }
13296
13297
13298 /**
13299   * Initialize a a new cipher_ctx struct. This function will allocate memory
13300   * for the cipher context and for the key
13301   * 
13302   * returns SQLCIPHER_OK if initialization was successful
13303   * returns SQLCIPHER_NOMEM if an error occured allocating memory
13304   */
13305 int sqlcipher_cipher_ctx_init(cipher_ctx **iCtx) {
13306   cipher_ctx *ctx;
13307   *iCtx = (cipher_ctx *) sqlcipher_malloc(sizeof(cipher_ctx));
13308   ctx = *iCtx;
13309   if(ctx == NULL) return SQLCIPHER_NOMEM;
13310   memset(ctx, 0, sizeof(cipher_ctx)); 
13311   ctx->key = (unsigned char *) sqlcipher_malloc(EVP_MAX_KEY_LENGTH);
13312   ctx->hmac_key = (unsigned char *) sqlcipher_malloc(EVP_MAX_KEY_LENGTH);
13313   if(ctx->key == NULL) return SQLCIPHER_NOMEM;
13314   if(ctx->hmac_key == NULL) return SQLCIPHER_NOMEM;
13315   return SQLCIPHER_OK;
13316 }
13317
13318 /**
13319   * Free and wipe memory associated with a cipher_ctx
13320   */
13321 void sqlcipher_cipher_ctx_free(cipher_ctx **iCtx) {
13322   cipher_ctx *ctx = *iCtx;
13323   CODEC_TRACE(("cipher_ctx_free: entered iCtx=%d\n", iCtx));
13324   sqlcipher_free(ctx->key, ctx->key_sz);
13325   sqlcipher_free(ctx->hmac_key, ctx->key_sz);
13326   sqlcipher_free(ctx->pass, ctx->pass_sz);
13327   sqlcipher_free(ctx, sizeof(cipher_ctx)); 
13328 }
13329
13330 /**
13331   * Compare one cipher_ctx to another.
13332   *
13333   * returns 0 if all the parameters (except the derived key data) are the same
13334   * returns 1 otherwise
13335   */
13336 int sqlcipher_cipher_ctx_cmp(cipher_ctx *c1, cipher_ctx *c2) {
13337   CODEC_TRACE(("sqlcipher_cipher_ctx_cmp: entered c1=%d c2=%d\n", c1, c2));
13338
13339   if(
13340     c1->evp_cipher == c2->evp_cipher
13341     && c1->iv_sz == c2->iv_sz
13342     && c1->kdf_iter == c2->kdf_iter
13343     && c1->fast_kdf_iter == c2->fast_kdf_iter
13344     && c1->key_sz == c2->key_sz
13345     && c1->pass_sz == c2->pass_sz
13346     && (
13347       c1->pass == c2->pass
13348       || !sqlcipher_memcmp((const unsigned char*)c1->pass,
13349                            (const unsigned char*)c2->pass,
13350                            c1->pass_sz)
13351     ) 
13352   ) return 0;
13353   return 1;
13354 }
13355
13356 /**
13357   * Copy one cipher_ctx to another. For instance, assuming that read_ctx is a 
13358   * fully initialized context, you could copy it to write_ctx and all yet data
13359   * and pass information across
13360   *
13361   * returns SQLCIPHER_OK if initialization was successful
13362   * returns SQLCIPHER_NOMEM if an error occured allocating memory
13363   */
13364 int sqlcipher_cipher_ctx_copy(cipher_ctx *target, cipher_ctx *source) {
13365   void *key = target->key; 
13366   void *hmac_key = target->hmac_key; 
13367
13368   CODEC_TRACE(("sqlcipher_cipher_ctx_copy: entered target=%d, source=%d\n", target, source));
13369   sqlcipher_free(target->pass, target->pass_sz); 
13370   memcpy(target, source, sizeof(cipher_ctx));
13371   
13372   target->key = key; //restore pointer to previously allocated key data
13373   memcpy(target->key, source->key, EVP_MAX_KEY_LENGTH);
13374
13375   target->hmac_key = hmac_key; //restore pointer to previously allocated hmac key data
13376   memcpy(target->hmac_key, source->hmac_key, EVP_MAX_KEY_LENGTH);
13377
13378   target->pass = sqlcipher_malloc(source->pass_sz);
13379   if(target->pass == NULL) return SQLCIPHER_NOMEM;
13380   memcpy(target->pass, source->pass, source->pass_sz);
13381
13382   return SQLCIPHER_OK;
13383 }
13384
13385
13386 /**
13387   * Set the raw password / key data for a cipher context
13388   * 
13389   * returns SQLCIPHER_OK if assignment was successfull
13390   * returns SQLCIPHER_NOMEM if an error occured allocating memory
13391   * returns SQLCIPHER_ERROR if the key couldn't be set because the pass was null or size was zero
13392   */
13393 int sqlcipher_cipher_ctx_set_pass(cipher_ctx *ctx, const void *zKey, int nKey) {
13394   sqlcipher_free(ctx->pass, ctx->pass_sz);
13395   ctx->pass_sz = nKey;
13396   if(zKey && nKey) {
13397     ctx->pass = sqlcipher_malloc(nKey);
13398     if(ctx->pass == NULL) return SQLCIPHER_NOMEM;
13399     memcpy(ctx->pass, zKey, nKey);
13400     return SQLCIPHER_OK;
13401   }
13402   return SQLCIPHER_ERROR;
13403 }
13404
13405 int sqlcipher_codec_ctx_set_pass(codec_ctx *ctx, const void *zKey, int nKey, int for_ctx) {
13406   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
13407   int rc;
13408
13409   if((rc = sqlcipher_cipher_ctx_set_pass(c_ctx, zKey, nKey)) != SQLCIPHER_OK) return rc; 
13410   c_ctx->derive_key = 1;
13411
13412   if(for_ctx == 2)
13413     if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLCIPHER_OK) 
13414       return rc; 
13415
13416   return SQLCIPHER_OK;
13417
13418
13419 int sqlcipher_codec_ctx_set_cipher(codec_ctx *ctx, const char *cipher_name, int for_ctx) {
13420   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
13421   int rc;
13422
13423   c_ctx->evp_cipher = (EVP_CIPHER *) EVP_get_cipherbyname(cipher_name);
13424   c_ctx->key_sz = EVP_CIPHER_key_length(c_ctx->evp_cipher);
13425   c_ctx->iv_sz = EVP_CIPHER_iv_length(c_ctx->evp_cipher);
13426   c_ctx->block_sz = EVP_CIPHER_block_size(c_ctx->evp_cipher);
13427   c_ctx->hmac_sz = EVP_MD_size(EVP_sha1());
13428   c_ctx->derive_key = 1;
13429
13430   if(for_ctx == 2)
13431     if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLCIPHER_OK)
13432       return rc; 
13433
13434   return SQLCIPHER_OK;
13435 }
13436
13437 int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *ctx, int kdf_iter, int for_ctx) {
13438   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
13439   int rc;
13440
13441   c_ctx->kdf_iter = kdf_iter;
13442   c_ctx->derive_key = 1;
13443
13444   if(for_ctx == 2)
13445     if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLCIPHER_OK)
13446       return rc; 
13447
13448   return SQLCIPHER_OK;
13449 }
13450
13451 int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *ctx, int fast_kdf_iter, int for_ctx) {
13452   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
13453   int rc;
13454
13455   c_ctx->fast_kdf_iter = fast_kdf_iter;
13456   c_ctx->derive_key = 1;
13457
13458   if(for_ctx == 2)
13459     if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLCIPHER_OK)
13460       return rc; 
13461
13462   return SQLCIPHER_OK;
13463 }
13464
13465
13466 int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use) {
13467   int reserve = EVP_MAX_IV_LENGTH; /* base reserve size will be IV only */ 
13468
13469   if(use) reserve += ctx->read_ctx->hmac_sz; /* if reserve will include hmac, update that size */
13470
13471   /* calculate the amount of reserve needed in even increments of the cipher block size */
13472
13473   reserve = ((reserve % ctx->read_ctx->block_sz) == 0) ? reserve :
13474                ((reserve / ctx->read_ctx->block_sz) + 1) * ctx->read_ctx->block_sz;  
13475
13476   CODEC_TRACE(("sqlcipher_codec_ctx_set_use_hmac: use=%d block_sz=%d md_size=%d reserve=%d\n", 
13477                 use, ctx->read_ctx->block_sz, ctx->read_ctx->hmac_sz, reserve)); 
13478
13479   ctx->write_ctx->use_hmac = ctx->read_ctx->use_hmac = use;
13480   ctx->write_ctx->reserve_sz = ctx->read_ctx->reserve_sz = reserve;
13481
13482   return SQLCIPHER_OK;
13483 }
13484
13485 void sqlcipher_codec_ctx_set_error(codec_ctx *ctx, int error) {
13486   ctx->pBt->db->errCode = error;
13487 }
13488
13489 int sqlcipher_codec_ctx_get_pagesize(codec_ctx *ctx) {
13490   return ctx->page_sz;
13491 }
13492
13493 int sqlcipher_codec_ctx_get_reservesize(codec_ctx *ctx) {
13494   return ctx->read_ctx->reserve_sz;
13495 }
13496
13497 void* sqlcipher_codec_ctx_get_data(codec_ctx *ctx) {
13498   return ctx->buffer;
13499 }
13500
13501 void* sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx) {
13502   return ctx->kdf_salt;
13503 }
13504
13505 void sqlcipher_codec_get_pass(codec_ctx *ctx, void **zKey, int *nKey) {
13506   *zKey = ctx->read_ctx->pass;
13507   *nKey = ctx->read_ctx->pass_sz;
13508 }
13509
13510 int sqlcipher_codec_ctx_set_pagesize(codec_ctx *ctx, int size) {
13511   /* attempt to free the existing page buffer */
13512   sqlcipher_free(ctx->buffer,ctx->page_sz);
13513   ctx->page_sz = size;
13514
13515   /* pre-allocate a page buffer of PageSize bytes. This will
13516      be used as a persistent buffer for encryption and decryption 
13517      operations to avoid overhead of multiple memory allocations*/
13518   ctx->buffer = sqlcipher_malloc(size);
13519   if(ctx->buffer == NULL) return SQLCIPHER_NOMEM;
13520   memset(ctx->buffer, 0, size);
13521
13522   return SQLCIPHER_OK;
13523 }
13524
13525 int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, sqlcipher3_file *fd, const void *zKey, int nKey) {
13526   int rc;
13527   codec_ctx *ctx;
13528   *iCtx = sqlcipher_malloc(sizeof(codec_ctx));
13529   ctx = *iCtx;
13530
13531   (void) pPager;
13532
13533   if(ctx == NULL) return SQLCIPHER_NOMEM;
13534
13535   memset(ctx, 0, sizeof(codec_ctx)); /* initialize all pointers and values to 0 */
13536   ctx->pBt = pDb->pBt; /* assign pointer to database btree structure */
13537
13538   /* allocate space for salt data. Then read the first 16 bytes 
13539        directly off the database file. This is the salt for the
13540        key derivation function. If we get a short read allocate
13541        a new random salt value */
13542   ctx->kdf_salt_sz = FILE_HEADER_SZ;
13543   ctx->kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz);
13544   if(ctx->kdf_salt == NULL) return SQLCIPHER_NOMEM;
13545   memset(ctx->kdf_salt, 0, ctx->kdf_salt_sz);
13546
13547   /* allocate space for separate hmac salt data. We want the
13548      HMAC derivation salt to be different than the encryption
13549      key derivation salt */
13550   ctx->hmac_kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz);
13551   if(ctx->hmac_kdf_salt == NULL) return SQLCIPHER_NOMEM;
13552
13553
13554   /*
13555      Always overwrite page size and set to the default because the first page of the database
13556      in encrypted and thus sqlcipher can't effectively determine the pagesize. this causes an issue in 
13557      cases where bytes 16 & 17 of the page header are a power of 2 as reported by John Lehman
13558   */
13559   if((rc = sqlcipher_codec_ctx_set_pagesize(ctx, SQLCIPHER_DEFAULT_PAGE_SIZE)) != SQLCIPHER_OK) return rc;
13560
13561   if((rc = sqlcipher_cipher_ctx_init(&ctx->read_ctx)) != SQLCIPHER_OK) return rc; 
13562   if((rc = sqlcipher_cipher_ctx_init(&ctx->write_ctx)) != SQLCIPHER_OK) return rc; 
13563
13564   if(fd == NULL || sqlcipher3OsRead(fd, ctx->kdf_salt, FILE_HEADER_SZ, 0) != SQLCIPHER_OK) {
13565     /* if unable to read the bytes, generate random salt */
13566     if(sqlcipher_random(ctx->kdf_salt, FILE_HEADER_SZ) != 1) return SQLCIPHER_ERROR;
13567   }
13568
13569   if((rc = sqlcipher_codec_ctx_set_cipher(ctx, CIPHER, 0)) != SQLCIPHER_OK) return rc;
13570   if((rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, PBKDF2_ITER, 0)) != SQLCIPHER_OK) return rc;
13571   if((rc = sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, FAST_PBKDF2_ITER, 0)) != SQLCIPHER_OK) return rc;
13572   if((rc = sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, 0)) != SQLCIPHER_OK) return rc;
13573
13574   /* Use HMAC signatures by default. Note that codec_set_use_hmac will implicity call
13575      codec_set_page_size to set the default */
13576   if((rc = sqlcipher_codec_ctx_set_use_hmac(ctx, DEFAULT_USE_HMAC)) != SQLCIPHER_OK) return rc;
13577
13578   if((rc = sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx)) != SQLCIPHER_OK) return rc;
13579
13580   return SQLCIPHER_OK;
13581 }
13582
13583 /**
13584   * Free and wipe memory associated with a cipher_ctx, including the allocated
13585   * read_ctx and write_ctx.
13586   */
13587 void sqlcipher_codec_ctx_free(codec_ctx **iCtx) {
13588   codec_ctx *ctx = *iCtx;
13589   CODEC_TRACE(("codec_ctx_free: entered iCtx=%d\n", iCtx));
13590   sqlcipher_free(ctx->kdf_salt, ctx->kdf_salt_sz);
13591   sqlcipher_free(ctx->hmac_kdf_salt, ctx->kdf_salt_sz);
13592   sqlcipher_free(ctx->buffer, 0);
13593   sqlcipher_cipher_ctx_free(&ctx->read_ctx);
13594   sqlcipher_cipher_ctx_free(&ctx->write_ctx);
13595   sqlcipher_free(ctx, sizeof(codec_ctx)); 
13596 }
13597
13598 int sqlcipher_page_hmac(cipher_ctx *ctx, Pgno pgno, unsigned char *in, int in_sz, unsigned char *out) {
13599   HMAC_CTX_init(&ctx->hctx);
13600   
13601   HMAC_Init_ex(&ctx->hctx, ctx->hmac_key, ctx->key_sz, EVP_sha1(), NULL);
13602
13603   /* include the encrypted page data,  initialization vector, and page number in HMAC. This will 
13604      prevent both tampering with the ciphertext, manipulation of the IV, or resequencing otherwise
13605      valid pages out of order in a database */ 
13606   HMAC_Update(&ctx->hctx, in, in_sz);
13607   HMAC_Update(&ctx->hctx, (const unsigned char*) &pgno, sizeof(Pgno));
13608   HMAC_Final(&ctx->hctx, out, NULL);
13609   HMAC_CTX_cleanup(&ctx->hctx);
13610   return SQLCIPHER_OK; 
13611 }
13612
13613 /*
13614  * ctx - codec context
13615  * pgno - page number in database
13616  * size - size in bytes of input and output buffers
13617  * mode - 1 to encrypt, 0 to decrypt
13618  * in - pointer to input bytes
13619  * out - pouter to output bytes
13620  */
13621 int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode, int page_sz, unsigned char *in, unsigned char *out) {
13622   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
13623   unsigned char *iv_in, *iv_out, *hmac_in, *hmac_out, *out_start;
13624   int tmp_csz, csz, size;
13625
13626   /* calculate some required positions into various buffers */
13627   size = page_sz - c_ctx->reserve_sz; /* adjust size to useable size and memset reserve at end of page */
13628   iv_out = out + size;
13629   iv_in = in + size;
13630
13631   /* hmac will be written immediately after the initialization vector. the remainder of the page reserve will contain
13632      random bytes. note, these pointers are only valid when use_hmac is true */
13633   hmac_in = in + size + c_ctx->iv_sz; 
13634   hmac_out = out + size + c_ctx->iv_sz;
13635   out_start = out; /* note the original position of the output buffer pointer, as out will be rewritten during encryption */
13636
13637   CODEC_TRACE(("codec_cipher:entered pgno=%d, mode=%d, size=%d\n", pgno, mode, size));
13638
13639   /* just copy raw data from in to out when key size is 0
13640    * i.e. during a rekey of a plaintext database */ 
13641   if(c_ctx->key_sz == 0) {
13642     memcpy(out, in, size);
13643     return SQLCIPHER_OK;
13644   } 
13645
13646   if(mode == CIPHER_ENCRYPT) {
13647     /* start at front of the reserve block, write random data to the end */
13648     if(sqlcipher_random(iv_out, c_ctx->reserve_sz) != 1) return SQLCIPHER_ERROR; 
13649   } else { /* CIPHER_DECRYPT */
13650     memcpy(iv_out, iv_in, c_ctx->iv_sz); /* copy the iv from the input to output buffer */
13651   } 
13652
13653   if(c_ctx->use_hmac && (mode == CIPHER_DECRYPT)) {
13654     if(sqlcipher_page_hmac(c_ctx, pgno, in, size + c_ctx->iv_sz, hmac_out) != SQLCIPHER_OK) {
13655       memset(out, 0, page_sz); 
13656       CODEC_TRACE(("codec_cipher: hmac operations failed for pgno=%d\n", pgno));
13657       return SQLCIPHER_ERROR;
13658     }
13659
13660     CODEC_TRACE(("codec_cipher: comparing hmac on in=%d out=%d hmac_sz=%d\n", hmac_in, hmac_out, c_ctx->hmac_sz));
13661     if(sqlcipher_memcmp(hmac_in, hmac_out, c_ctx->hmac_sz) != 0) {
13662       /* the hmac check failed, which means the data was tampered with or
13663          corrupted in some way. we will return an error, and zero out the page data
13664          to force an error */
13665       memset(out, 0, page_sz); 
13666       CODEC_TRACE(("codec_cipher: hmac check failed for pgno=%d\n", pgno));
13667       return SQLCIPHER_ERROR;
13668     }
13669   } 
13670
13671   EVP_CipherInit(&c_ctx->ectx, c_ctx->evp_cipher, NULL, NULL, mode);
13672   EVP_CIPHER_CTX_set_padding(&c_ctx->ectx, 0);
13673   EVP_CipherInit(&c_ctx->ectx, NULL, c_ctx->key, iv_out, mode);
13674   EVP_CipherUpdate(&c_ctx->ectx, out, &tmp_csz, in, size);
13675   csz = tmp_csz;  
13676   out += tmp_csz;
13677   EVP_CipherFinal(&c_ctx->ectx, out, &tmp_csz);
13678   csz += tmp_csz;
13679   EVP_CIPHER_CTX_cleanup(&c_ctx->ectx);
13680   assert(size == csz);
13681
13682   if(c_ctx->use_hmac && (mode == CIPHER_ENCRYPT)) {
13683     sqlcipher_page_hmac(c_ctx, pgno, out_start, size + c_ctx->iv_sz, hmac_out); 
13684   }
13685
13686   return SQLCIPHER_OK;
13687 }
13688
13689 /**
13690   * Derive an encryption key for a cipher contex key based on the raw password.
13691   *
13692   * If the raw key data is formated as x'hex' and there are exactly enough hex chars to fill
13693   * the key space (i.e 64 hex chars for a 256 bit key) then the key data will be used directly. 
13694   * 
13695   * Otherwise, a key data will be derived using PBKDF2
13696   * 
13697   * returns SQLCIPHER_OK if initialization was successful
13698   * returns SQLCIPHER_ERROR if the key could't be derived (for instance if pass is NULL or pass_sz is 0)
13699   */
13700 int sqlcipher_cipher_ctx_key_derive(codec_ctx *ctx, cipher_ctx *c_ctx) {
13701   CODEC_TRACE(("codec_key_derive: entered c_ctx->pass=%s, c_ctx->pass_sz=%d \
13702                 ctx->kdf_salt=%d ctx->kdf_salt_sz=%d c_ctx->kdf_iter=%d \
13703                 ctx->hmac_kdf_salt=%d, c_ctx->fast_kdf_iter=%d c_ctx->key_sz=%d\n", 
13704                 c_ctx->pass, c_ctx->pass_sz, ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->kdf_iter, 
13705                 ctx->hmac_kdf_salt, c_ctx->fast_kdf_iter, c_ctx->key_sz)); 
13706                 
13707
13708   if(c_ctx->pass && c_ctx->pass_sz) { // if pass is not null
13709     if (c_ctx->pass_sz == ((c_ctx->key_sz*2)+3) && sqlcipher3StrNICmp(c_ctx->pass ,"x'", 2) == 0) { 
13710       int n = c_ctx->pass_sz - 3; /* adjust for leading x' and tailing ' */
13711       const char *z = c_ctx->pass + 2; /* adjust lead offset of x' */
13712       CODEC_TRACE(("codec_key_derive: using raw key from hex\n")); 
13713       cipher_hex2bin(z, n, c_ctx->key);
13714     } else { 
13715       CODEC_TRACE(("codec_key_derive: deriving key using full PBKDF2 with %d iterations\n", c_ctx->kdf_iter)); 
13716       PKCS5_PBKDF2_HMAC_SHA1( c_ctx->pass, c_ctx->pass_sz, 
13717                               ctx->kdf_salt, ctx->kdf_salt_sz, 
13718                               c_ctx->kdf_iter, c_ctx->key_sz, c_ctx->key);
13719                               
13720     }
13721
13722     /* if this context is setup to use hmac checks, generate a seperate and different 
13723        key for HMAC. In this case, we use the output of the previous KDF as the input to 
13724        this KDF run. This ensures a distinct but predictable HMAC key. */
13725     if(c_ctx->use_hmac) {
13726       int i;
13727
13728       /* start by copying the kdf key into the hmac salt slot
13729          then XOR it with the fixed hmac salt defined at compile time
13730          this ensures that the salt passed in to derive the hmac key, while 
13731          easy to derive and publically known, is not the same as the salt used 
13732          to generate the encryption key */ 
13733       memcpy(ctx->hmac_kdf_salt, ctx->kdf_salt, ctx->kdf_salt_sz);
13734       for(i = 0; i < ctx->kdf_salt_sz; i++) {
13735         ctx->hmac_kdf_salt[i] ^= HMAC_SALT_MASK;
13736       } 
13737
13738       CODEC_TRACE(("codec_key_derive: deriving hmac key from encryption key using PBKDF2 with %d iterations\n", 
13739         c_ctx->fast_kdf_iter)); 
13740       PKCS5_PBKDF2_HMAC_SHA1( (const char*)c_ctx->key, c_ctx->key_sz, 
13741                               ctx->hmac_kdf_salt, ctx->kdf_salt_sz, 
13742                               c_ctx->fast_kdf_iter, c_ctx->key_sz, c_ctx->hmac_key); 
13743     }
13744
13745     c_ctx->derive_key = 0;
13746     return SQLCIPHER_OK;
13747   };
13748   return SQLCIPHER_ERROR;
13749 }
13750
13751 int sqlcipher_codec_key_derive(codec_ctx *ctx) {
13752   /* derive key on first use if necessary */
13753   if(ctx->read_ctx->derive_key) {
13754     if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->read_ctx) != SQLCIPHER_OK) return SQLCIPHER_ERROR;
13755   }
13756
13757   if(ctx->write_ctx->derive_key) {
13758     if(sqlcipher_cipher_ctx_cmp(ctx->write_ctx, ctx->read_ctx) == 0) {
13759       // the relevant parameters are the same, just copy read key
13760       if(sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx) != SQLCIPHER_OK) return SQLCIPHER_ERROR;
13761     } else {
13762       if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->write_ctx) != SQLCIPHER_OK) return SQLCIPHER_ERROR;
13763     }
13764   }
13765   return SQLCIPHER_OK; 
13766 }
13767
13768 int sqlcipher_codec_key_copy(codec_ctx *ctx, int source) {
13769   if(source == CIPHER_READ_CTX) { 
13770       return sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx); 
13771   } else {
13772       return sqlcipher_cipher_ctx_copy(ctx->read_ctx, ctx->write_ctx); 
13773   }
13774 }
13775
13776
13777 #ifndef OMIT_EXPORT
13778
13779 /*
13780  * Implementation of an "export" function that allows a caller
13781  * to duplicate the main database to an attached database. This is intended
13782  * as a conveneince for users who need to:
13783  * 
13784  *   1. migrate from an non-encrypted database to an encrypted database
13785  *   2. move from an encrypted database to a non-encrypted database
13786  *   3. convert beween the various flavors of encrypted databases.  
13787  *
13788  * This implementation is based heavily on the procedure and code used
13789  * in vacuum.c, but is exposed as a function that allows export to any
13790  * named attached database.
13791  */
13792
13793 /*
13794 ** Finalize a prepared statement.  If there was an error, store the
13795 ** text of the error message in *pzErrMsg.  Return the result code.
13796 ** 
13797 ** Based on vacuumFinalize from vacuum.c
13798 */
13799 static int sqlcipher_finalize(sqlcipher3 *db, sqlcipher3_stmt *pStmt, char **pzErrMsg){
13800   int rc;
13801   rc = sqlcipher3VdbeFinalize((Vdbe*)pStmt);
13802   if( rc ){
13803     sqlcipher3SetString(pzErrMsg, db, sqlcipher3_errmsg(db));
13804   }
13805   return rc;
13806 }
13807
13808 /*
13809 ** Execute zSql on database db. Return an error code.
13810 ** 
13811 ** Based on execSql from vacuum.c
13812 */
13813 static int sqlcipher_execSql(sqlcipher3 *db, char **pzErrMsg, const char *zSql){
13814   sqlcipher3_stmt *pStmt;
13815   VVA_ONLY( int rc; )
13816   if( !zSql ){
13817     return SQLCIPHER_NOMEM;
13818   }
13819   if( SQLCIPHER_OK!=sqlcipher3_prepare(db, zSql, -1, &pStmt, 0) ){
13820     sqlcipher3SetString(pzErrMsg, db, sqlcipher3_errmsg(db));
13821     return sqlcipher3_errcode(db);
13822   }
13823   VVA_ONLY( rc = ) sqlcipher3_step(pStmt);
13824   assert( rc!=SQLCIPHER_ROW );
13825   return sqlcipher_finalize(db, pStmt, pzErrMsg);
13826 }
13827
13828 /*
13829 ** Execute zSql on database db. The statement returns exactly
13830 ** one column. Execute this as SQL on the same database.
13831 ** 
13832 ** Based on execExecSql from vacuum.c
13833 */
13834 static int sqlcipher_execExecSql(sqlcipher3 *db, char **pzErrMsg, const char *zSql){
13835   sqlcipher3_stmt *pStmt;
13836   int rc;
13837
13838   rc = sqlcipher3_prepare(db, zSql, -1, &pStmt, 0);
13839   if( rc!=SQLCIPHER_OK ) return rc;
13840
13841   while( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
13842     rc = sqlcipher_execSql(db, pzErrMsg, (char*)sqlcipher3_column_text(pStmt, 0));
13843     if( rc!=SQLCIPHER_OK ){
13844       sqlcipher_finalize(db, pStmt, pzErrMsg);
13845       return rc;
13846     }
13847   }
13848
13849   return sqlcipher_finalize(db, pStmt, pzErrMsg);
13850 }
13851
13852 /*
13853  * copy database and schema from the main database to an attached database
13854  * 
13855  * Based on sqlcipher3RunVacuum from vacuum.c
13856 */
13857 void sqlcipher_exportFunc(sqlcipher3_context *context, int argc, sqlcipher3_value **argv) {
13858   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
13859   const char* attachedDb = (const char*) sqlcipher3_value_text(argv[0]);
13860   int saved_flags;        /* Saved value of the db->flags */
13861   int saved_nChange;      /* Saved value of db->nChange */
13862   int saved_nTotalChange; /* Saved value of db->nTotalChange */
13863   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
13864   int rc = SQLCIPHER_OK;     /* Return code from service routines */
13865   char *zSql = NULL;         /* SQL statements */
13866   char *pzErrMsg = NULL;
13867
13868   (void) argc;
13869
13870   saved_flags = db->flags;
13871   saved_nChange = db->nChange;
13872   saved_nTotalChange = db->nTotalChange;
13873   saved_xTrace = db->xTrace;
13874   db->flags |= SQLCIPHER_WriteSchema | SQLCIPHER_IgnoreChecks | SQLCIPHER_PreferBuiltin;
13875   db->flags &= ~(SQLCIPHER_ForeignKeys | SQLCIPHER_ReverseOrder);
13876   db->xTrace = 0;
13877
13878   /* Query the schema of the main database. Create a mirror schema
13879   ** in the temporary database.
13880   */
13881   zSql = sqlcipher3_mprintf(
13882     "SELECT 'CREATE TABLE %s.' || substr(sql,14) "
13883     "  FROM sqlcipher_master WHERE type='table' AND name!='sqlcipher_sequence'"
13884     "   AND rootpage>0"
13885   , attachedDb);
13886   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); 
13887   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13888   sqlcipher3_free(zSql);
13889
13890   zSql = sqlcipher3_mprintf(
13891     "SELECT 'CREATE INDEX %s.' || substr(sql,14)"
13892     "  FROM sqlcipher_master WHERE sql LIKE 'CREATE INDEX %%' "
13893   , attachedDb);
13894   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); 
13895   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13896   sqlcipher3_free(zSql);
13897
13898   zSql = sqlcipher3_mprintf(
13899     "SELECT 'CREATE UNIQUE INDEX %s.' || substr(sql,21) "
13900     "  FROM sqlcipher_master WHERE sql LIKE 'CREATE UNIQUE INDEX %%'"
13901   , attachedDb);
13902   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); 
13903   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13904   sqlcipher3_free(zSql);
13905
13906   /* Loop through the tables in the main database. For each, do
13907   ** an "INSERT INTO rekey_db.xxx SELECT * FROM main.xxx;" to copy
13908   ** the contents to the temporary database.
13909   */
13910   zSql = sqlcipher3_mprintf(
13911     "SELECT 'INSERT INTO %s.' || quote(name) "
13912     "|| ' SELECT * FROM main.' || quote(name) || ';'"
13913     "FROM main.sqlcipher_master "
13914     "WHERE type = 'table' AND name!='sqlcipher_sequence' "
13915     "  AND rootpage>0"
13916   , attachedDb);
13917   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); 
13918   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13919   sqlcipher3_free(zSql);
13920
13921   /* Copy over the sequence table
13922   */
13923   zSql = sqlcipher3_mprintf(
13924     "SELECT 'DELETE FROM %s.' || quote(name) || ';' "
13925     "FROM %s.sqlcipher_master WHERE name='sqlcipher_sequence' "
13926   , attachedDb, attachedDb);
13927   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); 
13928   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13929   sqlcipher3_free(zSql);
13930
13931   zSql = sqlcipher3_mprintf(
13932     "SELECT 'INSERT INTO %s.' || quote(name) "
13933     "|| ' SELECT * FROM main.' || quote(name) || ';' "
13934     "FROM %s.sqlcipher_master WHERE name=='sqlcipher_sequence';"
13935   , attachedDb, attachedDb);
13936   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); 
13937   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13938   sqlcipher3_free(zSql);
13939
13940   /* Copy the triggers, views, and virtual tables from the main database
13941   ** over to the temporary database.  None of these objects has any
13942   ** associated storage, so all we have to do is copy their entries
13943   ** from the SQLCIPHER_MASTER table.
13944   */
13945   zSql = sqlcipher3_mprintf(
13946     "INSERT INTO %s.sqlcipher_master "
13947     "  SELECT type, name, tbl_name, rootpage, sql"
13948     "    FROM main.sqlcipher_master"
13949     "   WHERE type='view' OR type='trigger'"
13950     "      OR (type='table' AND rootpage=0)"
13951   , attachedDb);
13952   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execSql(db, &pzErrMsg, zSql); 
13953   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13954   sqlcipher3_free(zSql);
13955
13956   zSql = NULL;
13957 end_of_export:
13958   db->flags = saved_flags;
13959   db->nChange = saved_nChange;
13960   db->nTotalChange = saved_nTotalChange;
13961   db->xTrace = saved_xTrace;
13962
13963   sqlcipher3_free(zSql);
13964
13965   if(rc) {
13966     if(pzErrMsg != NULL) {
13967       sqlcipher3_result_error(context, pzErrMsg, -1);
13968       sqlcipher3DbFree(db, pzErrMsg);
13969     } else {
13970       sqlcipher3_result_error(context, sqlcipher3ErrStr(rc), -1);
13971     }
13972   }
13973 }
13974
13975 #endif
13976 #endif
13977
13978 /************** End of crypto_impl.c *****************************************/
13979 /************** Begin file global.c ******************************************/
13980 /*
13981 ** 2008 June 13
13982 **
13983 ** The author disclaims copyright to this source code.  In place of
13984 ** a legal notice, here is a blessing:
13985 **
13986 **    May you do good and not evil.
13987 **    May you find forgiveness for yourself and forgive others.
13988 **    May you share freely, never taking more than you give.
13989 **
13990 *************************************************************************
13991 **
13992 ** This file contains definitions of global variables and contants.
13993 */
13994
13995 /* An array to map all upper-case characters into their corresponding
13996 ** lower-case character. 
13997 **
13998 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
13999 ** handle case conversions for the UTF character set since the tables
14000 ** involved are nearly as big or bigger than SQLite itself.
14001 */
14002 SQLCIPHER_PRIVATE const unsigned char sqlcipher3UpperToLower[] = {
14003 #ifdef SQLCIPHER_ASCII
14004       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
14005      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
14006      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
14007      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
14008     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
14009     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
14010     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
14011     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
14012     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
14013     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
14014     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
14015     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
14016     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
14017     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
14018     252,253,254,255
14019 #endif
14020 #ifdef SQLCIPHER_EBCDIC
14021       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
14022      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
14023      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
14024      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
14025      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
14026      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
14027      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
14028     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
14029     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
14030     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
14031     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
14032     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
14033     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
14034     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
14035     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
14036     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
14037 #endif
14038 };
14039
14040 /*
14041 ** The following 256 byte lookup table is used to support SQLites built-in
14042 ** equivalents to the following standard library functions:
14043 **
14044 **   isspace()                        0x01
14045 **   isalpha()                        0x02
14046 **   isdigit()                        0x04
14047 **   isalnum()                        0x06
14048 **   isxdigit()                       0x08
14049 **   toupper()                        0x20
14050 **   SQLite identifier character      0x40
14051 **
14052 ** Bit 0x20 is set if the mapped character requires translation to upper
14053 ** case. i.e. if the character is a lower-case ASCII character.
14054 ** If x is a lower-case ASCII character, then its upper-case equivalent
14055 ** is (x - 0x20). Therefore toupper() can be implemented as:
14056 **
14057 **   (x & ~(map[x]&0x20))
14058 **
14059 ** Standard function tolower() is implemented using the sqlcipher3UpperToLower[]
14060 ** array. tolower() is used more often than toupper() by SQLite.
14061 **
14062 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
14063 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
14064 ** non-ASCII UTF character. Hence the test for whether or not a character is
14065 ** part of an identifier is 0x46.
14066 **
14067 ** SQLite's versions are identical to the standard versions assuming a
14068 ** locale of "C". They are implemented as macros in sqlcipherInt.h.
14069 */
14070 #ifdef SQLCIPHER_ASCII
14071 SQLCIPHER_PRIVATE const unsigned char sqlcipher3CtypeMap[256] = {
14072   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
14073   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
14074   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
14075   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
14076   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
14077   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
14078   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
14079   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
14080
14081   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
14082   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
14083   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
14084   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
14085   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
14086   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
14087   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
14088   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
14089
14090   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
14091   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
14092   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
14093   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
14094   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
14095   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
14096   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
14097   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
14098
14099   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
14100   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
14101   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
14102   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
14103   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
14104   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
14105   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
14106   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
14107 };
14108 #endif
14109
14110 #ifndef SQLCIPHER_USE_URI
14111 # define  SQLCIPHER_USE_URI 0
14112 #endif
14113
14114 /*
14115 ** The following singleton contains the global configuration for
14116 ** the SQLite library.
14117 */
14118 SQLCIPHER_PRIVATE SQLCIPHER_WSD struct Sqlite3Config sqlcipher3Config = {
14119    SQLCIPHER_DEFAULT_MEMSTATUS,  /* bMemstat */
14120    1,                         /* bCoreMutex */
14121    SQLCIPHER_THREADSAFE==1,      /* bFullMutex */
14122    SQLCIPHER_USE_URI,            /* bOpenUri */
14123    0x7ffffffe,                /* mxStrlen */
14124    128,                       /* szLookaside */
14125    500,                       /* nLookaside */
14126    {0,0,0,0,0,0,0,0},         /* m */
14127    {0,0,0,0,0,0,0,0,0},       /* mutex */
14128    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
14129    (void*)0,                  /* pHeap */
14130    0,                         /* nHeap */
14131    0, 0,                      /* mnHeap, mxHeap */
14132    (void*)0,                  /* pScratch */
14133    0,                         /* szScratch */
14134    0,                         /* nScratch */
14135    (void*)0,                  /* pPage */
14136    0,                         /* szPage */
14137    0,                         /* nPage */
14138    0,                         /* mxParserStack */
14139    0,                         /* sharedCacheEnabled */
14140    /* All the rest should always be initialized to zero */
14141    0,                         /* isInit */
14142    0,                         /* inProgress */
14143    0,                         /* isMutexInit */
14144    0,                         /* isMallocInit */
14145    0,                         /* isPCacheInit */
14146    0,                         /* pInitMutex */
14147    0,                         /* nRefInitMutex */
14148    0,                         /* xLog */
14149    0,                         /* pLogArg */
14150    0,                         /* bLocaltimeFault */
14151 };
14152
14153
14154 /*
14155 ** Hash table for global functions - functions common to all
14156 ** database connections.  After initialization, this table is
14157 ** read-only.
14158 */
14159 SQLCIPHER_PRIVATE SQLCIPHER_WSD FuncDefHash sqlcipher3GlobalFunctions;
14160
14161 /*
14162 ** Constant tokens for values 0 and 1.
14163 */
14164 SQLCIPHER_PRIVATE const Token sqlcipher3IntTokens[] = {
14165    { "0", 1 },
14166    { "1", 1 }
14167 };
14168
14169
14170 /*
14171 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
14172 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
14173 ** the database page that contains the pending byte.  It never attempts
14174 ** to read or write that page.  The pending byte page is set assign
14175 ** for use by the VFS layers as space for managing file locks.
14176 **
14177 ** During testing, it is often desirable to move the pending byte to
14178 ** a different position in the file.  This allows code that has to
14179 ** deal with the pending byte to run on files that are much smaller
14180 ** than 1 GiB.  The sqlcipher3_test_control() interface can be used to
14181 ** move the pending byte.
14182 **
14183 ** IMPORTANT:  Changing the pending byte to any value other than
14184 ** 0x40000000 results in an incompatible database file format!
14185 ** Changing the pending byte during operating results in undefined
14186 ** and dileterious behavior.
14187 */
14188 #ifndef SQLCIPHER_OMIT_WSD
14189 SQLCIPHER_PRIVATE int sqlcipher3PendingByte = 0x40000000;
14190 #endif
14191
14192 /*
14193 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
14194 ** created by mkopcodeh.awk during compilation.  Data is obtained
14195 ** from the comments following the "case OP_xxxx:" statements in
14196 ** the vdbe.c file.  
14197 */
14198 SQLCIPHER_PRIVATE const unsigned char sqlcipher3OpcodeProperty[] = OPFLG_INITIALIZER;
14199
14200 /************** End of global.c **********************************************/
14201 /************** Begin file ctime.c *******************************************/
14202 /*
14203 ** 2010 February 23
14204 **
14205 ** The author disclaims copyright to this source code.  In place of
14206 ** a legal notice, here is a blessing:
14207 **
14208 **    May you do good and not evil.
14209 **    May you find forgiveness for yourself and forgive others.
14210 **    May you share freely, never taking more than you give.
14211 **
14212 *************************************************************************
14213 **
14214 ** This file implements routines used to report what compile-time options
14215 ** SQLite was built with.
14216 */
14217
14218 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
14219
14220
14221 /*
14222 ** An array of names of all compile-time options.  This array should 
14223 ** be sorted A-Z.
14224 **
14225 ** This array looks large, but in a typical installation actually uses
14226 ** only a handful of compile-time options, so most times this array is usually
14227 ** rather short and uses little memory space.
14228 */
14229 static const char * const azCompileOpt[] = {
14230
14231 /* These macros are provided to "stringify" the value of the define
14232 ** for those options in which the value is meaningful. */
14233 #define CTIMEOPT_VAL_(opt) #opt
14234 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
14235
14236 #ifdef SQLCIPHER_32BIT_ROWID
14237   "32BIT_ROWID",
14238 #endif
14239 #ifdef SQLCIPHER_4_BYTE_ALIGNED_MALLOC
14240   "4_BYTE_ALIGNED_MALLOC",
14241 #endif
14242 #ifdef SQLCIPHER_CASE_SENSITIVE_LIKE
14243   "CASE_SENSITIVE_LIKE",
14244 #endif
14245 #ifdef SQLCIPHER_CHECK_PAGES
14246   "CHECK_PAGES",
14247 #endif
14248 #ifdef SQLCIPHER_COVERAGE_TEST
14249   "COVERAGE_TEST",
14250 #endif
14251 #ifdef SQLCIPHER_DEBUG
14252   "DEBUG",
14253 #endif
14254 #ifdef SQLCIPHER_DEFAULT_LOCKING_MODE
14255   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLCIPHER_DEFAULT_LOCKING_MODE),
14256 #endif
14257 #ifdef SQLCIPHER_DISABLE_DIRSYNC
14258   "DISABLE_DIRSYNC",
14259 #endif
14260 #ifdef SQLCIPHER_DISABLE_LFS
14261   "DISABLE_LFS",
14262 #endif
14263 #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
14264   "ENABLE_ATOMIC_WRITE",
14265 #endif
14266 #ifdef SQLCIPHER_ENABLE_CEROD
14267   "ENABLE_CEROD",
14268 #endif
14269 #ifdef SQLCIPHER_ENABLE_COLUMN_METADATA
14270   "ENABLE_COLUMN_METADATA",
14271 #endif
14272 #ifdef SQLCIPHER_ENABLE_EXPENSIVE_ASSERT
14273   "ENABLE_EXPENSIVE_ASSERT",
14274 #endif
14275 #ifdef SQLCIPHER_ENABLE_FTS1
14276   "ENABLE_FTS1",
14277 #endif
14278 #ifdef SQLCIPHER_ENABLE_FTS2
14279   "ENABLE_FTS2",
14280 #endif
14281 #ifdef SQLCIPHER_ENABLE_FTS3
14282   "ENABLE_FTS3",
14283 #endif
14284 #ifdef SQLCIPHER_ENABLE_FTS3_PARENTHESIS
14285   "ENABLE_FTS3_PARENTHESIS",
14286 #endif
14287 #ifdef SQLCIPHER_ENABLE_FTS4
14288   "ENABLE_FTS4",
14289 #endif
14290 #ifdef SQLCIPHER_ENABLE_ICU
14291   "ENABLE_ICU",
14292 #endif
14293 #ifdef SQLCIPHER_ENABLE_IOTRACE
14294   "ENABLE_IOTRACE",
14295 #endif
14296 #ifdef SQLCIPHER_ENABLE_LOAD_EXTENSION
14297   "ENABLE_LOAD_EXTENSION",
14298 #endif
14299 #ifdef SQLCIPHER_ENABLE_LOCKING_STYLE
14300   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLCIPHER_ENABLE_LOCKING_STYLE),
14301 #endif
14302 #ifdef SQLCIPHER_ENABLE_MEMORY_MANAGEMENT
14303   "ENABLE_MEMORY_MANAGEMENT",
14304 #endif
14305 #ifdef SQLCIPHER_ENABLE_MEMSYS3
14306   "ENABLE_MEMSYS3",
14307 #endif
14308 #ifdef SQLCIPHER_ENABLE_MEMSYS5
14309   "ENABLE_MEMSYS5",
14310 #endif
14311 #ifdef SQLCIPHER_ENABLE_OVERSIZE_CELL_CHECK
14312   "ENABLE_OVERSIZE_CELL_CHECK",
14313 #endif
14314 #ifdef SQLCIPHER_ENABLE_RTREE
14315   "ENABLE_RTREE",
14316 #endif
14317 #ifdef SQLCIPHER_ENABLE_STAT3
14318   "ENABLE_STAT3",
14319 #endif
14320 #ifdef SQLCIPHER_ENABLE_UNLOCK_NOTIFY
14321   "ENABLE_UNLOCK_NOTIFY",
14322 #endif
14323 #ifdef SQLCIPHER_ENABLE_UPDATE_DELETE_LIMIT
14324   "ENABLE_UPDATE_DELETE_LIMIT",
14325 #endif
14326 #ifdef SQLCIPHER_HAS_CODEC
14327   "HAS_CODEC",
14328 #endif
14329 #ifdef SQLCIPHER_HAVE_ISNAN
14330   "HAVE_ISNAN",
14331 #endif
14332 #ifdef SQLCIPHER_HOMEGROWN_RECURSIVE_MUTEX
14333   "HOMEGROWN_RECURSIVE_MUTEX",
14334 #endif
14335 #ifdef SQLCIPHER_IGNORE_AFP_LOCK_ERRORS
14336   "IGNORE_AFP_LOCK_ERRORS",
14337 #endif
14338 #ifdef SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS
14339   "IGNORE_FLOCK_LOCK_ERRORS",
14340 #endif
14341 #ifdef SQLCIPHER_INT64_TYPE
14342   "INT64_TYPE",
14343 #endif
14344 #ifdef SQLCIPHER_LOCK_TRACE
14345   "LOCK_TRACE",
14346 #endif
14347 #ifdef SQLCIPHER_MAX_SCHEMA_RETRY
14348   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLCIPHER_MAX_SCHEMA_RETRY),
14349 #endif
14350 #ifdef SQLCIPHER_MEMDEBUG
14351   "MEMDEBUG",
14352 #endif
14353 #ifdef SQLCIPHER_MIXED_ENDIAN_64BIT_FLOAT
14354   "MIXED_ENDIAN_64BIT_FLOAT",
14355 #endif
14356 #ifdef SQLCIPHER_NO_SYNC
14357   "NO_SYNC",
14358 #endif
14359 #ifdef SQLCIPHER_OMIT_ALTERTABLE
14360   "OMIT_ALTERTABLE",
14361 #endif
14362 #ifdef SQLCIPHER_OMIT_ANALYZE
14363   "OMIT_ANALYZE",
14364 #endif
14365 #ifdef SQLCIPHER_OMIT_ATTACH
14366   "OMIT_ATTACH",
14367 #endif
14368 #ifdef SQLCIPHER_OMIT_AUTHORIZATION
14369   "OMIT_AUTHORIZATION",
14370 #endif
14371 #ifdef SQLCIPHER_OMIT_AUTOINCREMENT
14372   "OMIT_AUTOINCREMENT",
14373 #endif
14374 #ifdef SQLCIPHER_OMIT_AUTOINIT
14375   "OMIT_AUTOINIT",
14376 #endif
14377 #ifdef SQLCIPHER_OMIT_AUTOMATIC_INDEX
14378   "OMIT_AUTOMATIC_INDEX",
14379 #endif
14380 #ifdef SQLCIPHER_OMIT_AUTORESET
14381   "OMIT_AUTORESET",
14382 #endif
14383 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
14384   "OMIT_AUTOVACUUM",
14385 #endif
14386 #ifdef SQLCIPHER_OMIT_BETWEEN_OPTIMIZATION
14387   "OMIT_BETWEEN_OPTIMIZATION",
14388 #endif
14389 #ifdef SQLCIPHER_OMIT_BLOB_LITERAL
14390   "OMIT_BLOB_LITERAL",
14391 #endif
14392 #ifdef SQLCIPHER_OMIT_BTREECOUNT
14393   "OMIT_BTREECOUNT",
14394 #endif
14395 #ifdef SQLCIPHER_OMIT_BUILTIN_TEST
14396   "OMIT_BUILTIN_TEST",
14397 #endif
14398 #ifdef SQLCIPHER_OMIT_CAST
14399   "OMIT_CAST",
14400 #endif
14401 #ifdef SQLCIPHER_OMIT_CHECK
14402   "OMIT_CHECK",
14403 #endif
14404 /* // redundant
14405 ** #ifdef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
14406 **   "OMIT_COMPILEOPTION_DIAGS",
14407 ** #endif
14408 */
14409 #ifdef SQLCIPHER_OMIT_COMPLETE
14410   "OMIT_COMPLETE",
14411 #endif
14412 #ifdef SQLCIPHER_OMIT_COMPOUND_SELECT
14413   "OMIT_COMPOUND_SELECT",
14414 #endif
14415 #ifdef SQLCIPHER_OMIT_DATETIME_FUNCS
14416   "OMIT_DATETIME_FUNCS",
14417 #endif
14418 #ifdef SQLCIPHER_OMIT_DECLTYPE
14419   "OMIT_DECLTYPE",
14420 #endif
14421 #ifdef SQLCIPHER_OMIT_DEPRECATED
14422   "OMIT_DEPRECATED",
14423 #endif
14424 #ifdef SQLCIPHER_OMIT_DISKIO
14425   "OMIT_DISKIO",
14426 #endif
14427 #ifdef SQLCIPHER_OMIT_EXPLAIN
14428   "OMIT_EXPLAIN",
14429 #endif
14430 #ifdef SQLCIPHER_OMIT_FLAG_PRAGMAS
14431   "OMIT_FLAG_PRAGMAS",
14432 #endif
14433 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
14434   "OMIT_FLOATING_POINT",
14435 #endif
14436 #ifdef SQLCIPHER_OMIT_FOREIGN_KEY
14437   "OMIT_FOREIGN_KEY",
14438 #endif
14439 #ifdef SQLCIPHER_OMIT_GET_TABLE
14440   "OMIT_GET_TABLE",
14441 #endif
14442 #ifdef SQLCIPHER_OMIT_INCRBLOB
14443   "OMIT_INCRBLOB",
14444 #endif
14445 #ifdef SQLCIPHER_OMIT_INTEGRITY_CHECK
14446   "OMIT_INTEGRITY_CHECK",
14447 #endif
14448 #ifdef SQLCIPHER_OMIT_LIKE_OPTIMIZATION
14449   "OMIT_LIKE_OPTIMIZATION",
14450 #endif
14451 #ifdef SQLCIPHER_OMIT_LOAD_EXTENSION
14452   "OMIT_LOAD_EXTENSION",
14453 #endif
14454 #ifdef SQLCIPHER_OMIT_LOCALTIME
14455   "OMIT_LOCALTIME",
14456 #endif
14457 #ifdef SQLCIPHER_OMIT_LOOKASIDE
14458   "OMIT_LOOKASIDE",
14459 #endif
14460 #ifdef SQLCIPHER_OMIT_MEMORYDB
14461   "OMIT_MEMORYDB",
14462 #endif
14463 #ifdef SQLCIPHER_OMIT_MERGE_SORT
14464   "OMIT_MERGE_SORT",
14465 #endif
14466 #ifdef SQLCIPHER_OMIT_OR_OPTIMIZATION
14467   "OMIT_OR_OPTIMIZATION",
14468 #endif
14469 #ifdef SQLCIPHER_OMIT_PAGER_PRAGMAS
14470   "OMIT_PAGER_PRAGMAS",
14471 #endif
14472 #ifdef SQLCIPHER_OMIT_PRAGMA
14473   "OMIT_PRAGMA",
14474 #endif
14475 #ifdef SQLCIPHER_OMIT_PROGRESS_CALLBACK
14476   "OMIT_PROGRESS_CALLBACK",
14477 #endif
14478 #ifdef SQLCIPHER_OMIT_QUICKBALANCE
14479   "OMIT_QUICKBALANCE",
14480 #endif
14481 #ifdef SQLCIPHER_OMIT_REINDEX
14482   "OMIT_REINDEX",
14483 #endif
14484 #ifdef SQLCIPHER_OMIT_SCHEMA_PRAGMAS
14485   "OMIT_SCHEMA_PRAGMAS",
14486 #endif
14487 #ifdef SQLCIPHER_OMIT_SCHEMA_VERSION_PRAGMAS
14488   "OMIT_SCHEMA_VERSION_PRAGMAS",
14489 #endif
14490 #ifdef SQLCIPHER_OMIT_SHARED_CACHE
14491   "OMIT_SHARED_CACHE",
14492 #endif
14493 #ifdef SQLCIPHER_OMIT_SUBQUERY
14494   "OMIT_SUBQUERY",
14495 #endif
14496 #ifdef SQLCIPHER_OMIT_TCL_VARIABLE
14497   "OMIT_TCL_VARIABLE",
14498 #endif
14499 #ifdef SQLCIPHER_OMIT_TEMPDB
14500   "OMIT_TEMPDB",
14501 #endif
14502 #ifdef SQLCIPHER_OMIT_TRACE
14503   "OMIT_TRACE",
14504 #endif
14505 #ifdef SQLCIPHER_OMIT_TRIGGER
14506   "OMIT_TRIGGER",
14507 #endif
14508 #ifdef SQLCIPHER_OMIT_TRUNCATE_OPTIMIZATION
14509   "OMIT_TRUNCATE_OPTIMIZATION",
14510 #endif
14511 #ifdef SQLCIPHER_OMIT_UTF16
14512   "OMIT_UTF16",
14513 #endif
14514 #ifdef SQLCIPHER_OMIT_VACUUM
14515   "OMIT_VACUUM",
14516 #endif
14517 #ifdef SQLCIPHER_OMIT_VIEW
14518   "OMIT_VIEW",
14519 #endif
14520 #ifdef SQLCIPHER_OMIT_VIRTUALTABLE
14521   "OMIT_VIRTUALTABLE",
14522 #endif
14523 #ifdef SQLCIPHER_OMIT_WAL
14524   "OMIT_WAL",
14525 #endif
14526 #ifdef SQLCIPHER_OMIT_WSD
14527   "OMIT_WSD",
14528 #endif
14529 #ifdef SQLCIPHER_OMIT_XFER_OPT
14530   "OMIT_XFER_OPT",
14531 #endif
14532 #ifdef SQLCIPHER_PERFORMANCE_TRACE
14533   "PERFORMANCE_TRACE",
14534 #endif
14535 #ifdef SQLCIPHER_PROXY_DEBUG
14536   "PROXY_DEBUG",
14537 #endif
14538 #ifdef SQLCIPHER_SECURE_DELETE
14539   "SECURE_DELETE",
14540 #endif
14541 #ifdef SQLCIPHER_SMALL_STACK
14542   "SMALL_STACK",
14543 #endif
14544 #ifdef SQLCIPHER_SOUNDEX
14545   "SOUNDEX",
14546 #endif
14547 #ifdef SQLCIPHER_TCL
14548   "TCL",
14549 #endif
14550 #ifdef SQLCIPHER_TEMP_STORE
14551   "TEMP_STORE=" CTIMEOPT_VAL(SQLCIPHER_TEMP_STORE),
14552 #endif
14553 #ifdef SQLCIPHER_TEST
14554   "TEST",
14555 #endif
14556 #ifdef SQLCIPHER_THREADSAFE
14557   "THREADSAFE=" CTIMEOPT_VAL(SQLCIPHER_THREADSAFE),
14558 #endif
14559 #ifdef SQLCIPHER_USE_ALLOCA
14560   "USE_ALLOCA",
14561 #endif
14562 #ifdef SQLCIPHER_ZERO_MALLOC
14563   "ZERO_MALLOC"
14564 #endif
14565 };
14566
14567 /*
14568 ** Given the name of a compile-time option, return true if that option
14569 ** was used and false if not.
14570 **
14571 ** The name can optionally begin with "SQLCIPHER_" but the "SQLCIPHER_" prefix
14572 ** is not required for a match.
14573 */
14574 SQLCIPHER_API int sqlcipher3_compileoption_used(const char *zOptName){
14575   int i, n;
14576   if( sqlcipher3StrNICmp(zOptName, "SQLCIPHER_", 7)==0 ) zOptName += 7;
14577   n = sqlcipher3Strlen30(zOptName);
14578
14579   /* Since ArraySize(azCompileOpt) is normally in single digits, a
14580   ** linear search is adequate.  No need for a binary search. */
14581   for(i=0; i<ArraySize(azCompileOpt); i++){
14582     if(   (sqlcipher3StrNICmp(zOptName, azCompileOpt[i], n)==0)
14583        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
14584   }
14585   return 0;
14586 }
14587
14588 /*
14589 ** Return the N-th compile-time option string.  If N is out of range,
14590 ** return a NULL pointer.
14591 */
14592 SQLCIPHER_API const char *sqlcipher3_compileoption_get(int N){
14593   if( N>=0 && N<ArraySize(azCompileOpt) ){
14594     return azCompileOpt[N];
14595   }
14596   return 0;
14597 }
14598
14599 #endif /* SQLCIPHER_OMIT_COMPILEOPTION_DIAGS */
14600
14601 /************** End of ctime.c ***********************************************/
14602 /************** Begin file status.c ******************************************/
14603 /*
14604 ** 2008 June 18
14605 **
14606 ** The author disclaims copyright to this source code.  In place of
14607 ** a legal notice, here is a blessing:
14608 **
14609 **    May you do good and not evil.
14610 **    May you find forgiveness for yourself and forgive others.
14611 **    May you share freely, never taking more than you give.
14612 **
14613 *************************************************************************
14614 **
14615 ** This module implements the sqlcipher3_status() interface and related
14616 ** functionality.
14617 */
14618 /************** Include vdbeInt.h in the middle of status.c ******************/
14619 /************** Begin file vdbeInt.h *****************************************/
14620 /*
14621 ** 2003 September 6
14622 **
14623 ** The author disclaims copyright to this source code.  In place of
14624 ** a legal notice, here is a blessing:
14625 **
14626 **    May you do good and not evil.
14627 **    May you find forgiveness for yourself and forgive others.
14628 **    May you share freely, never taking more than you give.
14629 **
14630 *************************************************************************
14631 ** This is the header file for information that is private to the
14632 ** VDBE.  This information used to all be at the top of the single
14633 ** source code file "vdbe.c".  When that file became too big (over
14634 ** 6000 lines long) it was split up into several smaller files and
14635 ** this header information was factored out.
14636 */
14637 #ifndef _VDBEINT_H_
14638 #define _VDBEINT_H_
14639
14640 /*
14641 ** SQL is translated into a sequence of instructions to be
14642 ** executed by a virtual machine.  Each instruction is an instance
14643 ** of the following structure.
14644 */
14645 typedef struct VdbeOp Op;
14646
14647 /*
14648 ** Boolean values
14649 */
14650 typedef unsigned char Bool;
14651
14652 /* Opaque type used by code in vdbesort.c */
14653 typedef struct VdbeSorter VdbeSorter;
14654
14655 /*
14656 ** A cursor is a pointer into a single BTree within a database file.
14657 ** The cursor can seek to a BTree entry with a particular key, or
14658 ** loop over all entries of the Btree.  You can also insert new BTree
14659 ** entries or retrieve the key or data from the entry that the cursor
14660 ** is currently pointing to.
14661 ** 
14662 ** Every cursor that the virtual machine has open is represented by an
14663 ** instance of the following structure.
14664 */
14665 struct VdbeCursor {
14666   BtCursor *pCursor;    /* The cursor structure of the backend */
14667   Btree *pBt;           /* Separate file holding temporary table */
14668   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
14669   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
14670   int pseudoTableReg;   /* Register holding pseudotable content. */
14671   int nField;           /* Number of fields in the header */
14672   Bool zeroed;          /* True if zeroed out and ready for reuse */
14673   Bool rowidIsValid;    /* True if lastRowid is valid */
14674   Bool atFirst;         /* True if pointing to first entry */
14675   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
14676   Bool nullRow;         /* True if pointing to a row with no data */
14677   Bool deferredMoveto;  /* A call to sqlcipher3BtreeMoveto() is needed */
14678   Bool isTable;         /* True if a table requiring integer keys */
14679   Bool isIndex;         /* True if an index containing keys only - no data */
14680   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
14681   Bool isSorter;        /* True if a new-style sorter */
14682   sqlcipher3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
14683   const sqlcipher3_module *pModule;     /* Module for cursor pVtabCursor */
14684   i64 seqCount;         /* Sequence counter */
14685   i64 movetoTarget;     /* Argument to the deferred sqlcipher3BtreeMoveto() */
14686   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
14687   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
14688
14689   /* Result of last sqlcipher3BtreeMoveto() done by an OP_NotExists or 
14690   ** OP_IsUnique opcode on this cursor. */
14691   int seekResult;
14692
14693   /* Cached information about the header for the data record that the
14694   ** cursor is currently pointing to.  Only valid if cacheStatus matches
14695   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
14696   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
14697   ** the cache is out of date.
14698   **
14699   ** aRow might point to (ephemeral) data for the current row, or it might
14700   ** be NULL.
14701   */
14702   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
14703   int payloadSize;      /* Total number of bytes in the record */
14704   u32 *aType;           /* Type values for all entries in the record */
14705   u32 *aOffset;         /* Cached offsets to the start of each columns data */
14706   u8 *aRow;             /* Data for the current row, if all on one page */
14707 };
14708 typedef struct VdbeCursor VdbeCursor;
14709
14710 /*
14711 ** When a sub-program is executed (OP_Program), a structure of this type
14712 ** is allocated to store the current value of the program counter, as
14713 ** well as the current memory cell array and various other frame specific
14714 ** values stored in the Vdbe struct. When the sub-program is finished, 
14715 ** these values are copied back to the Vdbe from the VdbeFrame structure,
14716 ** restoring the state of the VM to as it was before the sub-program
14717 ** began executing.
14718 **
14719 ** The memory for a VdbeFrame object is allocated and managed by a memory
14720 ** cell in the parent (calling) frame. When the memory cell is deleted or
14721 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
14722 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
14723 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
14724 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
14725 ** calls to sqlcipher3VdbeMemRelease() when the memory cells belonging to the
14726 ** child frame are released.
14727 **
14728 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
14729 ** set to NULL if the currently executing frame is the main program.
14730 */
14731 typedef struct VdbeFrame VdbeFrame;
14732 struct VdbeFrame {
14733   Vdbe *v;                /* VM this frame belongs to */
14734   int pc;                 /* Program Counter in parent (calling) frame */
14735   Op *aOp;                /* Program instructions for parent frame */
14736   int nOp;                /* Size of aOp array */
14737   Mem *aMem;              /* Array of memory cells for parent frame */
14738   int nMem;               /* Number of entries in aMem */
14739   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
14740   u16 nCursor;            /* Number of entries in apCsr */
14741   void *token;            /* Copy of SubProgram.token */
14742   int nChildMem;          /* Number of memory cells for child frame */
14743   int nChildCsr;          /* Number of cursors for child frame */
14744   i64 lastRowid;          /* Last insert rowid (sqlcipher3.lastRowid) */
14745   int nChange;            /* Statement changes (Vdbe.nChanges)     */
14746   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
14747 };
14748
14749 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
14750
14751 /*
14752 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
14753 */
14754 #define CACHE_STALE 0
14755
14756 /*
14757 ** Internally, the vdbe manipulates nearly all SQL values as Mem
14758 ** structures. Each Mem struct may cache multiple representations (string,
14759 ** integer etc.) of the same value.
14760 */
14761 struct Mem {
14762   sqlcipher3 *db;        /* The associated database connection */
14763   char *z;            /* String or BLOB value */
14764   double r;           /* Real value */
14765   union {
14766     i64 i;              /* Integer value used when MEM_Int is set in flags */
14767     int nZero;          /* Used when bit MEM_Zero is set in flags */
14768     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
14769     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
14770     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
14771   } u;
14772   int n;              /* Number of characters in string value, excluding '\0' */
14773   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
14774   u8  type;           /* One of SQLCIPHER_NULL, SQLCIPHER_TEXT, SQLCIPHER_INTEGER, etc */
14775   u8  enc;            /* SQLCIPHER_UTF8, SQLCIPHER_UTF16BE, SQLCIPHER_UTF16LE */
14776 #ifdef SQLCIPHER_DEBUG
14777   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
14778   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
14779 #endif
14780   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
14781   char *zMalloc;      /* Dynamic buffer allocated by sqlcipher3_malloc() */
14782 };
14783
14784 /* One or more of the following flags are set to indicate the validOK
14785 ** representations of the value stored in the Mem struct.
14786 **
14787 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
14788 ** No other flags may be set in this case.
14789 **
14790 ** If the MEM_Str flag is set then Mem.z points at a string representation.
14791 ** Usually this is encoded in the same unicode encoding as the main
14792 ** database (see below for exceptions). If the MEM_Term flag is also
14793 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
14794 ** flags may coexist with the MEM_Str flag.
14795 */
14796 #define MEM_Null      0x0001   /* Value is NULL */
14797 #define MEM_Str       0x0002   /* Value is a string */
14798 #define MEM_Int       0x0004   /* Value is an integer */
14799 #define MEM_Real      0x0008   /* Value is a real number */
14800 #define MEM_Blob      0x0010   /* Value is a BLOB */
14801 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
14802 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
14803 #define MEM_Invalid   0x0080   /* Value is undefined */
14804 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
14805
14806 /* Whenever Mem contains a valid string or blob representation, one of
14807 ** the following flags must be set to determine the memory management
14808 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
14809 ** string is \000 or \u0000 terminated
14810 */
14811 #define MEM_Term      0x0200   /* String rep is nul terminated */
14812 #define MEM_Dyn       0x0400   /* Need to call sqlcipherFree() on Mem.z */
14813 #define MEM_Static    0x0800   /* Mem.z points to a static string */
14814 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
14815 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
14816 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
14817 #ifdef SQLCIPHER_OMIT_INCRBLOB
14818   #undef MEM_Zero
14819   #define MEM_Zero 0x0000
14820 #endif
14821
14822 /*
14823 ** Clear any existing type flags from a Mem and replace them with f
14824 */
14825 #define MemSetTypeFlag(p, f) \
14826    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
14827
14828 /*
14829 ** Return true if a memory cell is not marked as invalid.  This macro
14830 ** is for use inside assert() statements only.
14831 */
14832 #ifdef SQLCIPHER_DEBUG
14833 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
14834 #endif
14835
14836
14837 /* A VdbeFunc is just a FuncDef (defined in sqlcipherInt.h) that contains
14838 ** additional information about auxiliary information bound to arguments
14839 ** of the function.  This is used to implement the sqlcipher3_get_auxdata()
14840 ** and sqlcipher3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
14841 ** that can be associated with a constant argument to a function.  This
14842 ** allows functions such as "regexp" to compile their constant regular
14843 ** expression argument once and reused the compiled code for multiple
14844 ** invocations.
14845 */
14846 struct VdbeFunc {
14847   FuncDef *pFunc;               /* The definition of the function */
14848   int nAux;                     /* Number of entries allocated for apAux[] */
14849   struct AuxData {
14850     void *pAux;                   /* Aux data for the i-th argument */
14851     void (*xDelete)(void *);      /* Destructor for the aux data */
14852   } apAux[1];                   /* One slot for each function argument */
14853 };
14854
14855 /*
14856 ** The "context" argument for a installable function.  A pointer to an
14857 ** instance of this structure is the first argument to the routines used
14858 ** implement the SQL functions.
14859 **
14860 ** There is a typedef for this structure in sqlcipher.h.  So all routines,
14861 ** even the public interface to SQLite, can use a pointer to this structure.
14862 ** But this file is the only place where the internal details of this
14863 ** structure are known.
14864 **
14865 ** This structure is defined inside of vdbeInt.h because it uses substructures
14866 ** (Mem) which are only defined there.
14867 */
14868 struct sqlcipher3_context {
14869   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
14870   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
14871   Mem s;                /* The return value is stored here */
14872   Mem *pMem;            /* Memory cell used to store aggregate context */
14873   int isError;          /* Error code returned by the function. */
14874   CollSeq *pColl;       /* Collating sequence */
14875 };
14876
14877 /*
14878 ** An instance of the virtual machine.  This structure contains the complete
14879 ** state of the virtual machine.
14880 **
14881 ** The "sqlcipher3_stmt" structure pointer that is returned by sqlcipher3_prepare()
14882 ** is really a pointer to an instance of this structure.
14883 **
14884 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
14885 ** any virtual table method invocations made by the vdbe program. It is
14886 ** set to 2 for xDestroy method calls and 1 for all other methods. This
14887 ** variable is used for two purposes: to allow xDestroy methods to execute
14888 ** "DROP TABLE" statements and to prevent some nasty side effects of
14889 ** malloc failure when SQLite is invoked recursively by a virtual table 
14890 ** method function.
14891 */
14892 struct Vdbe {
14893   sqlcipher3 *db;            /* The database connection that owns this statement */
14894   Op *aOp;                /* Space to hold the virtual machine's program */
14895   Mem *aMem;              /* The memory locations */
14896   Mem **apArg;            /* Arguments to currently executing user function */
14897   Mem *aColName;          /* Column names to return */
14898   Mem *pResultSet;        /* Pointer to an array of results */
14899   int nMem;               /* Number of memory locations currently allocated */
14900   int nOp;                /* Number of instructions in the program */
14901   int nOpAlloc;           /* Number of slots allocated for aOp[] */
14902   int nLabel;             /* Number of labels used */
14903   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
14904   int *aLabel;            /* Space to hold the labels */
14905   u16 nResColumn;         /* Number of columns in one row of the result set */
14906   u16 nCursor;            /* Number of slots in apCsr[] */
14907   u32 magic;              /* Magic number for sanity checking */
14908   char *zErrMsg;          /* Error message written here */
14909   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
14910   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
14911   Mem *aVar;              /* Values for the OP_Variable opcode. */
14912   char **azVar;           /* Name of variables */
14913   ynVar nVar;             /* Number of entries in aVar[] */
14914   ynVar nzVar;            /* Number of entries in azVar[] */
14915   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
14916   int pc;                 /* The program counter */
14917   int rc;                 /* Value to return */
14918   u8 errorAction;         /* Recovery action to do in case of an error */
14919   u8 explain;             /* True if EXPLAIN present on SQL command */
14920   u8 changeCntOn;         /* True to update the change-counter */
14921   u8 expired;             /* True if the VM needs to be recompiled */
14922   u8 runOnlyOnce;         /* Automatically expire on reset */
14923   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
14924   u8 inVtabMethod;        /* See comments above */
14925   u8 usesStmtJournal;     /* True if uses a statement journal */
14926   u8 readOnly;            /* True for read-only statements */
14927   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
14928   int nChange;            /* Number of db changes made since last reset */
14929   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
14930   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
14931   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
14932   int aCounter[3];        /* Counters used by sqlcipher3_stmt_status() */
14933 #ifndef SQLCIPHER_OMIT_TRACE
14934   i64 startTime;          /* Time when query started - used for profiling */
14935 #endif
14936   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
14937   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
14938   char *zSql;             /* Text of the SQL statement that generated this */
14939   void *pFree;            /* Free this when deleting the vdbe */
14940 #ifdef SQLCIPHER_DEBUG
14941   FILE *trace;            /* Write an execution trace here, if not NULL */
14942 #endif
14943   VdbeFrame *pFrame;      /* Parent frame */
14944   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
14945   int nFrame;             /* Number of frames in pFrame list */
14946   u32 expmask;            /* Binding to these vars invalidates VM */
14947   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
14948 };
14949
14950 /*
14951 ** The following are allowed values for Vdbe.magic
14952 */
14953 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
14954 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
14955 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
14956 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
14957
14958 /*
14959 ** Function prototypes
14960 */
14961 SQLCIPHER_PRIVATE void sqlcipher3VdbeFreeCursor(Vdbe *, VdbeCursor*);
14962 void sqlcipherVdbePopStack(Vdbe*,int);
14963 SQLCIPHER_PRIVATE int sqlcipher3VdbeCursorMoveto(VdbeCursor*);
14964 #if defined(SQLCIPHER_DEBUG) || defined(VDBE_PROFILE)
14965 SQLCIPHER_PRIVATE void sqlcipher3VdbePrintOp(FILE*, int, Op*);
14966 #endif
14967 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialTypeLen(u32);
14968 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialType(Mem*, int);
14969 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialPut(unsigned char*, int, Mem*, int);
14970 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialGet(const unsigned char*, u32, Mem*);
14971 SQLCIPHER_PRIVATE void sqlcipher3VdbeDeleteAuxData(VdbeFunc*, int);
14972
14973 int sqlcipher2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
14974 SQLCIPHER_PRIVATE int sqlcipher3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
14975 SQLCIPHER_PRIVATE int sqlcipher3VdbeIdxRowid(sqlcipher3*, BtCursor *, i64 *);
14976 SQLCIPHER_PRIVATE int sqlcipher3MemCompare(const Mem*, const Mem*, const CollSeq*);
14977 SQLCIPHER_PRIVATE int sqlcipher3VdbeExec(Vdbe*);
14978 SQLCIPHER_PRIVATE int sqlcipher3VdbeList(Vdbe*);
14979 SQLCIPHER_PRIVATE int sqlcipher3VdbeHalt(Vdbe*);
14980 SQLCIPHER_PRIVATE int sqlcipher3VdbeChangeEncoding(Mem *, int);
14981 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemTooBig(Mem*);
14982 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemCopy(Mem*, const Mem*);
14983 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemShallowCopy(Mem*, const Mem*, int);
14984 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemMove(Mem*, Mem*);
14985 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemNulTerminate(Mem*);
14986 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
14987 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetInt64(Mem*, i64);
14988 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
14989 # define sqlcipher3VdbeMemSetDouble sqlcipher3VdbeMemSetInt64
14990 #else
14991 SQLCIPHER_PRIVATE   void sqlcipher3VdbeMemSetDouble(Mem*, double);
14992 #endif
14993 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetNull(Mem*);
14994 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetZeroBlob(Mem*,int);
14995 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetRowSet(Mem*);
14996 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemMakeWriteable(Mem*);
14997 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemStringify(Mem*, int);
14998 SQLCIPHER_PRIVATE i64 sqlcipher3VdbeIntValue(Mem*);
14999 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemIntegerify(Mem*);
15000 SQLCIPHER_PRIVATE double sqlcipher3VdbeRealValue(Mem*);
15001 SQLCIPHER_PRIVATE void sqlcipher3VdbeIntegerAffinity(Mem*);
15002 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemRealify(Mem*);
15003 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemNumerify(Mem*);
15004 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
15005 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemRelease(Mem *p);
15006 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemReleaseExternal(Mem *p);
15007 #define MemReleaseExt(X)  \
15008   if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
15009     sqlcipher3VdbeMemReleaseExternal(X);
15010 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemFinalize(Mem*, FuncDef*);
15011 SQLCIPHER_PRIVATE const char *sqlcipher3OpcodeName(int);
15012 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemGrow(Mem *pMem, int n, int preserve);
15013 SQLCIPHER_PRIVATE int sqlcipher3VdbeCloseStatement(Vdbe *, int);
15014 SQLCIPHER_PRIVATE void sqlcipher3VdbeFrameDelete(VdbeFrame*);
15015 SQLCIPHER_PRIVATE int sqlcipher3VdbeFrameRestore(VdbeFrame *);
15016 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemStoreType(Mem *pMem);
15017 SQLCIPHER_PRIVATE int sqlcipher3VdbeTransferError(Vdbe *p);
15018
15019 #ifdef SQLCIPHER_OMIT_MERGE_SORT
15020 # define sqlcipher3VdbeSorterInit(Y,Z)      SQLCIPHER_OK
15021 # define sqlcipher3VdbeSorterWrite(X,Y,Z)   SQLCIPHER_OK
15022 # define sqlcipher3VdbeSorterClose(Y,Z)
15023 # define sqlcipher3VdbeSorterRowkey(Y,Z)    SQLCIPHER_OK
15024 # define sqlcipher3VdbeSorterRewind(X,Y,Z)  SQLCIPHER_OK
15025 # define sqlcipher3VdbeSorterNext(X,Y,Z)    SQLCIPHER_OK
15026 # define sqlcipher3VdbeSorterCompare(X,Y,Z) SQLCIPHER_OK
15027 #else
15028 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterInit(sqlcipher3 *, VdbeCursor *);
15029 SQLCIPHER_PRIVATE void sqlcipher3VdbeSorterClose(sqlcipher3 *, VdbeCursor *);
15030 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterRowkey(VdbeCursor *, Mem *);
15031 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterNext(sqlcipher3 *, VdbeCursor *, int *);
15032 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterRewind(sqlcipher3 *, VdbeCursor *, int *);
15033 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterWrite(sqlcipher3 *, VdbeCursor *, Mem *);
15034 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterCompare(VdbeCursor *, Mem *, int *);
15035 #endif
15036
15037 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && SQLCIPHER_THREADSAFE>0
15038 SQLCIPHER_PRIVATE   void sqlcipher3VdbeEnter(Vdbe*);
15039 SQLCIPHER_PRIVATE   void sqlcipher3VdbeLeave(Vdbe*);
15040 #else
15041 # define sqlcipher3VdbeEnter(X)
15042 # define sqlcipher3VdbeLeave(X)
15043 #endif
15044
15045 #ifdef SQLCIPHER_DEBUG
15046 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemPrepareToChange(Vdbe*,Mem*);
15047 #endif
15048
15049 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
15050 SQLCIPHER_PRIVATE int sqlcipher3VdbeCheckFk(Vdbe *, int);
15051 #else
15052 # define sqlcipher3VdbeCheckFk(p,i) 0
15053 #endif
15054
15055 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemTranslate(Mem*, u8);
15056 #ifdef SQLCIPHER_DEBUG
15057 SQLCIPHER_PRIVATE   void sqlcipher3VdbePrintSql(Vdbe*);
15058 SQLCIPHER_PRIVATE   void sqlcipher3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
15059 #endif
15060 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemHandleBom(Mem *pMem);
15061
15062 #ifndef SQLCIPHER_OMIT_INCRBLOB
15063 SQLCIPHER_PRIVATE   int sqlcipher3VdbeMemExpandBlob(Mem *);
15064 #else
15065   #define sqlcipher3VdbeMemExpandBlob(x) SQLCIPHER_OK
15066 #endif
15067
15068 #endif /* !defined(_VDBEINT_H_) */
15069
15070 /************** End of vdbeInt.h *********************************************/
15071 /************** Continuing where we left off in status.c *********************/
15072
15073 /*
15074 ** Variables in which to record status information.
15075 */
15076 typedef struct sqlcipher3StatType sqlcipher3StatType;
15077 static SQLCIPHER_WSD struct sqlcipher3StatType {
15078   int nowValue[10];         /* Current value */
15079   int mxValue[10];          /* Maximum value */
15080 } sqlcipher3Stat = { {0,}, {0,} };
15081
15082
15083 /* The "wsdStat" macro will resolve to the status information
15084 ** state vector.  If writable static data is unsupported on the target,
15085 ** we have to locate the state vector at run-time.  In the more common
15086 ** case where writable static data is supported, wsdStat can refer directly
15087 ** to the "sqlcipher3Stat" state vector declared above.
15088 */
15089 #ifdef SQLCIPHER_OMIT_WSD
15090 # define wsdStatInit  sqlcipher3StatType *x = &GLOBAL(sqlcipher3StatType,sqlcipher3Stat)
15091 # define wsdStat x[0]
15092 #else
15093 # define wsdStatInit
15094 # define wsdStat sqlcipher3Stat
15095 #endif
15096
15097 /*
15098 ** Return the current value of a status parameter.
15099 */
15100 SQLCIPHER_PRIVATE int sqlcipher3StatusValue(int op){
15101   wsdStatInit;
15102   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15103   return wsdStat.nowValue[op];
15104 }
15105
15106 /*
15107 ** Add N to the value of a status record.  It is assumed that the
15108 ** caller holds appropriate locks.
15109 */
15110 SQLCIPHER_PRIVATE void sqlcipher3StatusAdd(int op, int N){
15111   wsdStatInit;
15112   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15113   wsdStat.nowValue[op] += N;
15114   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
15115     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15116   }
15117 }
15118
15119 /*
15120 ** Set the value of a status to X.
15121 */
15122 SQLCIPHER_PRIVATE void sqlcipher3StatusSet(int op, int X){
15123   wsdStatInit;
15124   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15125   wsdStat.nowValue[op] = X;
15126   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
15127     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15128   }
15129 }
15130
15131 /*
15132 ** Query status information.
15133 **
15134 ** This implementation assumes that reading or writing an aligned
15135 ** 32-bit integer is an atomic operation.  If that assumption is not true,
15136 ** then this routine is not threadsafe.
15137 */
15138 SQLCIPHER_API int sqlcipher3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
15139   wsdStatInit;
15140   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
15141     return SQLCIPHER_MISUSE_BKPT;
15142   }
15143   *pCurrent = wsdStat.nowValue[op];
15144   *pHighwater = wsdStat.mxValue[op];
15145   if( resetFlag ){
15146     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15147   }
15148   return SQLCIPHER_OK;
15149 }
15150
15151 /*
15152 ** Query status information for a single database connection
15153 */
15154 SQLCIPHER_API int sqlcipher3_db_status(
15155   sqlcipher3 *db,          /* The database connection whose status is desired */
15156   int op,               /* Status verb */
15157   int *pCurrent,        /* Write current value here */
15158   int *pHighwater,      /* Write high-water mark here */
15159   int resetFlag         /* Reset high-water mark if true */
15160 ){
15161   int rc = SQLCIPHER_OK;   /* Return code */
15162   sqlcipher3_mutex_enter(db->mutex);
15163   switch( op ){
15164     case SQLCIPHER_DBSTATUS_LOOKASIDE_USED: {
15165       *pCurrent = db->lookaside.nOut;
15166       *pHighwater = db->lookaside.mxOut;
15167       if( resetFlag ){
15168         db->lookaside.mxOut = db->lookaside.nOut;
15169       }
15170       break;
15171     }
15172
15173     case SQLCIPHER_DBSTATUS_LOOKASIDE_HIT:
15174     case SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_SIZE:
15175     case SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_FULL: {
15176       testcase( op==SQLCIPHER_DBSTATUS_LOOKASIDE_HIT );
15177       testcase( op==SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_SIZE );
15178       testcase( op==SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_FULL );
15179       assert( (op-SQLCIPHER_DBSTATUS_LOOKASIDE_HIT)>=0 );
15180       assert( (op-SQLCIPHER_DBSTATUS_LOOKASIDE_HIT)<3 );
15181       *pCurrent = 0;
15182       *pHighwater = db->lookaside.anStat[op - SQLCIPHER_DBSTATUS_LOOKASIDE_HIT];
15183       if( resetFlag ){
15184         db->lookaside.anStat[op - SQLCIPHER_DBSTATUS_LOOKASIDE_HIT] = 0;
15185       }
15186       break;
15187     }
15188
15189     /* 
15190     ** Return an approximation for the amount of memory currently used
15191     ** by all pagers associated with the given database connection.  The
15192     ** highwater mark is meaningless and is returned as zero.
15193     */
15194     case SQLCIPHER_DBSTATUS_CACHE_USED: {
15195       int totalUsed = 0;
15196       int i;
15197       sqlcipher3BtreeEnterAll(db);
15198       for(i=0; i<db->nDb; i++){
15199         Btree *pBt = db->aDb[i].pBt;
15200         if( pBt ){
15201           Pager *pPager = sqlcipher3BtreePager(pBt);
15202           totalUsed += sqlcipher3PagerMemUsed(pPager);
15203         }
15204       }
15205       sqlcipher3BtreeLeaveAll(db);
15206       *pCurrent = totalUsed;
15207       *pHighwater = 0;
15208       break;
15209     }
15210
15211     /*
15212     ** *pCurrent gets an accurate estimate of the amount of memory used
15213     ** to store the schema for all databases (main, temp, and any ATTACHed
15214     ** databases.  *pHighwater is set to zero.
15215     */
15216     case SQLCIPHER_DBSTATUS_SCHEMA_USED: {
15217       int i;                      /* Used to iterate through schemas */
15218       int nByte = 0;              /* Used to accumulate return value */
15219
15220       sqlcipher3BtreeEnterAll(db);
15221       db->pnBytesFreed = &nByte;
15222       for(i=0; i<db->nDb; i++){
15223         Schema *pSchema = db->aDb[i].pSchema;
15224         if( ALWAYS(pSchema!=0) ){
15225           HashElem *p;
15226
15227           nByte += sqlcipher3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
15228               pSchema->tblHash.count 
15229             + pSchema->trigHash.count
15230             + pSchema->idxHash.count
15231             + pSchema->fkeyHash.count
15232           );
15233           nByte += sqlcipher3MallocSize(pSchema->tblHash.ht);
15234           nByte += sqlcipher3MallocSize(pSchema->trigHash.ht);
15235           nByte += sqlcipher3MallocSize(pSchema->idxHash.ht);
15236           nByte += sqlcipher3MallocSize(pSchema->fkeyHash.ht);
15237
15238           for(p=sqlcipherHashFirst(&pSchema->trigHash); p; p=sqlcipherHashNext(p)){
15239             sqlcipher3DeleteTrigger(db, (Trigger*)sqlcipherHashData(p));
15240           }
15241           for(p=sqlcipherHashFirst(&pSchema->tblHash); p; p=sqlcipherHashNext(p)){
15242             sqlcipher3DeleteTable(db, (Table *)sqlcipherHashData(p));
15243           }
15244         }
15245       }
15246       db->pnBytesFreed = 0;
15247       sqlcipher3BtreeLeaveAll(db);
15248
15249       *pHighwater = 0;
15250       *pCurrent = nByte;
15251       break;
15252     }
15253
15254     /*
15255     ** *pCurrent gets an accurate estimate of the amount of memory used
15256     ** to store all prepared statements.
15257     ** *pHighwater is set to zero.
15258     */
15259     case SQLCIPHER_DBSTATUS_STMT_USED: {
15260       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
15261       int nByte = 0;              /* Used to accumulate return value */
15262
15263       db->pnBytesFreed = &nByte;
15264       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
15265         sqlcipher3VdbeDeleteObject(db, pVdbe);
15266       }
15267       db->pnBytesFreed = 0;
15268
15269       *pHighwater = 0;
15270       *pCurrent = nByte;
15271
15272       break;
15273     }
15274
15275     /*
15276     ** Set *pCurrent to the total cache hits or misses encountered by all
15277     ** pagers the database handle is connected to. *pHighwater is always set 
15278     ** to zero.
15279     */
15280     case SQLCIPHER_DBSTATUS_CACHE_HIT:
15281     case SQLCIPHER_DBSTATUS_CACHE_MISS: {
15282       int i;
15283       int nRet = 0;
15284       assert( SQLCIPHER_DBSTATUS_CACHE_MISS==SQLCIPHER_DBSTATUS_CACHE_HIT+1 );
15285
15286       for(i=0; i<db->nDb; i++){
15287         if( db->aDb[i].pBt ){
15288           Pager *pPager = sqlcipher3BtreePager(db->aDb[i].pBt);
15289           sqlcipher3PagerCacheStat(pPager, op, resetFlag, &nRet);
15290         }
15291       }
15292       *pHighwater = 0;
15293       *pCurrent = nRet;
15294       break;
15295     }
15296
15297     default: {
15298       rc = SQLCIPHER_ERROR;
15299     }
15300   }
15301   sqlcipher3_mutex_leave(db->mutex);
15302   return rc;
15303 }
15304
15305 /************** End of status.c **********************************************/
15306 /************** Begin file date.c ********************************************/
15307 /*
15308 ** 2003 October 31
15309 **
15310 ** The author disclaims copyright to this source code.  In place of
15311 ** a legal notice, here is a blessing:
15312 **
15313 **    May you do good and not evil.
15314 **    May you find forgiveness for yourself and forgive others.
15315 **    May you share freely, never taking more than you give.
15316 **
15317 *************************************************************************
15318 ** This file contains the C functions that implement date and time
15319 ** functions for SQLite.  
15320 **
15321 ** There is only one exported symbol in this file - the function
15322 ** sqlcipher3RegisterDateTimeFunctions() found at the bottom of the file.
15323 ** All other code has file scope.
15324 **
15325 ** SQLite processes all times and dates as Julian Day numbers.  The
15326 ** dates and times are stored as the number of days since noon
15327 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
15328 ** calendar system. 
15329 **
15330 ** 1970-01-01 00:00:00 is JD 2440587.5
15331 ** 2000-01-01 00:00:00 is JD 2451544.5
15332 **
15333 ** This implemention requires years to be expressed as a 4-digit number
15334 ** which means that only dates between 0000-01-01 and 9999-12-31 can
15335 ** be represented, even though julian day numbers allow a much wider
15336 ** range of dates.
15337 **
15338 ** The Gregorian calendar system is used for all dates and times,
15339 ** even those that predate the Gregorian calendar.  Historians usually
15340 ** use the Julian calendar for dates prior to 1582-10-15 and for some
15341 ** dates afterwards, depending on locale.  Beware of this difference.
15342 **
15343 ** The conversion algorithms are implemented based on descriptions
15344 ** in the following text:
15345 **
15346 **      Jean Meeus
15347 **      Astronomical Algorithms, 2nd Edition, 1998
15348 **      ISBM 0-943396-61-1
15349 **      Willmann-Bell, Inc
15350 **      Richmond, Virginia (USA)
15351 */
15352 /* #include <stdlib.h> */
15353 /* #include <assert.h> */
15354 #include <time.h>
15355
15356 #ifndef SQLCIPHER_OMIT_DATETIME_FUNCS
15357
15358
15359 /*
15360 ** A structure for holding a single date and time.
15361 */
15362 typedef struct DateTime DateTime;
15363 struct DateTime {
15364   sqlcipher3_int64 iJD; /* The julian day number times 86400000 */
15365   int Y, M, D;       /* Year, month, and day */
15366   int h, m;          /* Hour and minutes */
15367   int tz;            /* Timezone offset in minutes */
15368   double s;          /* Seconds */
15369   char validYMD;     /* True (1) if Y,M,D are valid */
15370   char validHMS;     /* True (1) if h,m,s are valid */
15371   char validJD;      /* True (1) if iJD is valid */
15372   char validTZ;      /* True (1) if tz is valid */
15373 };
15374
15375
15376 /*
15377 ** Convert zDate into one or more integers.  Additional arguments
15378 ** come in groups of 5 as follows:
15379 **
15380 **       N       number of digits in the integer
15381 **       min     minimum allowed value of the integer
15382 **       max     maximum allowed value of the integer
15383 **       nextC   first character after the integer
15384 **       pVal    where to write the integers value.
15385 **
15386 ** Conversions continue until one with nextC==0 is encountered.
15387 ** The function returns the number of successful conversions.
15388 */
15389 static int getDigits(const char *zDate, ...){
15390   va_list ap;
15391   int val;
15392   int N;
15393   int min;
15394   int max;
15395   int nextC;
15396   int *pVal;
15397   int cnt = 0;
15398   va_start(ap, zDate);
15399   do{
15400     N = va_arg(ap, int);
15401     min = va_arg(ap, int);
15402     max = va_arg(ap, int);
15403     nextC = va_arg(ap, int);
15404     pVal = va_arg(ap, int*);
15405     val = 0;
15406     while( N-- ){
15407       if( !sqlcipher3Isdigit(*zDate) ){
15408         goto end_getDigits;
15409       }
15410       val = val*10 + *zDate - '0';
15411       zDate++;
15412     }
15413     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
15414       goto end_getDigits;
15415     }
15416     *pVal = val;
15417     zDate++;
15418     cnt++;
15419   }while( nextC );
15420 end_getDigits:
15421   va_end(ap);
15422   return cnt;
15423 }
15424
15425 /*
15426 ** Parse a timezone extension on the end of a date-time.
15427 ** The extension is of the form:
15428 **
15429 **        (+/-)HH:MM
15430 **
15431 ** Or the "zulu" notation:
15432 **
15433 **        Z
15434 **
15435 ** If the parse is successful, write the number of minutes
15436 ** of change in p->tz and return 0.  If a parser error occurs,
15437 ** return non-zero.
15438 **
15439 ** A missing specifier is not considered an error.
15440 */
15441 static int parseTimezone(const char *zDate, DateTime *p){
15442   int sgn = 0;
15443   int nHr, nMn;
15444   int c;
15445   while( sqlcipher3Isspace(*zDate) ){ zDate++; }
15446   p->tz = 0;
15447   c = *zDate;
15448   if( c=='-' ){
15449     sgn = -1;
15450   }else if( c=='+' ){
15451     sgn = +1;
15452   }else if( c=='Z' || c=='z' ){
15453     zDate++;
15454     goto zulu_time;
15455   }else{
15456     return c!=0;
15457   }
15458   zDate++;
15459   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
15460     return 1;
15461   }
15462   zDate += 5;
15463   p->tz = sgn*(nMn + nHr*60);
15464 zulu_time:
15465   while( sqlcipher3Isspace(*zDate) ){ zDate++; }
15466   return *zDate!=0;
15467 }
15468
15469 /*
15470 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
15471 ** The HH, MM, and SS must each be exactly 2 digits.  The
15472 ** fractional seconds FFFF can be one or more digits.
15473 **
15474 ** Return 1 if there is a parsing error and 0 on success.
15475 */
15476 static int parseHhMmSs(const char *zDate, DateTime *p){
15477   int h, m, s;
15478   double ms = 0.0;
15479   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
15480     return 1;
15481   }
15482   zDate += 5;
15483   if( *zDate==':' ){
15484     zDate++;
15485     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
15486       return 1;
15487     }
15488     zDate += 2;
15489     if( *zDate=='.' && sqlcipher3Isdigit(zDate[1]) ){
15490       double rScale = 1.0;
15491       zDate++;
15492       while( sqlcipher3Isdigit(*zDate) ){
15493         ms = ms*10.0 + *zDate - '0';
15494         rScale *= 10.0;
15495         zDate++;
15496       }
15497       ms /= rScale;
15498     }
15499   }else{
15500     s = 0;
15501   }
15502   p->validJD = 0;
15503   p->validHMS = 1;
15504   p->h = h;
15505   p->m = m;
15506   p->s = s + ms;
15507   if( parseTimezone(zDate, p) ) return 1;
15508   p->validTZ = (p->tz!=0)?1:0;
15509   return 0;
15510 }
15511
15512 /*
15513 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
15514 ** that the YYYY-MM-DD is according to the Gregorian calendar.
15515 **
15516 ** Reference:  Meeus page 61
15517 */
15518 static void computeJD(DateTime *p){
15519   int Y, M, D, A, B, X1, X2;
15520
15521   if( p->validJD ) return;
15522   if( p->validYMD ){
15523     Y = p->Y;
15524     M = p->M;
15525     D = p->D;
15526   }else{
15527     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
15528     M = 1;
15529     D = 1;
15530   }
15531   if( M<=2 ){
15532     Y--;
15533     M += 12;
15534   }
15535   A = Y/100;
15536   B = 2 - A + (A/4);
15537   X1 = 36525*(Y+4716)/100;
15538   X2 = 306001*(M+1)/10000;
15539   p->iJD = (sqlcipher3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
15540   p->validJD = 1;
15541   if( p->validHMS ){
15542     p->iJD += p->h*3600000 + p->m*60000 + (sqlcipher3_int64)(p->s*1000);
15543     if( p->validTZ ){
15544       p->iJD -= p->tz*60000;
15545       p->validYMD = 0;
15546       p->validHMS = 0;
15547       p->validTZ = 0;
15548     }
15549   }
15550 }
15551
15552 /*
15553 ** Parse dates of the form
15554 **
15555 **     YYYY-MM-DD HH:MM:SS.FFF
15556 **     YYYY-MM-DD HH:MM:SS
15557 **     YYYY-MM-DD HH:MM
15558 **     YYYY-MM-DD
15559 **
15560 ** Write the result into the DateTime structure and return 0
15561 ** on success and 1 if the input string is not a well-formed
15562 ** date.
15563 */
15564 static int parseYyyyMmDd(const char *zDate, DateTime *p){
15565   int Y, M, D, neg;
15566
15567   if( zDate[0]=='-' ){
15568     zDate++;
15569     neg = 1;
15570   }else{
15571     neg = 0;
15572   }
15573   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
15574     return 1;
15575   }
15576   zDate += 10;
15577   while( sqlcipher3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
15578   if( parseHhMmSs(zDate, p)==0 ){
15579     /* We got the time */
15580   }else if( *zDate==0 ){
15581     p->validHMS = 0;
15582   }else{
15583     return 1;
15584   }
15585   p->validJD = 0;
15586   p->validYMD = 1;
15587   p->Y = neg ? -Y : Y;
15588   p->M = M;
15589   p->D = D;
15590   if( p->validTZ ){
15591     computeJD(p);
15592   }
15593   return 0;
15594 }
15595
15596 /*
15597 ** Set the time to the current time reported by the VFS.
15598 **
15599 ** Return the number of errors.
15600 */
15601 static int setDateTimeToCurrent(sqlcipher3_context *context, DateTime *p){
15602   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
15603   if( sqlcipher3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLCIPHER_OK ){
15604     p->validJD = 1;
15605     return 0;
15606   }else{
15607     return 1;
15608   }
15609 }
15610
15611 /*
15612 ** Attempt to parse the given string into a Julian Day Number.  Return
15613 ** the number of errors.
15614 **
15615 ** The following are acceptable forms for the input string:
15616 **
15617 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
15618 **      DDDD.DD 
15619 **      now
15620 **
15621 ** In the first form, the +/-HH:MM is always optional.  The fractional
15622 ** seconds extension (the ".FFF") is optional.  The seconds portion
15623 ** (":SS.FFF") is option.  The year and date can be omitted as long
15624 ** as there is a time string.  The time string can be omitted as long
15625 ** as there is a year and date.
15626 */
15627 static int parseDateOrTime(
15628   sqlcipher3_context *context, 
15629   const char *zDate, 
15630   DateTime *p
15631 ){
15632   double r;
15633   if( parseYyyyMmDd(zDate,p)==0 ){
15634     return 0;
15635   }else if( parseHhMmSs(zDate, p)==0 ){
15636     return 0;
15637   }else if( sqlcipher3StrICmp(zDate,"now")==0){
15638     return setDateTimeToCurrent(context, p);
15639   }else if( sqlcipher3AtoF(zDate, &r, sqlcipher3Strlen30(zDate), SQLCIPHER_UTF8) ){
15640     p->iJD = (sqlcipher3_int64)(r*86400000.0 + 0.5);
15641     p->validJD = 1;
15642     return 0;
15643   }
15644   return 1;
15645 }
15646
15647 /*
15648 ** Compute the Year, Month, and Day from the julian day number.
15649 */
15650 static void computeYMD(DateTime *p){
15651   int Z, A, B, C, D, E, X1;
15652   if( p->validYMD ) return;
15653   if( !p->validJD ){
15654     p->Y = 2000;
15655     p->M = 1;
15656     p->D = 1;
15657   }else{
15658     Z = (int)((p->iJD + 43200000)/86400000);
15659     A = (int)((Z - 1867216.25)/36524.25);
15660     A = Z + 1 + A - (A/4);
15661     B = A + 1524;
15662     C = (int)((B - 122.1)/365.25);
15663     D = (36525*C)/100;
15664     E = (int)((B-D)/30.6001);
15665     X1 = (int)(30.6001*E);
15666     p->D = B - D - X1;
15667     p->M = E<14 ? E-1 : E-13;
15668     p->Y = p->M>2 ? C - 4716 : C - 4715;
15669   }
15670   p->validYMD = 1;
15671 }
15672
15673 /*
15674 ** Compute the Hour, Minute, and Seconds from the julian day number.
15675 */
15676 static void computeHMS(DateTime *p){
15677   int s;
15678   if( p->validHMS ) return;
15679   computeJD(p);
15680   s = (int)((p->iJD + 43200000) % 86400000);
15681   p->s = s/1000.0;
15682   s = (int)p->s;
15683   p->s -= s;
15684   p->h = s/3600;
15685   s -= p->h*3600;
15686   p->m = s/60;
15687   p->s += s - p->m*60;
15688   p->validHMS = 1;
15689 }
15690
15691 /*
15692 ** Compute both YMD and HMS
15693 */
15694 static void computeYMD_HMS(DateTime *p){
15695   computeYMD(p);
15696   computeHMS(p);
15697 }
15698
15699 /*
15700 ** Clear the YMD and HMS and the TZ
15701 */
15702 static void clearYMD_HMS_TZ(DateTime *p){
15703   p->validYMD = 0;
15704   p->validHMS = 0;
15705   p->validTZ = 0;
15706 }
15707
15708 /*
15709 ** On recent Windows platforms, the localtime_s() function is available
15710 ** as part of the "Secure CRT". It is essentially equivalent to 
15711 ** localtime_r() available under most POSIX platforms, except that the 
15712 ** order of the parameters is reversed.
15713 **
15714 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
15715 **
15716 ** If the user has not indicated to use localtime_r() or localtime_s()
15717 ** already, check for an MSVC build environment that provides 
15718 ** localtime_s().
15719 */
15720 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
15721      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
15722 #define HAVE_LOCALTIME_S 1
15723 #endif
15724
15725 #ifndef SQLCIPHER_OMIT_LOCALTIME
15726 /*
15727 ** The following routine implements the rough equivalent of localtime_r()
15728 ** using whatever operating-system specific localtime facility that
15729 ** is available.  This routine returns 0 on success and
15730 ** non-zero on any kind of error.
15731 **
15732 ** If the sqlcipher3GlobalConfig.bLocaltimeFault variable is true then this
15733 ** routine will always fail.
15734 */
15735 static int osLocaltime(time_t *t, struct tm *pTm){
15736   int rc;
15737 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
15738       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
15739   struct tm *pX;
15740 #if SQLCIPHER_THREADSAFE>0
15741   sqlcipher3_mutex *mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
15742 #endif
15743   sqlcipher3_mutex_enter(mutex);
15744   pX = localtime(t);
15745 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
15746   if( sqlcipher3GlobalConfig.bLocaltimeFault ) pX = 0;
15747 #endif
15748   if( pX ) *pTm = *pX;
15749   sqlcipher3_mutex_leave(mutex);
15750   rc = pX==0;
15751 #else
15752 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
15753   if( sqlcipher3GlobalConfig.bLocaltimeFault ) return 1;
15754 #endif
15755 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
15756   rc = localtime_r(t, pTm)==0;
15757 #else
15758   rc = localtime_s(pTm, t);
15759 #endif /* HAVE_LOCALTIME_R */
15760 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
15761   return rc;
15762 }
15763 #endif /* SQLCIPHER_OMIT_LOCALTIME */
15764
15765
15766 #ifndef SQLCIPHER_OMIT_LOCALTIME
15767 /*
15768 ** Compute the difference (in milliseconds) between localtime and UTC
15769 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
15770 ** return this value and set *pRc to SQLCIPHER_OK. 
15771 **
15772 ** Or, if an error does occur, set *pRc to SQLCIPHER_ERROR. The returned value
15773 ** is undefined in this case.
15774 */
15775 static sqlcipher3_int64 localtimeOffset(
15776   DateTime *p,                    /* Date at which to calculate offset */
15777   sqlcipher3_context *pCtx,          /* Write error here if one occurs */
15778   int *pRc                        /* OUT: Error code. SQLCIPHER_OK or ERROR */
15779 ){
15780   DateTime x, y;
15781   time_t t;
15782   struct tm sLocal;
15783
15784   /* Initialize the contents of sLocal to avoid a compiler warning. */
15785   memset(&sLocal, 0, sizeof(sLocal));
15786
15787   x = *p;
15788   computeYMD_HMS(&x);
15789   if( x.Y<1971 || x.Y>=2038 ){
15790     x.Y = 2000;
15791     x.M = 1;
15792     x.D = 1;
15793     x.h = 0;
15794     x.m = 0;
15795     x.s = 0.0;
15796   } else {
15797     int s = (int)(x.s + 0.5);
15798     x.s = s;
15799   }
15800   x.tz = 0;
15801   x.validJD = 0;
15802   computeJD(&x);
15803   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
15804   if( osLocaltime(&t, &sLocal) ){
15805     sqlcipher3_result_error(pCtx, "local time unavailable", -1);
15806     *pRc = SQLCIPHER_ERROR;
15807     return 0;
15808   }
15809   y.Y = sLocal.tm_year + 1900;
15810   y.M = sLocal.tm_mon + 1;
15811   y.D = sLocal.tm_mday;
15812   y.h = sLocal.tm_hour;
15813   y.m = sLocal.tm_min;
15814   y.s = sLocal.tm_sec;
15815   y.validYMD = 1;
15816   y.validHMS = 1;
15817   y.validJD = 0;
15818   y.validTZ = 0;
15819   computeJD(&y);
15820   *pRc = SQLCIPHER_OK;
15821   return y.iJD - x.iJD;
15822 }
15823 #endif /* SQLCIPHER_OMIT_LOCALTIME */
15824
15825 /*
15826 ** Process a modifier to a date-time stamp.  The modifiers are
15827 ** as follows:
15828 **
15829 **     NNN days
15830 **     NNN hours
15831 **     NNN minutes
15832 **     NNN.NNNN seconds
15833 **     NNN months
15834 **     NNN years
15835 **     start of month
15836 **     start of year
15837 **     start of week
15838 **     start of day
15839 **     weekday N
15840 **     unixepoch
15841 **     localtime
15842 **     utc
15843 **
15844 ** Return 0 on success and 1 if there is any kind of error. If the error
15845 ** is in a system call (i.e. localtime()), then an error message is written
15846 ** to context pCtx. If the error is an unrecognized modifier, no error is
15847 ** written to pCtx.
15848 */
15849 static int parseModifier(sqlcipher3_context *pCtx, const char *zMod, DateTime *p){
15850   int rc = 1;
15851   int n;
15852   double r;
15853   char *z, zBuf[30];
15854   z = zBuf;
15855   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
15856     z[n] = (char)sqlcipher3UpperToLower[(u8)zMod[n]];
15857   }
15858   z[n] = 0;
15859   switch( z[0] ){
15860 #ifndef SQLCIPHER_OMIT_LOCALTIME
15861     case 'l': {
15862       /*    localtime
15863       **
15864       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
15865       ** show local time.
15866       */
15867       if( strcmp(z, "localtime")==0 ){
15868         computeJD(p);
15869         p->iJD += localtimeOffset(p, pCtx, &rc);
15870         clearYMD_HMS_TZ(p);
15871       }
15872       break;
15873     }
15874 #endif
15875     case 'u': {
15876       /*
15877       **    unixepoch
15878       **
15879       ** Treat the current value of p->iJD as the number of
15880       ** seconds since 1970.  Convert to a real julian day number.
15881       */
15882       if( strcmp(z, "unixepoch")==0 && p->validJD ){
15883         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
15884         clearYMD_HMS_TZ(p);
15885         rc = 0;
15886       }
15887 #ifndef SQLCIPHER_OMIT_LOCALTIME
15888       else if( strcmp(z, "utc")==0 ){
15889         sqlcipher3_int64 c1;
15890         computeJD(p);
15891         c1 = localtimeOffset(p, pCtx, &rc);
15892         if( rc==SQLCIPHER_OK ){
15893           p->iJD -= c1;
15894           clearYMD_HMS_TZ(p);
15895           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
15896         }
15897       }
15898 #endif
15899       break;
15900     }
15901     case 'w': {
15902       /*
15903       **    weekday N
15904       **
15905       ** Move the date to the same time on the next occurrence of
15906       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
15907       ** date is already on the appropriate weekday, this is a no-op.
15908       */
15909       if( strncmp(z, "weekday ", 8)==0
15910                && sqlcipher3AtoF(&z[8], &r, sqlcipher3Strlen30(&z[8]), SQLCIPHER_UTF8)
15911                && (n=(int)r)==r && n>=0 && r<7 ){
15912         sqlcipher3_int64 Z;
15913         computeYMD_HMS(p);
15914         p->validTZ = 0;
15915         p->validJD = 0;
15916         computeJD(p);
15917         Z = ((p->iJD + 129600000)/86400000) % 7;
15918         if( Z>n ) Z -= 7;
15919         p->iJD += (n - Z)*86400000;
15920         clearYMD_HMS_TZ(p);
15921         rc = 0;
15922       }
15923       break;
15924     }
15925     case 's': {
15926       /*
15927       **    start of TTTTT
15928       **
15929       ** Move the date backwards to the beginning of the current day,
15930       ** or month or year.
15931       */
15932       if( strncmp(z, "start of ", 9)!=0 ) break;
15933       z += 9;
15934       computeYMD(p);
15935       p->validHMS = 1;
15936       p->h = p->m = 0;
15937       p->s = 0.0;
15938       p->validTZ = 0;
15939       p->validJD = 0;
15940       if( strcmp(z,"month")==0 ){
15941         p->D = 1;
15942         rc = 0;
15943       }else if( strcmp(z,"year")==0 ){
15944         computeYMD(p);
15945         p->M = 1;
15946         p->D = 1;
15947         rc = 0;
15948       }else if( strcmp(z,"day")==0 ){
15949         rc = 0;
15950       }
15951       break;
15952     }
15953     case '+':
15954     case '-':
15955     case '0':
15956     case '1':
15957     case '2':
15958     case '3':
15959     case '4':
15960     case '5':
15961     case '6':
15962     case '7':
15963     case '8':
15964     case '9': {
15965       double rRounder;
15966       for(n=1; z[n] && z[n]!=':' && !sqlcipher3Isspace(z[n]); n++){}
15967       if( !sqlcipher3AtoF(z, &r, n, SQLCIPHER_UTF8) ){
15968         rc = 1;
15969         break;
15970       }
15971       if( z[n]==':' ){
15972         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
15973         ** specified number of hours, minutes, seconds, and fractional seconds
15974         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
15975         ** omitted.
15976         */
15977         const char *z2 = z;
15978         DateTime tx;
15979         sqlcipher3_int64 day;
15980         if( !sqlcipher3Isdigit(*z2) ) z2++;
15981         memset(&tx, 0, sizeof(tx));
15982         if( parseHhMmSs(z2, &tx) ) break;
15983         computeJD(&tx);
15984         tx.iJD -= 43200000;
15985         day = tx.iJD/86400000;
15986         tx.iJD -= day*86400000;
15987         if( z[0]=='-' ) tx.iJD = -tx.iJD;
15988         computeJD(p);
15989         clearYMD_HMS_TZ(p);
15990         p->iJD += tx.iJD;
15991         rc = 0;
15992         break;
15993       }
15994       z += n;
15995       while( sqlcipher3Isspace(*z) ) z++;
15996       n = sqlcipher3Strlen30(z);
15997       if( n>10 || n<3 ) break;
15998       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
15999       computeJD(p);
16000       rc = 0;
16001       rRounder = r<0 ? -0.5 : +0.5;
16002       if( n==3 && strcmp(z,"day")==0 ){
16003         p->iJD += (sqlcipher3_int64)(r*86400000.0 + rRounder);
16004       }else if( n==4 && strcmp(z,"hour")==0 ){
16005         p->iJD += (sqlcipher3_int64)(r*(86400000.0/24.0) + rRounder);
16006       }else if( n==6 && strcmp(z,"minute")==0 ){
16007         p->iJD += (sqlcipher3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
16008       }else if( n==6 && strcmp(z,"second")==0 ){
16009         p->iJD += (sqlcipher3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
16010       }else if( n==5 && strcmp(z,"month")==0 ){
16011         int x, y;
16012         computeYMD_HMS(p);
16013         p->M += (int)r;
16014         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
16015         p->Y += x;
16016         p->M -= x*12;
16017         p->validJD = 0;
16018         computeJD(p);
16019         y = (int)r;
16020         if( y!=r ){
16021           p->iJD += (sqlcipher3_int64)((r - y)*30.0*86400000.0 + rRounder);
16022         }
16023       }else if( n==4 && strcmp(z,"year")==0 ){
16024         int y = (int)r;
16025         computeYMD_HMS(p);
16026         p->Y += y;
16027         p->validJD = 0;
16028         computeJD(p);
16029         if( y!=r ){
16030           p->iJD += (sqlcipher3_int64)((r - y)*365.0*86400000.0 + rRounder);
16031         }
16032       }else{
16033         rc = 1;
16034       }
16035       clearYMD_HMS_TZ(p);
16036       break;
16037     }
16038     default: {
16039       break;
16040     }
16041   }
16042   return rc;
16043 }
16044
16045 /*
16046 ** Process time function arguments.  argv[0] is a date-time stamp.
16047 ** argv[1] and following are modifiers.  Parse them all and write
16048 ** the resulting time into the DateTime structure p.  Return 0
16049 ** on success and 1 if there are any errors.
16050 **
16051 ** If there are zero parameters (if even argv[0] is undefined)
16052 ** then assume a default value of "now" for argv[0].
16053 */
16054 static int isDate(
16055   sqlcipher3_context *context, 
16056   int argc, 
16057   sqlcipher3_value **argv, 
16058   DateTime *p
16059 ){
16060   int i;
16061   const unsigned char *z;
16062   int eType;
16063   memset(p, 0, sizeof(*p));
16064   if( argc==0 ){
16065     return setDateTimeToCurrent(context, p);
16066   }
16067   if( (eType = sqlcipher3_value_type(argv[0]))==SQLCIPHER_FLOAT
16068                    || eType==SQLCIPHER_INTEGER ){
16069     p->iJD = (sqlcipher3_int64)(sqlcipher3_value_double(argv[0])*86400000.0 + 0.5);
16070     p->validJD = 1;
16071   }else{
16072     z = sqlcipher3_value_text(argv[0]);
16073     if( !z || parseDateOrTime(context, (char*)z, p) ){
16074       return 1;
16075     }
16076   }
16077   for(i=1; i<argc; i++){
16078     z = sqlcipher3_value_text(argv[i]);
16079     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
16080   }
16081   return 0;
16082 }
16083
16084
16085 /*
16086 ** The following routines implement the various date and time functions
16087 ** of SQLite.
16088 */
16089
16090 /*
16091 **    julianday( TIMESTRING, MOD, MOD, ...)
16092 **
16093 ** Return the julian day number of the date specified in the arguments
16094 */
16095 static void juliandayFunc(
16096   sqlcipher3_context *context,
16097   int argc,
16098   sqlcipher3_value **argv
16099 ){
16100   DateTime x;
16101   if( isDate(context, argc, argv, &x)==0 ){
16102     computeJD(&x);
16103     sqlcipher3_result_double(context, x.iJD/86400000.0);
16104   }
16105 }
16106
16107 /*
16108 **    datetime( TIMESTRING, MOD, MOD, ...)
16109 **
16110 ** Return YYYY-MM-DD HH:MM:SS
16111 */
16112 static void datetimeFunc(
16113   sqlcipher3_context *context,
16114   int argc,
16115   sqlcipher3_value **argv
16116 ){
16117   DateTime x;
16118   if( isDate(context, argc, argv, &x)==0 ){
16119     char zBuf[100];
16120     computeYMD_HMS(&x);
16121     sqlcipher3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
16122                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
16123     sqlcipher3_result_text(context, zBuf, -1, SQLCIPHER_TRANSIENT);
16124   }
16125 }
16126
16127 /*
16128 **    time( TIMESTRING, MOD, MOD, ...)
16129 **
16130 ** Return HH:MM:SS
16131 */
16132 static void timeFunc(
16133   sqlcipher3_context *context,
16134   int argc,
16135   sqlcipher3_value **argv
16136 ){
16137   DateTime x;
16138   if( isDate(context, argc, argv, &x)==0 ){
16139     char zBuf[100];
16140     computeHMS(&x);
16141     sqlcipher3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
16142     sqlcipher3_result_text(context, zBuf, -1, SQLCIPHER_TRANSIENT);
16143   }
16144 }
16145
16146 /*
16147 **    date( TIMESTRING, MOD, MOD, ...)
16148 **
16149 ** Return YYYY-MM-DD
16150 */
16151 static void dateFunc(
16152   sqlcipher3_context *context,
16153   int argc,
16154   sqlcipher3_value **argv
16155 ){
16156   DateTime x;
16157   if( isDate(context, argc, argv, &x)==0 ){
16158     char zBuf[100];
16159     computeYMD(&x);
16160     sqlcipher3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
16161     sqlcipher3_result_text(context, zBuf, -1, SQLCIPHER_TRANSIENT);
16162   }
16163 }
16164
16165 /*
16166 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
16167 **
16168 ** Return a string described by FORMAT.  Conversions as follows:
16169 **
16170 **   %d  day of month
16171 **   %f  ** fractional seconds  SS.SSS
16172 **   %H  hour 00-24
16173 **   %j  day of year 000-366
16174 **   %J  ** Julian day number
16175 **   %m  month 01-12
16176 **   %M  minute 00-59
16177 **   %s  seconds since 1970-01-01
16178 **   %S  seconds 00-59
16179 **   %w  day of week 0-6  sunday==0
16180 **   %W  week of year 00-53
16181 **   %Y  year 0000-9999
16182 **   %%  %
16183 */
16184 static void strftimeFunc(
16185   sqlcipher3_context *context,
16186   int argc,
16187   sqlcipher3_value **argv
16188 ){
16189   DateTime x;
16190   u64 n;
16191   size_t i,j;
16192   char *z;
16193   sqlcipher3 *db;
16194   const char *zFmt = (const char*)sqlcipher3_value_text(argv[0]);
16195   char zBuf[100];
16196   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
16197   db = sqlcipher3_context_db_handle(context);
16198   for(i=0, n=1; zFmt[i]; i++, n++){
16199     if( zFmt[i]=='%' ){
16200       switch( zFmt[i+1] ){
16201         case 'd':
16202         case 'H':
16203         case 'm':
16204         case 'M':
16205         case 'S':
16206         case 'W':
16207           n++;
16208           /* fall thru */
16209         case 'w':
16210         case '%':
16211           break;
16212         case 'f':
16213           n += 8;
16214           break;
16215         case 'j':
16216           n += 3;
16217           break;
16218         case 'Y':
16219           n += 8;
16220           break;
16221         case 's':
16222         case 'J':
16223           n += 50;
16224           break;
16225         default:
16226           return;  /* ERROR.  return a NULL */
16227       }
16228       i++;
16229     }
16230   }
16231   testcase( n==sizeof(zBuf)-1 );
16232   testcase( n==sizeof(zBuf) );
16233   testcase( n==(u64)db->aLimit[SQLCIPHER_LIMIT_LENGTH]+1 );
16234   testcase( n==(u64)db->aLimit[SQLCIPHER_LIMIT_LENGTH] );
16235   if( n<sizeof(zBuf) ){
16236     z = zBuf;
16237   }else if( n>(u64)db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
16238     sqlcipher3_result_error_toobig(context);
16239     return;
16240   }else{
16241     z = sqlcipher3DbMallocRaw(db, (int)n);
16242     if( z==0 ){
16243       sqlcipher3_result_error_nomem(context);
16244       return;
16245     }
16246   }
16247   computeJD(&x);
16248   computeYMD_HMS(&x);
16249   for(i=j=0; zFmt[i]; i++){
16250     if( zFmt[i]!='%' ){
16251       z[j++] = zFmt[i];
16252     }else{
16253       i++;
16254       switch( zFmt[i] ){
16255         case 'd':  sqlcipher3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
16256         case 'f': {
16257           double s = x.s;
16258           if( s>59.999 ) s = 59.999;
16259           sqlcipher3_snprintf(7, &z[j],"%06.3f", s);
16260           j += sqlcipher3Strlen30(&z[j]);
16261           break;
16262         }
16263         case 'H':  sqlcipher3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
16264         case 'W': /* Fall thru */
16265         case 'j': {
16266           int nDay;             /* Number of days since 1st day of year */
16267           DateTime y = x;
16268           y.validJD = 0;
16269           y.M = 1;
16270           y.D = 1;
16271           computeJD(&y);
16272           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
16273           if( zFmt[i]=='W' ){
16274             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
16275             wd = (int)(((x.iJD+43200000)/86400000)%7);
16276             sqlcipher3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
16277             j += 2;
16278           }else{
16279             sqlcipher3_snprintf(4, &z[j],"%03d",nDay+1);
16280             j += 3;
16281           }
16282           break;
16283         }
16284         case 'J': {
16285           sqlcipher3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
16286           j+=sqlcipher3Strlen30(&z[j]);
16287           break;
16288         }
16289         case 'm':  sqlcipher3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
16290         case 'M':  sqlcipher3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
16291         case 's': {
16292           sqlcipher3_snprintf(30,&z[j],"%lld",
16293                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
16294           j += sqlcipher3Strlen30(&z[j]);
16295           break;
16296         }
16297         case 'S':  sqlcipher3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
16298         case 'w': {
16299           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
16300           break;
16301         }
16302         case 'Y': {
16303           sqlcipher3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlcipher3Strlen30(&z[j]);
16304           break;
16305         }
16306         default:   z[j++] = '%'; break;
16307       }
16308     }
16309   }
16310   z[j] = 0;
16311   sqlcipher3_result_text(context, z, -1,
16312                       z==zBuf ? SQLCIPHER_TRANSIENT : SQLCIPHER_DYNAMIC);
16313 }
16314
16315 /*
16316 ** current_time()
16317 **
16318 ** This function returns the same value as time('now').
16319 */
16320 static void ctimeFunc(
16321   sqlcipher3_context *context,
16322   int NotUsed,
16323   sqlcipher3_value **NotUsed2
16324 ){
16325   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16326   timeFunc(context, 0, 0);
16327 }
16328
16329 /*
16330 ** current_date()
16331 **
16332 ** This function returns the same value as date('now').
16333 */
16334 static void cdateFunc(
16335   sqlcipher3_context *context,
16336   int NotUsed,
16337   sqlcipher3_value **NotUsed2
16338 ){
16339   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16340   dateFunc(context, 0, 0);
16341 }
16342
16343 /*
16344 ** current_timestamp()
16345 **
16346 ** This function returns the same value as datetime('now').
16347 */
16348 static void ctimestampFunc(
16349   sqlcipher3_context *context,
16350   int NotUsed,
16351   sqlcipher3_value **NotUsed2
16352 ){
16353   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16354   datetimeFunc(context, 0, 0);
16355 }
16356 #endif /* !defined(SQLCIPHER_OMIT_DATETIME_FUNCS) */
16357
16358 #ifdef SQLCIPHER_OMIT_DATETIME_FUNCS
16359 /*
16360 ** If the library is compiled to omit the full-scale date and time
16361 ** handling (to get a smaller binary), the following minimal version
16362 ** of the functions current_time(), current_date() and current_timestamp()
16363 ** are included instead. This is to support column declarations that
16364 ** include "DEFAULT CURRENT_TIME" etc.
16365 **
16366 ** This function uses the C-library functions time(), gmtime()
16367 ** and strftime(). The format string to pass to strftime() is supplied
16368 ** as the user-data for the function.
16369 */
16370 static void currentTimeFunc(
16371   sqlcipher3_context *context,
16372   int argc,
16373   sqlcipher3_value **argv
16374 ){
16375   time_t t;
16376   char *zFormat = (char *)sqlcipher3_user_data(context);
16377   sqlcipher3 *db;
16378   sqlcipher3_int64 iT;
16379   struct tm *pTm;
16380   struct tm sNow;
16381   char zBuf[20];
16382
16383   UNUSED_PARAMETER(argc);
16384   UNUSED_PARAMETER(argv);
16385
16386   db = sqlcipher3_context_db_handle(context);
16387   if( sqlcipher3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
16388   t = iT/1000 - 10000*(sqlcipher3_int64)21086676;
16389 #ifdef HAVE_GMTIME_R
16390   pTm = gmtime_r(&t, &sNow);
16391 #else
16392   sqlcipher3_mutex_enter(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
16393   pTm = gmtime(&t);
16394   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
16395   sqlcipher3_mutex_leave(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
16396 #endif
16397   if( pTm ){
16398     strftime(zBuf, 20, zFormat, &sNow);
16399     sqlcipher3_result_text(context, zBuf, -1, SQLCIPHER_TRANSIENT);
16400   }
16401 }
16402 #endif
16403
16404 /*
16405 ** This function registered all of the above C functions as SQL
16406 ** functions.  This should be the only routine in this file with
16407 ** external linkage.
16408 */
16409 SQLCIPHER_PRIVATE void sqlcipher3RegisterDateTimeFunctions(void){
16410   static SQLCIPHER_WSD FuncDef aDateTimeFuncs[] = {
16411 #ifndef SQLCIPHER_OMIT_DATETIME_FUNCS
16412     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
16413     FUNCTION(date,             -1, 0, 0, dateFunc      ),
16414     FUNCTION(time,             -1, 0, 0, timeFunc      ),
16415     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
16416     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
16417     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
16418     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
16419     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
16420 #else
16421     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
16422     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
16423     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
16424 #endif
16425   };
16426   int i;
16427   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlcipher3GlobalFunctions);
16428   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
16429
16430   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
16431     sqlcipher3FuncDefInsert(pHash, &aFunc[i]);
16432   }
16433 }
16434
16435 /************** End of date.c ************************************************/
16436 /************** Begin file os.c **********************************************/
16437 /*
16438 ** 2005 November 29
16439 **
16440 ** The author disclaims copyright to this source code.  In place of
16441 ** a legal notice, here is a blessing:
16442 **
16443 **    May you do good and not evil.
16444 **    May you find forgiveness for yourself and forgive others.
16445 **    May you share freely, never taking more than you give.
16446 **
16447 ******************************************************************************
16448 **
16449 ** This file contains OS interface code that is common to all
16450 ** architectures.
16451 */
16452 #define _SQLCIPHER_OS_C_ 1
16453 #undef _SQLCIPHER_OS_C_
16454
16455 /*
16456 ** The default SQLite sqlcipher3_vfs implementations do not allocate
16457 ** memory (actually, os_unix.c allocates a small amount of memory
16458 ** from within OsOpen()), but some third-party implementations may.
16459 ** So we test the effects of a malloc() failing and the sqlcipher3OsXXX()
16460 ** function returning SQLCIPHER_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
16461 **
16462 ** The following functions are instrumented for malloc() failure 
16463 ** testing:
16464 **
16465 **     sqlcipher3OsOpen()
16466 **     sqlcipher3OsRead()
16467 **     sqlcipher3OsWrite()
16468 **     sqlcipher3OsSync()
16469 **     sqlcipher3OsLock()
16470 **
16471 */
16472 #if defined(SQLCIPHER_TEST)
16473 SQLCIPHER_API int sqlcipher3_memdebug_vfs_oom_test = 1;
16474   #define DO_OS_MALLOC_TEST(x)                                       \
16475   if (sqlcipher3_memdebug_vfs_oom_test && (!x || !sqlcipher3IsMemJournal(x))) {  \
16476     void *pTstAlloc = sqlcipher3Malloc(10);                             \
16477     if (!pTstAlloc) return SQLCIPHER_IOERR_NOMEM;                       \
16478     sqlcipher3_free(pTstAlloc);                                         \
16479   }
16480 #else
16481   #define DO_OS_MALLOC_TEST(x)
16482 #endif
16483
16484 /*
16485 ** The following routines are convenience wrappers around methods
16486 ** of the sqlcipher3_file object.  This is mostly just syntactic sugar. All
16487 ** of this would be completely automatic if SQLite were coded using
16488 ** C++ instead of plain old C.
16489 */
16490 SQLCIPHER_PRIVATE int sqlcipher3OsClose(sqlcipher3_file *pId){
16491   int rc = SQLCIPHER_OK;
16492   if( pId->pMethods ){
16493     rc = pId->pMethods->xClose(pId);
16494     pId->pMethods = 0;
16495   }
16496   return rc;
16497 }
16498 SQLCIPHER_PRIVATE int sqlcipher3OsRead(sqlcipher3_file *id, void *pBuf, int amt, i64 offset){
16499   DO_OS_MALLOC_TEST(id);
16500   return id->pMethods->xRead(id, pBuf, amt, offset);
16501 }
16502 SQLCIPHER_PRIVATE int sqlcipher3OsWrite(sqlcipher3_file *id, const void *pBuf, int amt, i64 offset){
16503   DO_OS_MALLOC_TEST(id);
16504   return id->pMethods->xWrite(id, pBuf, amt, offset);
16505 }
16506 SQLCIPHER_PRIVATE int sqlcipher3OsTruncate(sqlcipher3_file *id, i64 size){
16507   return id->pMethods->xTruncate(id, size);
16508 }
16509 SQLCIPHER_PRIVATE int sqlcipher3OsSync(sqlcipher3_file *id, int flags){
16510   DO_OS_MALLOC_TEST(id);
16511   return id->pMethods->xSync(id, flags);
16512 }
16513 SQLCIPHER_PRIVATE int sqlcipher3OsFileSize(sqlcipher3_file *id, i64 *pSize){
16514   DO_OS_MALLOC_TEST(id);
16515   return id->pMethods->xFileSize(id, pSize);
16516 }
16517 SQLCIPHER_PRIVATE int sqlcipher3OsLock(sqlcipher3_file *id, int lockType){
16518   DO_OS_MALLOC_TEST(id);
16519   return id->pMethods->xLock(id, lockType);
16520 }
16521 SQLCIPHER_PRIVATE int sqlcipher3OsUnlock(sqlcipher3_file *id, int lockType){
16522   return id->pMethods->xUnlock(id, lockType);
16523 }
16524 SQLCIPHER_PRIVATE int sqlcipher3OsCheckReservedLock(sqlcipher3_file *id, int *pResOut){
16525   DO_OS_MALLOC_TEST(id);
16526   return id->pMethods->xCheckReservedLock(id, pResOut);
16527 }
16528 SQLCIPHER_PRIVATE int sqlcipher3OsFileControl(sqlcipher3_file *id, int op, void *pArg){
16529   return id->pMethods->xFileControl(id, op, pArg);
16530 }
16531 SQLCIPHER_PRIVATE int sqlcipher3OsSectorSize(sqlcipher3_file *id){
16532   int (*xSectorSize)(sqlcipher3_file*) = id->pMethods->xSectorSize;
16533   return (xSectorSize ? xSectorSize(id) : SQLCIPHER_DEFAULT_SECTOR_SIZE);
16534 }
16535 SQLCIPHER_PRIVATE int sqlcipher3OsDeviceCharacteristics(sqlcipher3_file *id){
16536   return id->pMethods->xDeviceCharacteristics(id);
16537 }
16538 SQLCIPHER_PRIVATE int sqlcipher3OsShmLock(sqlcipher3_file *id, int offset, int n, int flags){
16539   return id->pMethods->xShmLock(id, offset, n, flags);
16540 }
16541 SQLCIPHER_PRIVATE void sqlcipher3OsShmBarrier(sqlcipher3_file *id){
16542   id->pMethods->xShmBarrier(id);
16543 }
16544 SQLCIPHER_PRIVATE int sqlcipher3OsShmUnmap(sqlcipher3_file *id, int deleteFlag){
16545   return id->pMethods->xShmUnmap(id, deleteFlag);
16546 }
16547 SQLCIPHER_PRIVATE int sqlcipher3OsShmMap(
16548   sqlcipher3_file *id,               /* Database file handle */
16549   int iPage,
16550   int pgsz,
16551   int bExtend,                    /* True to extend file if necessary */
16552   void volatile **pp              /* OUT: Pointer to mapping */
16553 ){
16554   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
16555 }
16556
16557 /*
16558 ** The next group of routines are convenience wrappers around the
16559 ** VFS methods.
16560 */
16561 SQLCIPHER_PRIVATE int sqlcipher3OsOpen(
16562   sqlcipher3_vfs *pVfs, 
16563   const char *zPath, 
16564   sqlcipher3_file *pFile, 
16565   int flags, 
16566   int *pFlagsOut
16567 ){
16568   int rc;
16569   DO_OS_MALLOC_TEST(0);
16570   /* 0x87f3f is a mask of SQLCIPHER_OPEN_ flags that are valid to be passed
16571   ** down into the VFS layer.  Some SQLCIPHER_OPEN_ flags (for example,
16572   ** SQLCIPHER_OPEN_FULLMUTEX or SQLCIPHER_OPEN_SHAREDCACHE) are blocked before
16573   ** reaching the VFS. */
16574   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
16575   assert( rc==SQLCIPHER_OK || pFile->pMethods==0 );
16576   return rc;
16577 }
16578 SQLCIPHER_PRIVATE int sqlcipher3OsDelete(sqlcipher3_vfs *pVfs, const char *zPath, int dirSync){
16579   return pVfs->xDelete(pVfs, zPath, dirSync);
16580 }
16581 SQLCIPHER_PRIVATE int sqlcipher3OsAccess(
16582   sqlcipher3_vfs *pVfs, 
16583   const char *zPath, 
16584   int flags, 
16585   int *pResOut
16586 ){
16587   DO_OS_MALLOC_TEST(0);
16588   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
16589 }
16590 SQLCIPHER_PRIVATE int sqlcipher3OsFullPathname(
16591   sqlcipher3_vfs *pVfs, 
16592   const char *zPath, 
16593   int nPathOut, 
16594   char *zPathOut
16595 ){
16596   zPathOut[0] = 0;
16597   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
16598 }
16599 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
16600 SQLCIPHER_PRIVATE void *sqlcipher3OsDlOpen(sqlcipher3_vfs *pVfs, const char *zPath){
16601   return pVfs->xDlOpen(pVfs, zPath);
16602 }
16603 SQLCIPHER_PRIVATE void sqlcipher3OsDlError(sqlcipher3_vfs *pVfs, int nByte, char *zBufOut){
16604   pVfs->xDlError(pVfs, nByte, zBufOut);
16605 }
16606 SQLCIPHER_PRIVATE void (*sqlcipher3OsDlSym(sqlcipher3_vfs *pVfs, void *pHdle, const char *zSym))(void){
16607   return pVfs->xDlSym(pVfs, pHdle, zSym);
16608 }
16609 SQLCIPHER_PRIVATE void sqlcipher3OsDlClose(sqlcipher3_vfs *pVfs, void *pHandle){
16610   pVfs->xDlClose(pVfs, pHandle);
16611 }
16612 #endif /* SQLCIPHER_OMIT_LOAD_EXTENSION */
16613 SQLCIPHER_PRIVATE int sqlcipher3OsRandomness(sqlcipher3_vfs *pVfs, int nByte, char *zBufOut){
16614   return pVfs->xRandomness(pVfs, nByte, zBufOut);
16615 }
16616 SQLCIPHER_PRIVATE int sqlcipher3OsSleep(sqlcipher3_vfs *pVfs, int nMicro){
16617   return pVfs->xSleep(pVfs, nMicro);
16618 }
16619 SQLCIPHER_PRIVATE int sqlcipher3OsCurrentTimeInt64(sqlcipher3_vfs *pVfs, sqlcipher3_int64 *pTimeOut){
16620   int rc;
16621   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
16622   ** method to get the current date and time if that method is available
16623   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
16624   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
16625   ** unavailable.
16626   */
16627   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
16628     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
16629   }else{
16630     double r;
16631     rc = pVfs->xCurrentTime(pVfs, &r);
16632     *pTimeOut = (sqlcipher3_int64)(r*86400000.0);
16633   }
16634   return rc;
16635 }
16636
16637 SQLCIPHER_PRIVATE int sqlcipher3OsOpenMalloc(
16638   sqlcipher3_vfs *pVfs, 
16639   const char *zFile, 
16640   sqlcipher3_file **ppFile, 
16641   int flags,
16642   int *pOutFlags
16643 ){
16644   int rc = SQLCIPHER_NOMEM;
16645   sqlcipher3_file *pFile;
16646   pFile = (sqlcipher3_file *)sqlcipher3MallocZero(pVfs->szOsFile);
16647   if( pFile ){
16648     rc = sqlcipher3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
16649     if( rc!=SQLCIPHER_OK ){
16650       sqlcipher3_free(pFile);
16651     }else{
16652       *ppFile = pFile;
16653     }
16654   }
16655   return rc;
16656 }
16657 SQLCIPHER_PRIVATE int sqlcipher3OsCloseFree(sqlcipher3_file *pFile){
16658   int rc = SQLCIPHER_OK;
16659   assert( pFile );
16660   rc = sqlcipher3OsClose(pFile);
16661   sqlcipher3_free(pFile);
16662   return rc;
16663 }
16664
16665 /*
16666 ** This function is a wrapper around the OS specific implementation of
16667 ** sqlcipher3_os_init(). The purpose of the wrapper is to provide the
16668 ** ability to simulate a malloc failure, so that the handling of an
16669 ** error in sqlcipher3_os_init() by the upper layers can be tested.
16670 */
16671 SQLCIPHER_PRIVATE int sqlcipher3OsInit(void){
16672   void *p = sqlcipher3_malloc(10);
16673   if( p==0 ) return SQLCIPHER_NOMEM;
16674   sqlcipher3_free(p);
16675   return sqlcipher3_os_init();
16676 }
16677
16678 /*
16679 ** The list of all registered VFS implementations.
16680 */
16681 static sqlcipher3_vfs * SQLCIPHER_WSD vfsList = 0;
16682 #define vfsList GLOBAL(sqlcipher3_vfs *, vfsList)
16683
16684 /*
16685 ** Locate a VFS by name.  If no name is given, simply return the
16686 ** first VFS on the list.
16687 */
16688 SQLCIPHER_API sqlcipher3_vfs *sqlcipher3_vfs_find(const char *zVfs){
16689   sqlcipher3_vfs *pVfs = 0;
16690 #if SQLCIPHER_THREADSAFE
16691   sqlcipher3_mutex *mutex;
16692 #endif
16693 #ifndef SQLCIPHER_OMIT_AUTOINIT
16694   int rc = sqlcipher3_initialize();
16695   if( rc ) return 0;
16696 #endif
16697 #if SQLCIPHER_THREADSAFE
16698   mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
16699 #endif
16700   sqlcipher3_mutex_enter(mutex);
16701   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
16702     if( zVfs==0 ) break;
16703     if( strcmp(zVfs, pVfs->zName)==0 ) break;
16704   }
16705   sqlcipher3_mutex_leave(mutex);
16706   return pVfs;
16707 }
16708
16709 /*
16710 ** Unlink a VFS from the linked list
16711 */
16712 static void vfsUnlink(sqlcipher3_vfs *pVfs){
16713   assert( sqlcipher3_mutex_held(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER)) );
16714   if( pVfs==0 ){
16715     /* No-op */
16716   }else if( vfsList==pVfs ){
16717     vfsList = pVfs->pNext;
16718   }else if( vfsList ){
16719     sqlcipher3_vfs *p = vfsList;
16720     while( p->pNext && p->pNext!=pVfs ){
16721       p = p->pNext;
16722     }
16723     if( p->pNext==pVfs ){
16724       p->pNext = pVfs->pNext;
16725     }
16726   }
16727 }
16728
16729 /*
16730 ** Register a VFS with the system.  It is harmless to register the same
16731 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
16732 ** true.
16733 */
16734 SQLCIPHER_API int sqlcipher3_vfs_register(sqlcipher3_vfs *pVfs, int makeDflt){
16735   MUTEX_LOGIC(sqlcipher3_mutex *mutex;)
16736 #ifndef SQLCIPHER_OMIT_AUTOINIT
16737   int rc = sqlcipher3_initialize();
16738   if( rc ) return rc;
16739 #endif
16740   MUTEX_LOGIC( mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER); )
16741   sqlcipher3_mutex_enter(mutex);
16742   vfsUnlink(pVfs);
16743   if( makeDflt || vfsList==0 ){
16744     pVfs->pNext = vfsList;
16745     vfsList = pVfs;
16746   }else{
16747     pVfs->pNext = vfsList->pNext;
16748     vfsList->pNext = pVfs;
16749   }
16750   assert(vfsList);
16751   sqlcipher3_mutex_leave(mutex);
16752   return SQLCIPHER_OK;
16753 }
16754
16755 /*
16756 ** Unregister a VFS so that it is no longer accessible.
16757 */
16758 SQLCIPHER_API int sqlcipher3_vfs_unregister(sqlcipher3_vfs *pVfs){
16759 #if SQLCIPHER_THREADSAFE
16760   sqlcipher3_mutex *mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
16761 #endif
16762   sqlcipher3_mutex_enter(mutex);
16763   vfsUnlink(pVfs);
16764   sqlcipher3_mutex_leave(mutex);
16765   return SQLCIPHER_OK;
16766 }
16767
16768 /************** End of os.c **************************************************/
16769 /************** Begin file fault.c *******************************************/
16770 /*
16771 ** 2008 Jan 22
16772 **
16773 ** The author disclaims copyright to this source code.  In place of
16774 ** a legal notice, here is a blessing:
16775 **
16776 **    May you do good and not evil.
16777 **    May you find forgiveness for yourself and forgive others.
16778 **    May you share freely, never taking more than you give.
16779 **
16780 *************************************************************************
16781 **
16782 ** This file contains code to support the concept of "benign" 
16783 ** malloc failures (when the xMalloc() or xRealloc() method of the
16784 ** sqlcipher3_mem_methods structure fails to allocate a block of memory
16785 ** and returns 0). 
16786 **
16787 ** Most malloc failures are non-benign. After they occur, SQLite
16788 ** abandons the current operation and returns an error code (usually
16789 ** SQLCIPHER_NOMEM) to the user. However, sometimes a fault is not necessarily
16790 ** fatal. For example, if a malloc fails while resizing a hash table, this 
16791 ** is completely recoverable simply by not carrying out the resize. The 
16792 ** hash table will continue to function normally.  So a malloc failure 
16793 ** during a hash table resize is a benign fault.
16794 */
16795
16796
16797 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
16798
16799 /*
16800 ** Global variables.
16801 */
16802 typedef struct BenignMallocHooks BenignMallocHooks;
16803 static SQLCIPHER_WSD struct BenignMallocHooks {
16804   void (*xBenignBegin)(void);
16805   void (*xBenignEnd)(void);
16806 } sqlcipher3Hooks = { 0, 0 };
16807
16808 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
16809 ** structure.  If writable static data is unsupported on the target,
16810 ** we have to locate the state vector at run-time.  In the more common
16811 ** case where writable static data is supported, wsdHooks can refer directly
16812 ** to the "sqlcipher3Hooks" state vector declared above.
16813 */
16814 #ifdef SQLCIPHER_OMIT_WSD
16815 # define wsdHooksInit \
16816   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlcipher3Hooks)
16817 # define wsdHooks x[0]
16818 #else
16819 # define wsdHooksInit
16820 # define wsdHooks sqlcipher3Hooks
16821 #endif
16822
16823
16824 /*
16825 ** Register hooks to call when sqlcipher3BeginBenignMalloc() and
16826 ** sqlcipher3EndBenignMalloc() are called, respectively.
16827 */
16828 SQLCIPHER_PRIVATE void sqlcipher3BenignMallocHooks(
16829   void (*xBenignBegin)(void),
16830   void (*xBenignEnd)(void)
16831 ){
16832   wsdHooksInit;
16833   wsdHooks.xBenignBegin = xBenignBegin;
16834   wsdHooks.xBenignEnd = xBenignEnd;
16835 }
16836
16837 /*
16838 ** This (sqlcipher3EndBenignMalloc()) is called by SQLite code to indicate that
16839 ** subsequent malloc failures are benign. A call to sqlcipher3EndBenignMalloc()
16840 ** indicates that subsequent malloc failures are non-benign.
16841 */
16842 SQLCIPHER_PRIVATE void sqlcipher3BeginBenignMalloc(void){
16843   wsdHooksInit;
16844   if( wsdHooks.xBenignBegin ){
16845     wsdHooks.xBenignBegin();
16846   }
16847 }
16848 SQLCIPHER_PRIVATE void sqlcipher3EndBenignMalloc(void){
16849   wsdHooksInit;
16850   if( wsdHooks.xBenignEnd ){
16851     wsdHooks.xBenignEnd();
16852   }
16853 }
16854
16855 #endif   /* #ifndef SQLCIPHER_OMIT_BUILTIN_TEST */
16856
16857 /************** End of fault.c ***********************************************/
16858 /************** Begin file mem0.c ********************************************/
16859 /*
16860 ** 2008 October 28
16861 **
16862 ** The author disclaims copyright to this source code.  In place of
16863 ** a legal notice, here is a blessing:
16864 **
16865 **    May you do good and not evil.
16866 **    May you find forgiveness for yourself and forgive others.
16867 **    May you share freely, never taking more than you give.
16868 **
16869 *************************************************************************
16870 **
16871 ** This file contains a no-op memory allocation drivers for use when
16872 ** SQLCIPHER_ZERO_MALLOC is defined.  The allocation drivers implemented
16873 ** here always fail.  SQLite will not operate with these drivers.  These
16874 ** are merely placeholders.  Real drivers must be substituted using
16875 ** sqlcipher3_config() before SQLite will operate.
16876 */
16877
16878 /*
16879 ** This version of the memory allocator is the default.  It is
16880 ** used when no other memory allocator is specified using compile-time
16881 ** macros.
16882 */
16883 #ifdef SQLCIPHER_ZERO_MALLOC
16884
16885 /*
16886 ** No-op versions of all memory allocation routines
16887 */
16888 static void *sqlcipher3MemMalloc(int nByte){ return 0; }
16889 static void sqlcipher3MemFree(void *pPrior){ return; }
16890 static void *sqlcipher3MemRealloc(void *pPrior, int nByte){ return 0; }
16891 static int sqlcipher3MemSize(void *pPrior){ return 0; }
16892 static int sqlcipher3MemRoundup(int n){ return n; }
16893 static int sqlcipher3MemInit(void *NotUsed){ return SQLCIPHER_OK; }
16894 static void sqlcipher3MemShutdown(void *NotUsed){ return; }
16895
16896 /*
16897 ** This routine is the only routine in this file with external linkage.
16898 **
16899 ** Populate the low-level memory allocation function pointers in
16900 ** sqlcipher3GlobalConfig.m with pointers to the routines in this file.
16901 */
16902 SQLCIPHER_PRIVATE void sqlcipher3MemSetDefault(void){
16903   static const sqlcipher3_mem_methods defaultMethods = {
16904      sqlcipher3MemMalloc,
16905      sqlcipher3MemFree,
16906      sqlcipher3MemRealloc,
16907      sqlcipher3MemSize,
16908      sqlcipher3MemRoundup,
16909      sqlcipher3MemInit,
16910      sqlcipher3MemShutdown,
16911      0
16912   };
16913   sqlcipher3_config(SQLCIPHER_CONFIG_MALLOC, &defaultMethods);
16914 }
16915
16916 #endif /* SQLCIPHER_ZERO_MALLOC */
16917
16918 /************** End of mem0.c ************************************************/
16919 /************** Begin file mem1.c ********************************************/
16920 /*
16921 ** 2007 August 14
16922 **
16923 ** The author disclaims copyright to this source code.  In place of
16924 ** a legal notice, here is a blessing:
16925 **
16926 **    May you do good and not evil.
16927 **    May you find forgiveness for yourself and forgive others.
16928 **    May you share freely, never taking more than you give.
16929 **
16930 *************************************************************************
16931 **
16932 ** This file contains low-level memory allocation drivers for when
16933 ** SQLite will use the standard C-library malloc/realloc/free interface
16934 ** to obtain the memory it needs.
16935 **
16936 ** This file contains implementations of the low-level memory allocation
16937 ** routines specified in the sqlcipher3_mem_methods object.
16938 */
16939
16940 /*
16941 ** This version of the memory allocator is the default.  It is
16942 ** used when no other memory allocator is specified using compile-time
16943 ** macros.
16944 */
16945 #ifdef SQLCIPHER_SYSTEM_MALLOC
16946
16947 /*
16948 ** Like malloc(), but remember the size of the allocation
16949 ** so that we can find it later using sqlcipher3MemSize().
16950 **
16951 ** For this low-level routine, we are guaranteed that nByte>0 because
16952 ** cases of nByte<=0 will be intercepted and dealt with by higher level
16953 ** routines.
16954 */
16955 static void *sqlcipher3MemMalloc(int nByte){
16956   sqlcipher3_int64 *p;
16957   assert( nByte>0 );
16958   nByte = ROUND8(nByte);
16959   p = malloc( nByte+8 );
16960   if( p ){
16961     p[0] = nByte;
16962     p++;
16963   }else{
16964     testcase( sqlcipher3GlobalConfig.xLog!=0 );
16965     sqlcipher3_log(SQLCIPHER_NOMEM, "failed to allocate %u bytes of memory", nByte);
16966   }
16967   return (void *)p;
16968 }
16969
16970 /*
16971 ** Like free() but works for allocations obtained from sqlcipher3MemMalloc()
16972 ** or sqlcipher3MemRealloc().
16973 **
16974 ** For this low-level routine, we already know that pPrior!=0 since
16975 ** cases where pPrior==0 will have been intecepted and dealt with
16976 ** by higher-level routines.
16977 */
16978 static void sqlcipher3MemFree(void *pPrior){
16979   sqlcipher3_int64 *p = (sqlcipher3_int64*)pPrior;
16980   assert( pPrior!=0 );
16981   p--;
16982   free(p);
16983 }
16984
16985 /*
16986 ** Report the allocated size of a prior return from xMalloc()
16987 ** or xRealloc().
16988 */
16989 static int sqlcipher3MemSize(void *pPrior){
16990   sqlcipher3_int64 *p;
16991   if( pPrior==0 ) return 0;
16992   p = (sqlcipher3_int64*)pPrior;
16993   p--;
16994   return (int)p[0];
16995 }
16996
16997 /*
16998 ** Like realloc().  Resize an allocation previously obtained from
16999 ** sqlcipher3MemMalloc().
17000 **
17001 ** For this low-level interface, we know that pPrior!=0.  Cases where
17002 ** pPrior==0 while have been intercepted by higher-level routine and
17003 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
17004 ** cases where nByte<=0 will have been intercepted by higher-level
17005 ** routines and redirected to xFree.
17006 */
17007 static void *sqlcipher3MemRealloc(void *pPrior, int nByte){
17008   sqlcipher3_int64 *p = (sqlcipher3_int64*)pPrior;
17009   assert( pPrior!=0 && nByte>0 );
17010   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
17011   p--;
17012   p = realloc(p, nByte+8 );
17013   if( p ){
17014     p[0] = nByte;
17015     p++;
17016   }else{
17017     testcase( sqlcipher3GlobalConfig.xLog!=0 );
17018     sqlcipher3_log(SQLCIPHER_NOMEM,
17019       "failed memory resize %u to %u bytes",
17020       sqlcipher3MemSize(pPrior), nByte);
17021   }
17022   return (void*)p;
17023 }
17024
17025 /*
17026 ** Round up a request size to the next valid allocation size.
17027 */
17028 static int sqlcipher3MemRoundup(int n){
17029   return ROUND8(n);
17030 }
17031
17032 /*
17033 ** Initialize this module.
17034 */
17035 static int sqlcipher3MemInit(void *NotUsed){
17036   UNUSED_PARAMETER(NotUsed);
17037   return SQLCIPHER_OK;
17038 }
17039
17040 /*
17041 ** Deinitialize this module.
17042 */
17043 static void sqlcipher3MemShutdown(void *NotUsed){
17044   UNUSED_PARAMETER(NotUsed);
17045   return;
17046 }
17047
17048 /*
17049 ** This routine is the only routine in this file with external linkage.
17050 **
17051 ** Populate the low-level memory allocation function pointers in
17052 ** sqlcipher3GlobalConfig.m with pointers to the routines in this file.
17053 */
17054 SQLCIPHER_PRIVATE void sqlcipher3MemSetDefault(void){
17055   static const sqlcipher3_mem_methods defaultMethods = {
17056      sqlcipher3MemMalloc,
17057      sqlcipher3MemFree,
17058      sqlcipher3MemRealloc,
17059      sqlcipher3MemSize,
17060      sqlcipher3MemRoundup,
17061      sqlcipher3MemInit,
17062      sqlcipher3MemShutdown,
17063      0
17064   };
17065   sqlcipher3_config(SQLCIPHER_CONFIG_MALLOC, &defaultMethods);
17066 }
17067
17068 #endif /* SQLCIPHER_SYSTEM_MALLOC */
17069
17070 /************** End of mem1.c ************************************************/
17071 /************** Begin file mem2.c ********************************************/
17072 /*
17073 ** 2007 August 15
17074 **
17075 ** The author disclaims copyright to this source code.  In place of
17076 ** a legal notice, here is a blessing:
17077 **
17078 **    May you do good and not evil.
17079 **    May you find forgiveness for yourself and forgive others.
17080 **    May you share freely, never taking more than you give.
17081 **
17082 *************************************************************************
17083 **
17084 ** This file contains low-level memory allocation drivers for when
17085 ** SQLite will use the standard C-library malloc/realloc/free interface
17086 ** to obtain the memory it needs while adding lots of additional debugging
17087 ** information to each allocation in order to help detect and fix memory
17088 ** leaks and memory usage errors.
17089 **
17090 ** This file contains implementations of the low-level memory allocation
17091 ** routines specified in the sqlcipher3_mem_methods object.
17092 */
17093
17094 /*
17095 ** This version of the memory allocator is used only if the
17096 ** SQLCIPHER_MEMDEBUG macro is defined
17097 */
17098 #ifdef SQLCIPHER_MEMDEBUG
17099
17100 /*
17101 ** The backtrace functionality is only available with GLIBC
17102 */
17103 #ifdef __GLIBC__
17104   extern int backtrace(void**,int);
17105   extern void backtrace_symbols_fd(void*const*,int,int);
17106 #else
17107 # define backtrace(A,B) 1
17108 # define backtrace_symbols_fd(A,B,C)
17109 #endif
17110 /* #include <stdio.h> */
17111
17112 /*
17113 ** Each memory allocation looks like this:
17114 **
17115 **  ------------------------------------------------------------------------
17116 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
17117 **  ------------------------------------------------------------------------
17118 **
17119 ** The application code sees only a pointer to the allocation.  We have
17120 ** to back up from the allocation pointer to find the MemBlockHdr.  The
17121 ** MemBlockHdr tells us the size of the allocation and the number of
17122 ** backtrace pointers.  There is also a guard word at the end of the
17123 ** MemBlockHdr.
17124 */
17125 struct MemBlockHdr {
17126   i64 iSize;                          /* Size of this allocation */
17127   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
17128   char nBacktrace;                    /* Number of backtraces on this alloc */
17129   char nBacktraceSlots;               /* Available backtrace slots */
17130   u8 nTitle;                          /* Bytes of title; includes '\0' */
17131   u8 eType;                           /* Allocation type code */
17132   int iForeGuard;                     /* Guard word for sanity */
17133 };
17134
17135 /*
17136 ** Guard words
17137 */
17138 #define FOREGUARD 0x80F5E153
17139 #define REARGUARD 0xE4676B53
17140
17141 /*
17142 ** Number of malloc size increments to track.
17143 */
17144 #define NCSIZE  1000
17145
17146 /*
17147 ** All of the static variables used by this module are collected
17148 ** into a single structure named "mem".  This is to keep the
17149 ** static variables organized and to reduce namespace pollution
17150 ** when this module is combined with other in the amalgamation.
17151 */
17152 static struct {
17153   
17154   /*
17155   ** Mutex to control access to the memory allocation subsystem.
17156   */
17157   sqlcipher3_mutex *mutex;
17158
17159   /*
17160   ** Head and tail of a linked list of all outstanding allocations
17161   */
17162   struct MemBlockHdr *pFirst;
17163   struct MemBlockHdr *pLast;
17164   
17165   /*
17166   ** The number of levels of backtrace to save in new allocations.
17167   */
17168   int nBacktrace;
17169   void (*xBacktrace)(int, int, void **);
17170
17171   /*
17172   ** Title text to insert in front of each block
17173   */
17174   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
17175   char zTitle[100];  /* The title text */
17176
17177   /* 
17178   ** sqlcipher3MallocDisallow() increments the following counter.
17179   ** sqlcipher3MallocAllow() decrements it.
17180   */
17181   int disallow; /* Do not allow memory allocation */
17182
17183   /*
17184   ** Gather statistics on the sizes of memory allocations.
17185   ** nAlloc[i] is the number of allocation attempts of i*8
17186   ** bytes.  i==NCSIZE is the number of allocation attempts for
17187   ** sizes more than NCSIZE*8 bytes.
17188   */
17189   int nAlloc[NCSIZE];      /* Total number of allocations */
17190   int nCurrent[NCSIZE];    /* Current number of allocations */
17191   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
17192
17193 } mem;
17194
17195
17196 /*
17197 ** Adjust memory usage statistics
17198 */
17199 static void adjustStats(int iSize, int increment){
17200   int i = ROUND8(iSize)/8;
17201   if( i>NCSIZE-1 ){
17202     i = NCSIZE - 1;
17203   }
17204   if( increment>0 ){
17205     mem.nAlloc[i]++;
17206     mem.nCurrent[i]++;
17207     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
17208       mem.mxCurrent[i] = mem.nCurrent[i];
17209     }
17210   }else{
17211     mem.nCurrent[i]--;
17212     assert( mem.nCurrent[i]>=0 );
17213   }
17214 }
17215
17216 /*
17217 ** Given an allocation, find the MemBlockHdr for that allocation.
17218 **
17219 ** This routine checks the guards at either end of the allocation and
17220 ** if they are incorrect it asserts.
17221 */
17222 static struct MemBlockHdr *sqlcipher3MemsysGetHeader(void *pAllocation){
17223   struct MemBlockHdr *p;
17224   int *pInt;
17225   u8 *pU8;
17226   int nReserve;
17227
17228   p = (struct MemBlockHdr*)pAllocation;
17229   p--;
17230   assert( p->iForeGuard==(int)FOREGUARD );
17231   nReserve = ROUND8(p->iSize);
17232   pInt = (int*)pAllocation;
17233   pU8 = (u8*)pAllocation;
17234   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
17235   /* This checks any of the "extra" bytes allocated due
17236   ** to rounding up to an 8 byte boundary to ensure 
17237   ** they haven't been overwritten.
17238   */
17239   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
17240   return p;
17241 }
17242
17243 /*
17244 ** Return the number of bytes currently allocated at address p.
17245 */
17246 static int sqlcipher3MemSize(void *p){
17247   struct MemBlockHdr *pHdr;
17248   if( !p ){
17249     return 0;
17250   }
17251   pHdr = sqlcipher3MemsysGetHeader(p);
17252   return pHdr->iSize;
17253 }
17254
17255 /*
17256 ** Initialize the memory allocation subsystem.
17257 */
17258 static int sqlcipher3MemInit(void *NotUsed){
17259   UNUSED_PARAMETER(NotUsed);
17260   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
17261   if( !sqlcipher3GlobalConfig.bMemstat ){
17262     /* If memory status is enabled, then the malloc.c wrapper will already
17263     ** hold the STATIC_MEM mutex when the routines here are invoked. */
17264     mem.mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MEM);
17265   }
17266   return SQLCIPHER_OK;
17267 }
17268
17269 /*
17270 ** Deinitialize the memory allocation subsystem.
17271 */
17272 static void sqlcipher3MemShutdown(void *NotUsed){
17273   UNUSED_PARAMETER(NotUsed);
17274   mem.mutex = 0;
17275 }
17276
17277 /*
17278 ** Round up a request size to the next valid allocation size.
17279 */
17280 static int sqlcipher3MemRoundup(int n){
17281   return ROUND8(n);
17282 }
17283
17284 /*
17285 ** Fill a buffer with pseudo-random bytes.  This is used to preset
17286 ** the content of a new memory allocation to unpredictable values and
17287 ** to clear the content of a freed allocation to unpredictable values.
17288 */
17289 static void randomFill(char *pBuf, int nByte){
17290   unsigned int x, y, r;
17291   x = SQLCIPHER_PTR_TO_INT(pBuf);
17292   y = nByte | 1;
17293   while( nByte >= 4 ){
17294     x = (x>>1) ^ (-(x&1) & 0xd0000001);
17295     y = y*1103515245 + 12345;
17296     r = x ^ y;
17297     *(int*)pBuf = r;
17298     pBuf += 4;
17299     nByte -= 4;
17300   }
17301   while( nByte-- > 0 ){
17302     x = (x>>1) ^ (-(x&1) & 0xd0000001);
17303     y = y*1103515245 + 12345;
17304     r = x ^ y;
17305     *(pBuf++) = r & 0xff;
17306   }
17307 }
17308
17309 /*
17310 ** Allocate nByte bytes of memory.
17311 */
17312 static void *sqlcipher3MemMalloc(int nByte){
17313   struct MemBlockHdr *pHdr;
17314   void **pBt;
17315   char *z;
17316   int *pInt;
17317   void *p = 0;
17318   int totalSize;
17319   int nReserve;
17320   sqlcipher3_mutex_enter(mem.mutex);
17321   assert( mem.disallow==0 );
17322   nReserve = ROUND8(nByte);
17323   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
17324                mem.nBacktrace*sizeof(void*) + mem.nTitle;
17325   p = malloc(totalSize);
17326   if( p ){
17327     z = p;
17328     pBt = (void**)&z[mem.nTitle];
17329     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
17330     pHdr->pNext = 0;
17331     pHdr->pPrev = mem.pLast;
17332     if( mem.pLast ){
17333       mem.pLast->pNext = pHdr;
17334     }else{
17335       mem.pFirst = pHdr;
17336     }
17337     mem.pLast = pHdr;
17338     pHdr->iForeGuard = FOREGUARD;
17339     pHdr->eType = MEMTYPE_HEAP;
17340     pHdr->nBacktraceSlots = mem.nBacktrace;
17341     pHdr->nTitle = mem.nTitle;
17342     if( mem.nBacktrace ){
17343       void *aAddr[40];
17344       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
17345       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
17346       assert(pBt[0]);
17347       if( mem.xBacktrace ){
17348         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
17349       }
17350     }else{
17351       pHdr->nBacktrace = 0;
17352     }
17353     if( mem.nTitle ){
17354       memcpy(z, mem.zTitle, mem.nTitle);
17355     }
17356     pHdr->iSize = nByte;
17357     adjustStats(nByte, +1);
17358     pInt = (int*)&pHdr[1];
17359     pInt[nReserve/sizeof(int)] = REARGUARD;
17360     randomFill((char*)pInt, nByte);
17361     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
17362     p = (void*)pInt;
17363   }
17364   sqlcipher3_mutex_leave(mem.mutex);
17365   return p; 
17366 }
17367
17368 /*
17369 ** Free memory.
17370 */
17371 static void sqlcipher3MemFree(void *pPrior){
17372   struct MemBlockHdr *pHdr;
17373   void **pBt;
17374   char *z;
17375   assert( sqlcipher3GlobalConfig.bMemstat || sqlcipher3GlobalConfig.bCoreMutex==0 
17376        || mem.mutex!=0 );
17377   pHdr = sqlcipher3MemsysGetHeader(pPrior);
17378   pBt = (void**)pHdr;
17379   pBt -= pHdr->nBacktraceSlots;
17380   sqlcipher3_mutex_enter(mem.mutex);
17381   if( pHdr->pPrev ){
17382     assert( pHdr->pPrev->pNext==pHdr );
17383     pHdr->pPrev->pNext = pHdr->pNext;
17384   }else{
17385     assert( mem.pFirst==pHdr );
17386     mem.pFirst = pHdr->pNext;
17387   }
17388   if( pHdr->pNext ){
17389     assert( pHdr->pNext->pPrev==pHdr );
17390     pHdr->pNext->pPrev = pHdr->pPrev;
17391   }else{
17392     assert( mem.pLast==pHdr );
17393     mem.pLast = pHdr->pPrev;
17394   }
17395   z = (char*)pBt;
17396   z -= pHdr->nTitle;
17397   adjustStats(pHdr->iSize, -1);
17398   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
17399                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
17400   free(z);
17401   sqlcipher3_mutex_leave(mem.mutex);  
17402 }
17403
17404 /*
17405 ** Change the size of an existing memory allocation.
17406 **
17407 ** For this debugging implementation, we *always* make a copy of the
17408 ** allocation into a new place in memory.  In this way, if the 
17409 ** higher level code is using pointer to the old allocation, it is 
17410 ** much more likely to break and we are much more liking to find
17411 ** the error.
17412 */
17413 static void *sqlcipher3MemRealloc(void *pPrior, int nByte){
17414   struct MemBlockHdr *pOldHdr;
17415   void *pNew;
17416   assert( mem.disallow==0 );
17417   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
17418   pOldHdr = sqlcipher3MemsysGetHeader(pPrior);
17419   pNew = sqlcipher3MemMalloc(nByte);
17420   if( pNew ){
17421     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
17422     if( nByte>pOldHdr->iSize ){
17423       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
17424     }
17425     sqlcipher3MemFree(pPrior);
17426   }
17427   return pNew;
17428 }
17429
17430 /*
17431 ** Populate the low-level memory allocation function pointers in
17432 ** sqlcipher3GlobalConfig.m with pointers to the routines in this file.
17433 */
17434 SQLCIPHER_PRIVATE void sqlcipher3MemSetDefault(void){
17435   static const sqlcipher3_mem_methods defaultMethods = {
17436      sqlcipher3MemMalloc,
17437      sqlcipher3MemFree,
17438      sqlcipher3MemRealloc,
17439      sqlcipher3MemSize,
17440      sqlcipher3MemRoundup,
17441      sqlcipher3MemInit,
17442      sqlcipher3MemShutdown,
17443      0
17444   };
17445   sqlcipher3_config(SQLCIPHER_CONFIG_MALLOC, &defaultMethods);
17446 }
17447
17448 /*
17449 ** Set the "type" of an allocation.
17450 */
17451 SQLCIPHER_PRIVATE void sqlcipher3MemdebugSetType(void *p, u8 eType){
17452   if( p && sqlcipher3GlobalConfig.m.xMalloc==sqlcipher3MemMalloc ){
17453     struct MemBlockHdr *pHdr;
17454     pHdr = sqlcipher3MemsysGetHeader(p);
17455     assert( pHdr->iForeGuard==FOREGUARD );
17456     pHdr->eType = eType;
17457   }
17458 }
17459
17460 /*
17461 ** Return TRUE if the mask of type in eType matches the type of the
17462 ** allocation p.  Also return true if p==NULL.
17463 **
17464 ** This routine is designed for use within an assert() statement, to
17465 ** verify the type of an allocation.  For example:
17466 **
17467 **     assert( sqlcipher3MemdebugHasType(p, MEMTYPE_DB) );
17468 */
17469 SQLCIPHER_PRIVATE int sqlcipher3MemdebugHasType(void *p, u8 eType){
17470   int rc = 1;
17471   if( p && sqlcipher3GlobalConfig.m.xMalloc==sqlcipher3MemMalloc ){
17472     struct MemBlockHdr *pHdr;
17473     pHdr = sqlcipher3MemsysGetHeader(p);
17474     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
17475     if( (pHdr->eType&eType)==0 ){
17476       rc = 0;
17477     }
17478   }
17479   return rc;
17480 }
17481
17482 /*
17483 ** Return TRUE if the mask of type in eType matches no bits of the type of the
17484 ** allocation p.  Also return true if p==NULL.
17485 **
17486 ** This routine is designed for use within an assert() statement, to
17487 ** verify the type of an allocation.  For example:
17488 **
17489 **     assert( sqlcipher3MemdebugNoType(p, MEMTYPE_DB) );
17490 */
17491 SQLCIPHER_PRIVATE int sqlcipher3MemdebugNoType(void *p, u8 eType){
17492   int rc = 1;
17493   if( p && sqlcipher3GlobalConfig.m.xMalloc==sqlcipher3MemMalloc ){
17494     struct MemBlockHdr *pHdr;
17495     pHdr = sqlcipher3MemsysGetHeader(p);
17496     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
17497     if( (pHdr->eType&eType)!=0 ){
17498       rc = 0;
17499     }
17500   }
17501   return rc;
17502 }
17503
17504 /*
17505 ** Set the number of backtrace levels kept for each allocation.
17506 ** A value of zero turns off backtracing.  The number is always rounded
17507 ** up to a multiple of 2.
17508 */
17509 SQLCIPHER_PRIVATE void sqlcipher3MemdebugBacktrace(int depth){
17510   if( depth<0 ){ depth = 0; }
17511   if( depth>20 ){ depth = 20; }
17512   depth = (depth+1)&0xfe;
17513   mem.nBacktrace = depth;
17514 }
17515
17516 SQLCIPHER_PRIVATE void sqlcipher3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
17517   mem.xBacktrace = xBacktrace;
17518 }
17519
17520 /*
17521 ** Set the title string for subsequent allocations.
17522 */
17523 SQLCIPHER_PRIVATE void sqlcipher3MemdebugSettitle(const char *zTitle){
17524   unsigned int n = sqlcipher3Strlen30(zTitle) + 1;
17525   sqlcipher3_mutex_enter(mem.mutex);
17526   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
17527   memcpy(mem.zTitle, zTitle, n);
17528   mem.zTitle[n] = 0;
17529   mem.nTitle = ROUND8(n);
17530   sqlcipher3_mutex_leave(mem.mutex);
17531 }
17532
17533 SQLCIPHER_PRIVATE void sqlcipher3MemdebugSync(){
17534   struct MemBlockHdr *pHdr;
17535   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17536     void **pBt = (void**)pHdr;
17537     pBt -= pHdr->nBacktraceSlots;
17538     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
17539   }
17540 }
17541
17542 /*
17543 ** Open the file indicated and write a log of all unfreed memory 
17544 ** allocations into that log.
17545 */
17546 SQLCIPHER_PRIVATE void sqlcipher3MemdebugDump(const char *zFilename){
17547   FILE *out;
17548   struct MemBlockHdr *pHdr;
17549   void **pBt;
17550   int i;
17551   out = fopen(zFilename, "w");
17552   if( out==0 ){
17553     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17554                     zFilename);
17555     return;
17556   }
17557   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17558     char *z = (char*)pHdr;
17559     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
17560     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
17561             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
17562     if( pHdr->nBacktrace ){
17563       fflush(out);
17564       pBt = (void**)pHdr;
17565       pBt -= pHdr->nBacktraceSlots;
17566       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
17567       fprintf(out, "\n");
17568     }
17569   }
17570   fprintf(out, "COUNTS:\n");
17571   for(i=0; i<NCSIZE-1; i++){
17572     if( mem.nAlloc[i] ){
17573       fprintf(out, "   %5d: %10d %10d %10d\n", 
17574             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
17575     }
17576   }
17577   if( mem.nAlloc[NCSIZE-1] ){
17578     fprintf(out, "   %5d: %10d %10d %10d\n",
17579              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
17580              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
17581   }
17582   fclose(out);
17583 }
17584
17585 /*
17586 ** Return the number of times sqlcipher3MemMalloc() has been called.
17587 */
17588 SQLCIPHER_PRIVATE int sqlcipher3MemdebugMallocCount(){
17589   int i;
17590   int nTotal = 0;
17591   for(i=0; i<NCSIZE; i++){
17592     nTotal += mem.nAlloc[i];
17593   }
17594   return nTotal;
17595 }
17596
17597
17598 #endif /* SQLCIPHER_MEMDEBUG */
17599
17600 /************** End of mem2.c ************************************************/
17601 /************** Begin file mem3.c ********************************************/
17602 /*
17603 ** 2007 October 14
17604 **
17605 ** The author disclaims copyright to this source code.  In place of
17606 ** a legal notice, here is a blessing:
17607 **
17608 **    May you do good and not evil.
17609 **    May you find forgiveness for yourself and forgive others.
17610 **    May you share freely, never taking more than you give.
17611 **
17612 *************************************************************************
17613 ** This file contains the C functions that implement a memory
17614 ** allocation subsystem for use by SQLite. 
17615 **
17616 ** This version of the memory allocation subsystem omits all
17617 ** use of malloc(). The SQLite user supplies a block of memory
17618 ** before calling sqlcipher3_initialize() from which allocations
17619 ** are made and returned by the xMalloc() and xRealloc() 
17620 ** implementations. Once sqlcipher3_initialize() has been called,
17621 ** the amount of memory available to SQLite is fixed and cannot
17622 ** be changed.
17623 **
17624 ** This version of the memory allocation subsystem is included
17625 ** in the build only if SQLCIPHER_ENABLE_MEMSYS3 is defined.
17626 */
17627
17628 /*
17629 ** This version of the memory allocator is only built into the library
17630 ** SQLCIPHER_ENABLE_MEMSYS3 is defined. Defining this symbol does not
17631 ** mean that the library will use a memory-pool by default, just that
17632 ** it is available. The mempool allocator is activated by calling
17633 ** sqlcipher3_config().
17634 */
17635 #ifdef SQLCIPHER_ENABLE_MEMSYS3
17636
17637 /*
17638 ** Maximum size (in Mem3Blocks) of a "small" chunk.
17639 */
17640 #define MX_SMALL 10
17641
17642
17643 /*
17644 ** Number of freelist hash slots
17645 */
17646 #define N_HASH  61
17647
17648 /*
17649 ** A memory allocation (also called a "chunk") consists of two or 
17650 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
17651 ** a header that is not returned to the user.
17652 **
17653 ** A chunk is two or more blocks that is either checked out or
17654 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
17655 ** size of the allocation in blocks if the allocation is free.
17656 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
17657 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
17658 ** is true if the previous chunk is checked out and false if the
17659 ** previous chunk is free.  The u.hdr.prevSize field is the size of
17660 ** the previous chunk in blocks if the previous chunk is on the
17661 ** freelist. If the previous chunk is checked out, then
17662 ** u.hdr.prevSize can be part of the data for that chunk and should
17663 ** not be read or written.
17664 **
17665 ** We often identify a chunk by its index in mem3.aPool[].  When
17666 ** this is done, the chunk index refers to the second block of
17667 ** the chunk.  In this way, the first chunk has an index of 1.
17668 ** A chunk index of 0 means "no such chunk" and is the equivalent
17669 ** of a NULL pointer.
17670 **
17671 ** The second block of free chunks is of the form u.list.  The
17672 ** two fields form a double-linked list of chunks of related sizes.
17673 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
17674 ** for smaller chunks and mem3.aiHash[] for larger chunks.
17675 **
17676 ** The second block of a chunk is user data if the chunk is checked 
17677 ** out.  If a chunk is checked out, the user data may extend into
17678 ** the u.hdr.prevSize value of the following chunk.
17679 */
17680 typedef struct Mem3Block Mem3Block;
17681 struct Mem3Block {
17682   union {
17683     struct {
17684       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
17685       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
17686     } hdr;
17687     struct {
17688       u32 next;       /* Index in mem3.aPool[] of next free chunk */
17689       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
17690     } list;
17691   } u;
17692 };
17693
17694 /*
17695 ** All of the static variables used by this module are collected
17696 ** into a single structure named "mem3".  This is to keep the
17697 ** static variables organized and to reduce namespace pollution
17698 ** when this module is combined with other in the amalgamation.
17699 */
17700 static SQLCIPHER_WSD struct Mem3Global {
17701   /*
17702   ** Memory available for allocation. nPool is the size of the array
17703   ** (in Mem3Blocks) pointed to by aPool less 2.
17704   */
17705   u32 nPool;
17706   Mem3Block *aPool;
17707
17708   /*
17709   ** True if we are evaluating an out-of-memory callback.
17710   */
17711   int alarmBusy;
17712   
17713   /*
17714   ** Mutex to control access to the memory allocation subsystem.
17715   */
17716   sqlcipher3_mutex *mutex;
17717   
17718   /*
17719   ** The minimum amount of free space that we have seen.
17720   */
17721   u32 mnMaster;
17722
17723   /*
17724   ** iMaster is the index of the master chunk.  Most new allocations
17725   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
17726   ** of the current master.  iMaster is 0 if there is not master chunk.
17727   ** The master chunk is not in either the aiHash[] or aiSmall[].
17728   */
17729   u32 iMaster;
17730   u32 szMaster;
17731
17732   /*
17733   ** Array of lists of free blocks according to the block size 
17734   ** for smaller chunks, or a hash on the block size for larger
17735   ** chunks.
17736   */
17737   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
17738   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
17739 } mem3 = { 97535575 };
17740
17741 #define mem3 GLOBAL(struct Mem3Global, mem3)
17742
17743 /*
17744 ** Unlink the chunk at mem3.aPool[i] from list it is currently
17745 ** on.  *pRoot is the list that i is a member of.
17746 */
17747 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
17748   u32 next = mem3.aPool[i].u.list.next;
17749   u32 prev = mem3.aPool[i].u.list.prev;
17750   assert( sqlcipher3_mutex_held(mem3.mutex) );
17751   if( prev==0 ){
17752     *pRoot = next;
17753   }else{
17754     mem3.aPool[prev].u.list.next = next;
17755   }
17756   if( next ){
17757     mem3.aPool[next].u.list.prev = prev;
17758   }
17759   mem3.aPool[i].u.list.next = 0;
17760   mem3.aPool[i].u.list.prev = 0;
17761 }
17762
17763 /*
17764 ** Unlink the chunk at index i from 
17765 ** whatever list is currently a member of.
17766 */
17767 static void memsys3Unlink(u32 i){
17768   u32 size, hash;
17769   assert( sqlcipher3_mutex_held(mem3.mutex) );
17770   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17771   assert( i>=1 );
17772   size = mem3.aPool[i-1].u.hdr.size4x/4;
17773   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17774   assert( size>=2 );
17775   if( size <= MX_SMALL ){
17776     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
17777   }else{
17778     hash = size % N_HASH;
17779     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17780   }
17781 }
17782
17783 /*
17784 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
17785 ** at *pRoot.
17786 */
17787 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
17788   assert( sqlcipher3_mutex_held(mem3.mutex) );
17789   mem3.aPool[i].u.list.next = *pRoot;
17790   mem3.aPool[i].u.list.prev = 0;
17791   if( *pRoot ){
17792     mem3.aPool[*pRoot].u.list.prev = i;
17793   }
17794   *pRoot = i;
17795 }
17796
17797 /*
17798 ** Link the chunk at index i into either the appropriate
17799 ** small chunk list, or into the large chunk hash table.
17800 */
17801 static void memsys3Link(u32 i){
17802   u32 size, hash;
17803   assert( sqlcipher3_mutex_held(mem3.mutex) );
17804   assert( i>=1 );
17805   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17806   size = mem3.aPool[i-1].u.hdr.size4x/4;
17807   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17808   assert( size>=2 );
17809   if( size <= MX_SMALL ){
17810     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
17811   }else{
17812     hash = size % N_HASH;
17813     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
17814   }
17815 }
17816
17817 /*
17818 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17819 ** will already be held (obtained by code in malloc.c) if
17820 ** sqlcipher3GlobalConfig.bMemStat is true.
17821 */
17822 static void memsys3Enter(void){
17823   if( sqlcipher3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
17824     mem3.mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MEM);
17825   }
17826   sqlcipher3_mutex_enter(mem3.mutex);
17827 }
17828 static void memsys3Leave(void){
17829   sqlcipher3_mutex_leave(mem3.mutex);
17830 }
17831
17832 /*
17833 ** Called when we are unable to satisfy an allocation of nBytes.
17834 */
17835 static void memsys3OutOfMemory(int nByte){
17836   if( !mem3.alarmBusy ){
17837     mem3.alarmBusy = 1;
17838     assert( sqlcipher3_mutex_held(mem3.mutex) );
17839     sqlcipher3_mutex_leave(mem3.mutex);
17840     sqlcipher3_release_memory(nByte);
17841     sqlcipher3_mutex_enter(mem3.mutex);
17842     mem3.alarmBusy = 0;
17843   }
17844 }
17845
17846
17847 /*
17848 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
17849 ** size parameters for check-out and return a pointer to the 
17850 ** user portion of the chunk.
17851 */
17852 static void *memsys3Checkout(u32 i, u32 nBlock){
17853   u32 x;
17854   assert( sqlcipher3_mutex_held(mem3.mutex) );
17855   assert( i>=1 );
17856   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
17857   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
17858   x = mem3.aPool[i-1].u.hdr.size4x;
17859   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
17860   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
17861   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
17862   return &mem3.aPool[i];
17863 }
17864
17865 /*
17866 ** Carve a piece off of the end of the mem3.iMaster free chunk.
17867 ** Return a pointer to the new allocation.  Or, if the master chunk
17868 ** is not large enough, return 0.
17869 */
17870 static void *memsys3FromMaster(u32 nBlock){
17871   assert( sqlcipher3_mutex_held(mem3.mutex) );
17872   assert( mem3.szMaster>=nBlock );
17873   if( nBlock>=mem3.szMaster-1 ){
17874     /* Use the entire master */
17875     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
17876     mem3.iMaster = 0;
17877     mem3.szMaster = 0;
17878     mem3.mnMaster = 0;
17879     return p;
17880   }else{
17881     /* Split the master block.  Return the tail. */
17882     u32 newi, x;
17883     newi = mem3.iMaster + mem3.szMaster - nBlock;
17884     assert( newi > mem3.iMaster+1 );
17885     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
17886     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
17887     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
17888     mem3.szMaster -= nBlock;
17889     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
17890     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17891     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17892     if( mem3.szMaster < mem3.mnMaster ){
17893       mem3.mnMaster = mem3.szMaster;
17894     }
17895     return (void*)&mem3.aPool[newi];
17896   }
17897 }
17898
17899 /*
17900 ** *pRoot is the head of a list of free chunks of the same size
17901 ** or same size hash.  In other words, *pRoot is an entry in either
17902 ** mem3.aiSmall[] or mem3.aiHash[].  
17903 **
17904 ** This routine examines all entries on the given list and tries
17905 ** to coalesce each entries with adjacent free chunks.  
17906 **
17907 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
17908 ** the current mem3.iMaster with the new larger chunk.  In order for
17909 ** this mem3.iMaster replacement to work, the master chunk must be
17910 ** linked into the hash tables.  That is not the normal state of
17911 ** affairs, of course.  The calling routine must link the master
17912 ** chunk before invoking this routine, then must unlink the (possibly
17913 ** changed) master chunk once this routine has finished.
17914 */
17915 static void memsys3Merge(u32 *pRoot){
17916   u32 iNext, prev, size, i, x;
17917
17918   assert( sqlcipher3_mutex_held(mem3.mutex) );
17919   for(i=*pRoot; i>0; i=iNext){
17920     iNext = mem3.aPool[i].u.list.next;
17921     size = mem3.aPool[i-1].u.hdr.size4x;
17922     assert( (size&1)==0 );
17923     if( (size&2)==0 ){
17924       memsys3UnlinkFromList(i, pRoot);
17925       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
17926       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
17927       if( prev==iNext ){
17928         iNext = mem3.aPool[prev].u.list.next;
17929       }
17930       memsys3Unlink(prev);
17931       size = i + size/4 - prev;
17932       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
17933       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
17934       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
17935       memsys3Link(prev);
17936       i = prev;
17937     }else{
17938       size /= 4;
17939     }
17940     if( size>mem3.szMaster ){
17941       mem3.iMaster = i;
17942       mem3.szMaster = size;
17943     }
17944   }
17945 }
17946
17947 /*
17948 ** Return a block of memory of at least nBytes in size.
17949 ** Return NULL if unable.
17950 **
17951 ** This function assumes that the necessary mutexes, if any, are
17952 ** already held by the caller. Hence "Unsafe".
17953 */
17954 static void *memsys3MallocUnsafe(int nByte){
17955   u32 i;
17956   u32 nBlock;
17957   u32 toFree;
17958
17959   assert( sqlcipher3_mutex_held(mem3.mutex) );
17960   assert( sizeof(Mem3Block)==8 );
17961   if( nByte<=12 ){
17962     nBlock = 2;
17963   }else{
17964     nBlock = (nByte + 11)/8;
17965   }
17966   assert( nBlock>=2 );
17967
17968   /* STEP 1:
17969   ** Look for an entry of the correct size in either the small
17970   ** chunk table or in the large chunk hash table.  This is
17971   ** successful most of the time (about 9 times out of 10).
17972   */
17973   if( nBlock <= MX_SMALL ){
17974     i = mem3.aiSmall[nBlock-2];
17975     if( i>0 ){
17976       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
17977       return memsys3Checkout(i, nBlock);
17978     }
17979   }else{
17980     int hash = nBlock % N_HASH;
17981     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
17982       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
17983         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17984         return memsys3Checkout(i, nBlock);
17985       }
17986     }
17987   }
17988
17989   /* STEP 2:
17990   ** Try to satisfy the allocation by carving a piece off of the end
17991   ** of the master chunk.  This step usually works if step 1 fails.
17992   */
17993   if( mem3.szMaster>=nBlock ){
17994     return memsys3FromMaster(nBlock);
17995   }
17996
17997
17998   /* STEP 3:  
17999   ** Loop through the entire memory pool.  Coalesce adjacent free
18000   ** chunks.  Recompute the master chunk as the largest free chunk.
18001   ** Then try again to satisfy the allocation by carving a piece off
18002   ** of the end of the master chunk.  This step happens very
18003   ** rarely (we hope!)
18004   */
18005   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
18006     memsys3OutOfMemory(toFree);
18007     if( mem3.iMaster ){
18008       memsys3Link(mem3.iMaster);
18009       mem3.iMaster = 0;
18010       mem3.szMaster = 0;
18011     }
18012     for(i=0; i<N_HASH; i++){
18013       memsys3Merge(&mem3.aiHash[i]);
18014     }
18015     for(i=0; i<MX_SMALL-1; i++){
18016       memsys3Merge(&mem3.aiSmall[i]);
18017     }
18018     if( mem3.szMaster ){
18019       memsys3Unlink(mem3.iMaster);
18020       if( mem3.szMaster>=nBlock ){
18021         return memsys3FromMaster(nBlock);
18022       }
18023     }
18024   }
18025
18026   /* If none of the above worked, then we fail. */
18027   return 0;
18028 }
18029
18030 /*
18031 ** Free an outstanding memory allocation.
18032 **
18033 ** This function assumes that the necessary mutexes, if any, are
18034 ** already held by the caller. Hence "Unsafe".
18035 */
18036 static void memsys3FreeUnsafe(void *pOld){
18037   Mem3Block *p = (Mem3Block*)pOld;
18038   int i;
18039   u32 size, x;
18040   assert( sqlcipher3_mutex_held(mem3.mutex) );
18041   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
18042   i = p - mem3.aPool;
18043   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
18044   size = mem3.aPool[i-1].u.hdr.size4x/4;
18045   assert( i+size<=mem3.nPool+1 );
18046   mem3.aPool[i-1].u.hdr.size4x &= ~1;
18047   mem3.aPool[i+size-1].u.hdr.prevSize = size;
18048   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
18049   memsys3Link(i);
18050
18051   /* Try to expand the master using the newly freed chunk */
18052   if( mem3.iMaster ){
18053     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
18054       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
18055       mem3.iMaster -= size;
18056       mem3.szMaster += size;
18057       memsys3Unlink(mem3.iMaster);
18058       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
18059       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
18060       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
18061     }
18062     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
18063     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
18064       memsys3Unlink(mem3.iMaster+mem3.szMaster);
18065       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
18066       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
18067       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
18068     }
18069   }
18070 }
18071
18072 /*
18073 ** Return the size of an outstanding allocation, in bytes.  The
18074 ** size returned omits the 8-byte header overhead.  This only
18075 ** works for chunks that are currently checked out.
18076 */
18077 static int memsys3Size(void *p){
18078   Mem3Block *pBlock;
18079   if( p==0 ) return 0;
18080   pBlock = (Mem3Block*)p;
18081   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
18082   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
18083 }
18084
18085 /*
18086 ** Round up a request size to the next valid allocation size.
18087 */
18088 static int memsys3Roundup(int n){
18089   if( n<=12 ){
18090     return 12;
18091   }else{
18092     return ((n+11)&~7) - 4;
18093   }
18094 }
18095
18096 /*
18097 ** Allocate nBytes of memory.
18098 */
18099 static void *memsys3Malloc(int nBytes){
18100   sqlcipher3_int64 *p;
18101   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
18102   memsys3Enter();
18103   p = memsys3MallocUnsafe(nBytes);
18104   memsys3Leave();
18105   return (void*)p; 
18106 }
18107
18108 /*
18109 ** Free memory.
18110 */
18111 static void memsys3Free(void *pPrior){
18112   assert( pPrior );
18113   memsys3Enter();
18114   memsys3FreeUnsafe(pPrior);
18115   memsys3Leave();
18116 }
18117
18118 /*
18119 ** Change the size of an existing memory allocation
18120 */
18121 static void *memsys3Realloc(void *pPrior, int nBytes){
18122   int nOld;
18123   void *p;
18124   if( pPrior==0 ){
18125     return sqlcipher3_malloc(nBytes);
18126   }
18127   if( nBytes<=0 ){
18128     sqlcipher3_free(pPrior);
18129     return 0;
18130   }
18131   nOld = memsys3Size(pPrior);
18132   if( nBytes<=nOld && nBytes>=nOld-128 ){
18133     return pPrior;
18134   }
18135   memsys3Enter();
18136   p = memsys3MallocUnsafe(nBytes);
18137   if( p ){
18138     if( nOld<nBytes ){
18139       memcpy(p, pPrior, nOld);
18140     }else{
18141       memcpy(p, pPrior, nBytes);
18142     }
18143     memsys3FreeUnsafe(pPrior);
18144   }
18145   memsys3Leave();
18146   return p;
18147 }
18148
18149 /*
18150 ** Initialize this module.
18151 */
18152 static int memsys3Init(void *NotUsed){
18153   UNUSED_PARAMETER(NotUsed);
18154   if( !sqlcipher3GlobalConfig.pHeap ){
18155     return SQLCIPHER_ERROR;
18156   }
18157
18158   /* Store a pointer to the memory block in global structure mem3. */
18159   assert( sizeof(Mem3Block)==8 );
18160   mem3.aPool = (Mem3Block *)sqlcipher3GlobalConfig.pHeap;
18161   mem3.nPool = (sqlcipher3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
18162
18163   /* Initialize the master block. */
18164   mem3.szMaster = mem3.nPool;
18165   mem3.mnMaster = mem3.szMaster;
18166   mem3.iMaster = 1;
18167   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
18168   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
18169   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
18170
18171   return SQLCIPHER_OK;
18172 }
18173
18174 /*
18175 ** Deinitialize this module.
18176 */
18177 static void memsys3Shutdown(void *NotUsed){
18178   UNUSED_PARAMETER(NotUsed);
18179   mem3.mutex = 0;
18180   return;
18181 }
18182
18183
18184
18185 /*
18186 ** Open the file indicated and write a log of all unfreed memory 
18187 ** allocations into that log.
18188 */
18189 SQLCIPHER_PRIVATE void sqlcipher3Memsys3Dump(const char *zFilename){
18190 #ifdef SQLCIPHER_DEBUG
18191   FILE *out;
18192   u32 i, j;
18193   u32 size;
18194   if( zFilename==0 || zFilename[0]==0 ){
18195     out = stdout;
18196   }else{
18197     out = fopen(zFilename, "w");
18198     if( out==0 ){
18199       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18200                       zFilename);
18201       return;
18202     }
18203   }
18204   memsys3Enter();
18205   fprintf(out, "CHUNKS:\n");
18206   for(i=1; i<=mem3.nPool; i+=size/4){
18207     size = mem3.aPool[i-1].u.hdr.size4x;
18208     if( size/4<=1 ){
18209       fprintf(out, "%p size error\n", &mem3.aPool[i]);
18210       assert( 0 );
18211       break;
18212     }
18213     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
18214       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
18215       assert( 0 );
18216       break;
18217     }
18218     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
18219       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
18220       assert( 0 );
18221       break;
18222     }
18223     if( size&1 ){
18224       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
18225     }else{
18226       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
18227                   i==mem3.iMaster ? " **master**" : "");
18228     }
18229   }
18230   for(i=0; i<MX_SMALL-1; i++){
18231     if( mem3.aiSmall[i]==0 ) continue;
18232     fprintf(out, "small(%2d):", i);
18233     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
18234       fprintf(out, " %p(%d)", &mem3.aPool[j],
18235               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
18236     }
18237     fprintf(out, "\n"); 
18238   }
18239   for(i=0; i<N_HASH; i++){
18240     if( mem3.aiHash[i]==0 ) continue;
18241     fprintf(out, "hash(%2d):", i);
18242     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
18243       fprintf(out, " %p(%d)", &mem3.aPool[j],
18244               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
18245     }
18246     fprintf(out, "\n"); 
18247   }
18248   fprintf(out, "master=%d\n", mem3.iMaster);
18249   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
18250   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
18251   sqlcipher3_mutex_leave(mem3.mutex);
18252   if( out==stdout ){
18253     fflush(stdout);
18254   }else{
18255     fclose(out);
18256   }
18257 #else
18258   UNUSED_PARAMETER(zFilename);
18259 #endif
18260 }
18261
18262 /*
18263 ** This routine is the only routine in this file with external 
18264 ** linkage.
18265 **
18266 ** Populate the low-level memory allocation function pointers in
18267 ** sqlcipher3GlobalConfig.m with pointers to the routines in this file. The
18268 ** arguments specify the block of memory to manage.
18269 **
18270 ** This routine is only called by sqlcipher3_config(), and therefore
18271 ** is not required to be threadsafe (it is not).
18272 */
18273 SQLCIPHER_PRIVATE const sqlcipher3_mem_methods *sqlcipher3MemGetMemsys3(void){
18274   static const sqlcipher3_mem_methods mempoolMethods = {
18275      memsys3Malloc,
18276      memsys3Free,
18277      memsys3Realloc,
18278      memsys3Size,
18279      memsys3Roundup,
18280      memsys3Init,
18281      memsys3Shutdown,
18282      0
18283   };
18284   return &mempoolMethods;
18285 }
18286
18287 #endif /* SQLCIPHER_ENABLE_MEMSYS3 */
18288
18289 /************** End of mem3.c ************************************************/
18290 /************** Begin file mem5.c ********************************************/
18291 /*
18292 ** 2007 October 14
18293 **
18294 ** The author disclaims copyright to this source code.  In place of
18295 ** a legal notice, here is a blessing:
18296 **
18297 **    May you do good and not evil.
18298 **    May you find forgiveness for yourself and forgive others.
18299 **    May you share freely, never taking more than you give.
18300 **
18301 *************************************************************************
18302 ** This file contains the C functions that implement a memory
18303 ** allocation subsystem for use by SQLite. 
18304 **
18305 ** This version of the memory allocation subsystem omits all
18306 ** use of malloc(). The application gives SQLite a block of memory
18307 ** before calling sqlcipher3_initialize() from which allocations
18308 ** are made and returned by the xMalloc() and xRealloc() 
18309 ** implementations. Once sqlcipher3_initialize() has been called,
18310 ** the amount of memory available to SQLite is fixed and cannot
18311 ** be changed.
18312 **
18313 ** This version of the memory allocation subsystem is included
18314 ** in the build only if SQLCIPHER_ENABLE_MEMSYS5 is defined.
18315 **
18316 ** This memory allocator uses the following algorithm:
18317 **
18318 **   1.  All memory allocations sizes are rounded up to a power of 2.
18319 **
18320 **   2.  If two adjacent free blocks are the halves of a larger block,
18321 **       then the two blocks are coalesed into the single larger block.
18322 **
18323 **   3.  New memory is allocated from the first available free block.
18324 **
18325 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
18326 ** Concerning Dynamic Storage Allocation". Journal of the Association for
18327 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
18328 ** 
18329 ** Let n be the size of the largest allocation divided by the minimum
18330 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
18331 ** be the maximum amount of memory ever outstanding at one time.  Let
18332 ** N be the total amount of memory available for allocation.  Robson
18333 ** proved that this memory allocator will never breakdown due to 
18334 ** fragmentation as long as the following constraint holds:
18335 **
18336 **      N >=  M*(1 + log2(n)/2) - n + 1
18337 **
18338 ** The sqlcipher3_status() logic tracks the maximum values of n and M so
18339 ** that an application can, at any time, verify this constraint.
18340 */
18341
18342 /*
18343 ** This version of the memory allocator is used only when 
18344 ** SQLCIPHER_ENABLE_MEMSYS5 is defined.
18345 */
18346 #ifdef SQLCIPHER_ENABLE_MEMSYS5
18347
18348 /*
18349 ** A minimum allocation is an instance of the following structure.
18350 ** Larger allocations are an array of these structures where the
18351 ** size of the array is a power of 2.
18352 **
18353 ** The size of this object must be a power of two.  That fact is
18354 ** verified in memsys5Init().
18355 */
18356 typedef struct Mem5Link Mem5Link;
18357 struct Mem5Link {
18358   int next;       /* Index of next free chunk */
18359   int prev;       /* Index of previous free chunk */
18360 };
18361
18362 /*
18363 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
18364 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
18365 ** it is not actually possible to reach this limit.
18366 */
18367 #define LOGMAX 30
18368
18369 /*
18370 ** Masks used for mem5.aCtrl[] elements.
18371 */
18372 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
18373 #define CTRL_FREE     0x20    /* True if not checked out */
18374
18375 /*
18376 ** All of the static variables used by this module are collected
18377 ** into a single structure named "mem5".  This is to keep the
18378 ** static variables organized and to reduce namespace pollution
18379 ** when this module is combined with other in the amalgamation.
18380 */
18381 static SQLCIPHER_WSD struct Mem5Global {
18382   /*
18383   ** Memory available for allocation
18384   */
18385   int szAtom;      /* Smallest possible allocation in bytes */
18386   int nBlock;      /* Number of szAtom sized blocks in zPool */
18387   u8 *zPool;       /* Memory available to be allocated */
18388   
18389   /*
18390   ** Mutex to control access to the memory allocation subsystem.
18391   */
18392   sqlcipher3_mutex *mutex;
18393
18394   /*
18395   ** Performance statistics
18396   */
18397   u64 nAlloc;         /* Total number of calls to malloc */
18398   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
18399   u64 totalExcess;    /* Total internal fragmentation */
18400   u32 currentOut;     /* Current checkout, including internal fragmentation */
18401   u32 currentCount;   /* Current number of distinct checkouts */
18402   u32 maxOut;         /* Maximum instantaneous currentOut */
18403   u32 maxCount;       /* Maximum instantaneous currentCount */
18404   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
18405   
18406   /*
18407   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
18408   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
18409   ** and so forth.
18410   */
18411   int aiFreelist[LOGMAX+1];
18412
18413   /*
18414   ** Space for tracking which blocks are checked out and the size
18415   ** of each block.  One byte per block.
18416   */
18417   u8 *aCtrl;
18418
18419 } mem5;
18420
18421 /*
18422 ** Access the static variable through a macro for SQLCIPHER_OMIT_WSD
18423 */
18424 #define mem5 GLOBAL(struct Mem5Global, mem5)
18425
18426 /*
18427 ** Assuming mem5.zPool is divided up into an array of Mem5Link
18428 ** structures, return a pointer to the idx-th such lik.
18429 */
18430 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
18431
18432 /*
18433 ** Unlink the chunk at mem5.aPool[i] from list it is currently
18434 ** on.  It should be found on mem5.aiFreelist[iLogsize].
18435 */
18436 static void memsys5Unlink(int i, int iLogsize){
18437   int next, prev;
18438   assert( i>=0 && i<mem5.nBlock );
18439   assert( iLogsize>=0 && iLogsize<=LOGMAX );
18440   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18441
18442   next = MEM5LINK(i)->next;
18443   prev = MEM5LINK(i)->prev;
18444   if( prev<0 ){
18445     mem5.aiFreelist[iLogsize] = next;
18446   }else{
18447     MEM5LINK(prev)->next = next;
18448   }
18449   if( next>=0 ){
18450     MEM5LINK(next)->prev = prev;
18451   }
18452 }
18453
18454 /*
18455 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
18456 ** free list.
18457 */
18458 static void memsys5Link(int i, int iLogsize){
18459   int x;
18460   assert( sqlcipher3_mutex_held(mem5.mutex) );
18461   assert( i>=0 && i<mem5.nBlock );
18462   assert( iLogsize>=0 && iLogsize<=LOGMAX );
18463   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18464
18465   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
18466   MEM5LINK(i)->prev = -1;
18467   if( x>=0 ){
18468     assert( x<mem5.nBlock );
18469     MEM5LINK(x)->prev = i;
18470   }
18471   mem5.aiFreelist[iLogsize] = i;
18472 }
18473
18474 /*
18475 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
18476 ** will already be held (obtained by code in malloc.c) if
18477 ** sqlcipher3GlobalConfig.bMemStat is true.
18478 */
18479 static void memsys5Enter(void){
18480   sqlcipher3_mutex_enter(mem5.mutex);
18481 }
18482 static void memsys5Leave(void){
18483   sqlcipher3_mutex_leave(mem5.mutex);
18484 }
18485
18486 /*
18487 ** Return the size of an outstanding allocation, in bytes.  The
18488 ** size returned omits the 8-byte header overhead.  This only
18489 ** works for chunks that are currently checked out.
18490 */
18491 static int memsys5Size(void *p){
18492   int iSize = 0;
18493   if( p ){
18494     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
18495     assert( i>=0 && i<mem5.nBlock );
18496     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
18497   }
18498   return iSize;
18499 }
18500
18501 /*
18502 ** Find the first entry on the freelist iLogsize.  Unlink that
18503 ** entry and return its index. 
18504 */
18505 static int memsys5UnlinkFirst(int iLogsize){
18506   int i;
18507   int iFirst;
18508
18509   assert( iLogsize>=0 && iLogsize<=LOGMAX );
18510   i = iFirst = mem5.aiFreelist[iLogsize];
18511   assert( iFirst>=0 );
18512   while( i>0 ){
18513     if( i<iFirst ) iFirst = i;
18514     i = MEM5LINK(i)->next;
18515   }
18516   memsys5Unlink(iFirst, iLogsize);
18517   return iFirst;
18518 }
18519
18520 /*
18521 ** Return a block of memory of at least nBytes in size.
18522 ** Return NULL if unable.  Return NULL if nBytes==0.
18523 **
18524 ** The caller guarantees that nByte positive.
18525 **
18526 ** The caller has obtained a mutex prior to invoking this
18527 ** routine so there is never any chance that two or more
18528 ** threads can be in this routine at the same time.
18529 */
18530 static void *memsys5MallocUnsafe(int nByte){
18531   int i;           /* Index of a mem5.aPool[] slot */
18532   int iBin;        /* Index into mem5.aiFreelist[] */
18533   int iFullSz;     /* Size of allocation rounded up to power of 2 */
18534   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
18535
18536   /* nByte must be a positive */
18537   assert( nByte>0 );
18538
18539   /* Keep track of the maximum allocation request.  Even unfulfilled
18540   ** requests are counted */
18541   if( (u32)nByte>mem5.maxRequest ){
18542     mem5.maxRequest = nByte;
18543   }
18544
18545   /* Abort if the requested allocation size is larger than the largest
18546   ** power of two that we can represent using 32-bit signed integers.
18547   */
18548   if( nByte > 0x40000000 ){
18549     return 0;
18550   }
18551
18552   /* Round nByte up to the next valid power of two */
18553   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
18554
18555   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
18556   ** block.  If not, then split a block of the next larger power of
18557   ** two in order to create a new free block of size iLogsize.
18558   */
18559   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
18560   if( iBin>LOGMAX ){
18561     testcase( sqlcipher3GlobalConfig.xLog!=0 );
18562     sqlcipher3_log(SQLCIPHER_NOMEM, "failed to allocate %u bytes", nByte);
18563     return 0;
18564   }
18565   i = memsys5UnlinkFirst(iBin);
18566   while( iBin>iLogsize ){
18567     int newSize;
18568
18569     iBin--;
18570     newSize = 1 << iBin;
18571     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
18572     memsys5Link(i+newSize, iBin);
18573   }
18574   mem5.aCtrl[i] = iLogsize;
18575
18576   /* Update allocator performance statistics. */
18577   mem5.nAlloc++;
18578   mem5.totalAlloc += iFullSz;
18579   mem5.totalExcess += iFullSz - nByte;
18580   mem5.currentCount++;
18581   mem5.currentOut += iFullSz;
18582   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
18583   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
18584
18585   /* Return a pointer to the allocated memory. */
18586   return (void*)&mem5.zPool[i*mem5.szAtom];
18587 }
18588
18589 /*
18590 ** Free an outstanding memory allocation.
18591 */
18592 static void memsys5FreeUnsafe(void *pOld){
18593   u32 size, iLogsize;
18594   int iBlock;
18595
18596   /* Set iBlock to the index of the block pointed to by pOld in 
18597   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
18598   */
18599   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
18600
18601   /* Check that the pointer pOld points to a valid, non-free block. */
18602   assert( iBlock>=0 && iBlock<mem5.nBlock );
18603   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
18604   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
18605
18606   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
18607   size = 1<<iLogsize;
18608   assert( iBlock+size-1<(u32)mem5.nBlock );
18609
18610   mem5.aCtrl[iBlock] |= CTRL_FREE;
18611   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
18612   assert( mem5.currentCount>0 );
18613   assert( mem5.currentOut>=(size*mem5.szAtom) );
18614   mem5.currentCount--;
18615   mem5.currentOut -= size*mem5.szAtom;
18616   assert( mem5.currentOut>0 || mem5.currentCount==0 );
18617   assert( mem5.currentCount>0 || mem5.currentOut==0 );
18618
18619   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18620   while( ALWAYS(iLogsize<LOGMAX) ){
18621     int iBuddy;
18622     if( (iBlock>>iLogsize) & 1 ){
18623       iBuddy = iBlock - size;
18624     }else{
18625       iBuddy = iBlock + size;
18626     }
18627     assert( iBuddy>=0 );
18628     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
18629     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
18630     memsys5Unlink(iBuddy, iLogsize);
18631     iLogsize++;
18632     if( iBuddy<iBlock ){
18633       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
18634       mem5.aCtrl[iBlock] = 0;
18635       iBlock = iBuddy;
18636     }else{
18637       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18638       mem5.aCtrl[iBuddy] = 0;
18639     }
18640     size *= 2;
18641   }
18642   memsys5Link(iBlock, iLogsize);
18643 }
18644
18645 /*
18646 ** Allocate nBytes of memory
18647 */
18648 static void *memsys5Malloc(int nBytes){
18649   sqlcipher3_int64 *p = 0;
18650   if( nBytes>0 ){
18651     memsys5Enter();
18652     p = memsys5MallocUnsafe(nBytes);
18653     memsys5Leave();
18654   }
18655   return (void*)p; 
18656 }
18657
18658 /*
18659 ** Free memory.
18660 **
18661 ** The outer layer memory allocator prevents this routine from
18662 ** being called with pPrior==0.
18663 */
18664 static void memsys5Free(void *pPrior){
18665   assert( pPrior!=0 );
18666   memsys5Enter();
18667   memsys5FreeUnsafe(pPrior);
18668   memsys5Leave();  
18669 }
18670
18671 /*
18672 ** Change the size of an existing memory allocation.
18673 **
18674 ** The outer layer memory allocator prevents this routine from
18675 ** being called with pPrior==0.  
18676 **
18677 ** nBytes is always a value obtained from a prior call to
18678 ** memsys5Round().  Hence nBytes is always a non-negative power
18679 ** of two.  If nBytes==0 that means that an oversize allocation
18680 ** (an allocation larger than 0x40000000) was requested and this
18681 ** routine should return 0 without freeing pPrior.
18682 */
18683 static void *memsys5Realloc(void *pPrior, int nBytes){
18684   int nOld;
18685   void *p;
18686   assert( pPrior!=0 );
18687   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
18688   assert( nBytes>=0 );
18689   if( nBytes==0 ){
18690     return 0;
18691   }
18692   nOld = memsys5Size(pPrior);
18693   if( nBytes<=nOld ){
18694     return pPrior;
18695   }
18696   memsys5Enter();
18697   p = memsys5MallocUnsafe(nBytes);
18698   if( p ){
18699     memcpy(p, pPrior, nOld);
18700     memsys5FreeUnsafe(pPrior);
18701   }
18702   memsys5Leave();
18703   return p;
18704 }
18705
18706 /*
18707 ** Round up a request size to the next valid allocation size.  If
18708 ** the allocation is too large to be handled by this allocation system,
18709 ** return 0.
18710 **
18711 ** All allocations must be a power of two and must be expressed by a
18712 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
18713 ** or 1073741824 bytes.
18714 */
18715 static int memsys5Roundup(int n){
18716   int iFullSz;
18717   if( n > 0x40000000 ) return 0;
18718   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
18719   return iFullSz;
18720 }
18721
18722 /*
18723 ** Return the ceiling of the logarithm base 2 of iValue.
18724 **
18725 ** Examples:   memsys5Log(1) -> 0
18726 **             memsys5Log(2) -> 1
18727 **             memsys5Log(4) -> 2
18728 **             memsys5Log(5) -> 3
18729 **             memsys5Log(8) -> 3
18730 **             memsys5Log(9) -> 4
18731 */
18732 static int memsys5Log(int iValue){
18733   int iLog;
18734   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
18735   return iLog;
18736 }
18737
18738 /*
18739 ** Initialize the memory allocator.
18740 **
18741 ** This routine is not threadsafe.  The caller must be holding a mutex
18742 ** to prevent multiple threads from entering at the same time.
18743 */
18744 static int memsys5Init(void *NotUsed){
18745   int ii;            /* Loop counter */
18746   int nByte;         /* Number of bytes of memory available to this allocator */
18747   u8 *zByte;         /* Memory usable by this allocator */
18748   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
18749   int iOffset;       /* An offset into mem5.aCtrl[] */
18750
18751   UNUSED_PARAMETER(NotUsed);
18752
18753   /* For the purposes of this routine, disable the mutex */
18754   mem5.mutex = 0;
18755
18756   /* The size of a Mem5Link object must be a power of two.  Verify that
18757   ** this is case.
18758   */
18759   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
18760
18761   nByte = sqlcipher3GlobalConfig.nHeap;
18762   zByte = (u8*)sqlcipher3GlobalConfig.pHeap;
18763   assert( zByte!=0 );  /* sqlcipher3_config() does not allow otherwise */
18764
18765   /* boundaries on sqlcipher3GlobalConfig.mnReq are enforced in sqlcipher3_config() */
18766   nMinLog = memsys5Log(sqlcipher3GlobalConfig.mnReq);
18767   mem5.szAtom = (1<<nMinLog);
18768   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
18769     mem5.szAtom = mem5.szAtom << 1;
18770   }
18771
18772   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
18773   mem5.zPool = zByte;
18774   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
18775
18776   for(ii=0; ii<=LOGMAX; ii++){
18777     mem5.aiFreelist[ii] = -1;
18778   }
18779
18780   iOffset = 0;
18781   for(ii=LOGMAX; ii>=0; ii--){
18782     int nAlloc = (1<<ii);
18783     if( (iOffset+nAlloc)<=mem5.nBlock ){
18784       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
18785       memsys5Link(iOffset, ii);
18786       iOffset += nAlloc;
18787     }
18788     assert((iOffset+nAlloc)>mem5.nBlock);
18789   }
18790
18791   /* If a mutex is required for normal operation, allocate one */
18792   if( sqlcipher3GlobalConfig.bMemstat==0 ){
18793     mem5.mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MEM);
18794   }
18795
18796   return SQLCIPHER_OK;
18797 }
18798
18799 /*
18800 ** Deinitialize this module.
18801 */
18802 static void memsys5Shutdown(void *NotUsed){
18803   UNUSED_PARAMETER(NotUsed);
18804   mem5.mutex = 0;
18805   return;
18806 }
18807
18808 #ifdef SQLCIPHER_TEST
18809 /*
18810 ** Open the file indicated and write a log of all unfreed memory 
18811 ** allocations into that log.
18812 */
18813 SQLCIPHER_PRIVATE void sqlcipher3Memsys5Dump(const char *zFilename){
18814   FILE *out;
18815   int i, j, n;
18816   int nMinLog;
18817
18818   if( zFilename==0 || zFilename[0]==0 ){
18819     out = stdout;
18820   }else{
18821     out = fopen(zFilename, "w");
18822     if( out==0 ){
18823       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18824                       zFilename);
18825       return;
18826     }
18827   }
18828   memsys5Enter();
18829   nMinLog = memsys5Log(mem5.szAtom);
18830   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
18831     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
18832     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
18833   }
18834   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
18835   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
18836   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
18837   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
18838   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
18839   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
18840   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
18841   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
18842   memsys5Leave();
18843   if( out==stdout ){
18844     fflush(stdout);
18845   }else{
18846     fclose(out);
18847   }
18848 }
18849 #endif
18850
18851 /*
18852 ** This routine is the only routine in this file with external 
18853 ** linkage. It returns a pointer to a static sqlcipher3_mem_methods
18854 ** struct populated with the memsys5 methods.
18855 */
18856 SQLCIPHER_PRIVATE const sqlcipher3_mem_methods *sqlcipher3MemGetMemsys5(void){
18857   static const sqlcipher3_mem_methods memsys5Methods = {
18858      memsys5Malloc,
18859      memsys5Free,
18860      memsys5Realloc,
18861      memsys5Size,
18862      memsys5Roundup,
18863      memsys5Init,
18864      memsys5Shutdown,
18865      0
18866   };
18867   return &memsys5Methods;
18868 }
18869
18870 #endif /* SQLCIPHER_ENABLE_MEMSYS5 */
18871
18872 /************** End of mem5.c ************************************************/
18873 /************** Begin file mutex.c *******************************************/
18874 /*
18875 ** 2007 August 14
18876 **
18877 ** The author disclaims copyright to this source code.  In place of
18878 ** a legal notice, here is a blessing:
18879 **
18880 **    May you do good and not evil.
18881 **    May you find forgiveness for yourself and forgive others.
18882 **    May you share freely, never taking more than you give.
18883 **
18884 *************************************************************************
18885 ** This file contains the C functions that implement mutexes.
18886 **
18887 ** This file contains code that is common across all mutex implementations.
18888 */
18889
18890 #if defined(SQLCIPHER_DEBUG) && !defined(SQLCIPHER_MUTEX_OMIT)
18891 /*
18892 ** For debugging purposes, record when the mutex subsystem is initialized
18893 ** and uninitialized so that we can assert() if there is an attempt to
18894 ** allocate a mutex while the system is uninitialized.
18895 */
18896 static SQLCIPHER_WSD int mutexIsInit = 0;
18897 #endif /* SQLCIPHER_DEBUG */
18898
18899
18900 #ifndef SQLCIPHER_MUTEX_OMIT
18901 /*
18902 ** Initialize the mutex system.
18903 */
18904 SQLCIPHER_PRIVATE int sqlcipher3MutexInit(void){ 
18905   int rc = SQLCIPHER_OK;
18906   if( !sqlcipher3GlobalConfig.mutex.xMutexAlloc ){
18907     /* If the xMutexAlloc method has not been set, then the user did not
18908     ** install a mutex implementation via sqlcipher3_config() prior to 
18909     ** sqlcipher3_initialize() being called. This block copies pointers to
18910     ** the default implementation into the sqlcipher3GlobalConfig structure.
18911     */
18912     sqlcipher3_mutex_methods const *pFrom;
18913     sqlcipher3_mutex_methods *pTo = &sqlcipher3GlobalConfig.mutex;
18914
18915     if( sqlcipher3GlobalConfig.bCoreMutex ){
18916       pFrom = sqlcipher3DefaultMutex();
18917     }else{
18918       pFrom = sqlcipher3NoopMutex();
18919     }
18920     memcpy(pTo, pFrom, offsetof(sqlcipher3_mutex_methods, xMutexAlloc));
18921     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
18922            sizeof(*pTo) - offsetof(sqlcipher3_mutex_methods, xMutexFree));
18923     pTo->xMutexAlloc = pFrom->xMutexAlloc;
18924   }
18925   rc = sqlcipher3GlobalConfig.mutex.xMutexInit();
18926
18927 #ifdef SQLCIPHER_DEBUG
18928   GLOBAL(int, mutexIsInit) = 1;
18929 #endif
18930
18931   return rc;
18932 }
18933
18934 /*
18935 ** Shutdown the mutex system. This call frees resources allocated by
18936 ** sqlcipher3MutexInit().
18937 */
18938 SQLCIPHER_PRIVATE int sqlcipher3MutexEnd(void){
18939   int rc = SQLCIPHER_OK;
18940   if( sqlcipher3GlobalConfig.mutex.xMutexEnd ){
18941     rc = sqlcipher3GlobalConfig.mutex.xMutexEnd();
18942   }
18943
18944 #ifdef SQLCIPHER_DEBUG
18945   GLOBAL(int, mutexIsInit) = 0;
18946 #endif
18947
18948   return rc;
18949 }
18950
18951 /*
18952 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
18953 */
18954 SQLCIPHER_API sqlcipher3_mutex *sqlcipher3_mutex_alloc(int id){
18955 #ifndef SQLCIPHER_OMIT_AUTOINIT
18956   if( sqlcipher3_initialize() ) return 0;
18957 #endif
18958   return sqlcipher3GlobalConfig.mutex.xMutexAlloc(id);
18959 }
18960
18961 SQLCIPHER_PRIVATE sqlcipher3_mutex *sqlcipher3MutexAlloc(int id){
18962   if( !sqlcipher3GlobalConfig.bCoreMutex ){
18963     return 0;
18964   }
18965   assert( GLOBAL(int, mutexIsInit) );
18966   return sqlcipher3GlobalConfig.mutex.xMutexAlloc(id);
18967 }
18968
18969 /*
18970 ** Free a dynamic mutex.
18971 */
18972 SQLCIPHER_API void sqlcipher3_mutex_free(sqlcipher3_mutex *p){
18973   if( p ){
18974     sqlcipher3GlobalConfig.mutex.xMutexFree(p);
18975   }
18976 }
18977
18978 /*
18979 ** Obtain the mutex p. If some other thread already has the mutex, block
18980 ** until it can be obtained.
18981 */
18982 SQLCIPHER_API void sqlcipher3_mutex_enter(sqlcipher3_mutex *p){
18983   if( p ){
18984     sqlcipher3GlobalConfig.mutex.xMutexEnter(p);
18985   }
18986 }
18987
18988 /*
18989 ** Obtain the mutex p. If successful, return SQLCIPHER_OK. Otherwise, if another
18990 ** thread holds the mutex and it cannot be obtained, return SQLCIPHER_BUSY.
18991 */
18992 SQLCIPHER_API int sqlcipher3_mutex_try(sqlcipher3_mutex *p){
18993   int rc = SQLCIPHER_OK;
18994   if( p ){
18995     return sqlcipher3GlobalConfig.mutex.xMutexTry(p);
18996   }
18997   return rc;
18998 }
18999
19000 /*
19001 ** The sqlcipher3_mutex_leave() routine exits a mutex that was previously
19002 ** entered by the same thread.  The behavior is undefined if the mutex 
19003 ** is not currently entered. If a NULL pointer is passed as an argument
19004 ** this function is a no-op.
19005 */
19006 SQLCIPHER_API void sqlcipher3_mutex_leave(sqlcipher3_mutex *p){
19007   if( p ){
19008     sqlcipher3GlobalConfig.mutex.xMutexLeave(p);
19009   }
19010 }
19011
19012 #ifndef NDEBUG
19013 /*
19014 ** The sqlcipher3_mutex_held() and sqlcipher3_mutex_notheld() routine are
19015 ** intended for use inside assert() statements.
19016 */
19017 SQLCIPHER_API int sqlcipher3_mutex_held(sqlcipher3_mutex *p){
19018   return p==0 || sqlcipher3GlobalConfig.mutex.xMutexHeld(p);
19019 }
19020 SQLCIPHER_API int sqlcipher3_mutex_notheld(sqlcipher3_mutex *p){
19021   return p==0 || sqlcipher3GlobalConfig.mutex.xMutexNotheld(p);
19022 }
19023 #endif
19024
19025 #endif /* SQLCIPHER_MUTEX_OMIT */
19026
19027 /************** End of mutex.c ***********************************************/
19028 /************** Begin file mutex_noop.c **************************************/
19029 /*
19030 ** 2008 October 07
19031 **
19032 ** The author disclaims copyright to this source code.  In place of
19033 ** a legal notice, here is a blessing:
19034 **
19035 **    May you do good and not evil.
19036 **    May you find forgiveness for yourself and forgive others.
19037 **    May you share freely, never taking more than you give.
19038 **
19039 *************************************************************************
19040 ** This file contains the C functions that implement mutexes.
19041 **
19042 ** This implementation in this file does not provide any mutual
19043 ** exclusion and is thus suitable for use only in applications
19044 ** that use SQLite in a single thread.  The routines defined
19045 ** here are place-holders.  Applications can substitute working
19046 ** mutex routines at start-time using the
19047 **
19048 **     sqlcipher3_config(SQLCIPHER_CONFIG_MUTEX,...)
19049 **
19050 ** interface.
19051 **
19052 ** If compiled with SQLCIPHER_DEBUG, then additional logic is inserted
19053 ** that does error checking on mutexes to make sure they are being
19054 ** called correctly.
19055 */
19056
19057 #ifndef SQLCIPHER_MUTEX_OMIT
19058
19059 #ifndef SQLCIPHER_DEBUG
19060 /*
19061 ** Stub routines for all mutex methods.
19062 **
19063 ** This routines provide no mutual exclusion or error checking.
19064 */
19065 static int noopMutexInit(void){ return SQLCIPHER_OK; }
19066 static int noopMutexEnd(void){ return SQLCIPHER_OK; }
19067 static sqlcipher3_mutex *noopMutexAlloc(int id){ 
19068   UNUSED_PARAMETER(id);
19069   return (sqlcipher3_mutex*)8; 
19070 }
19071 static void noopMutexFree(sqlcipher3_mutex *p){ UNUSED_PARAMETER(p); return; }
19072 static void noopMutexEnter(sqlcipher3_mutex *p){ UNUSED_PARAMETER(p); return; }
19073 static int noopMutexTry(sqlcipher3_mutex *p){
19074   UNUSED_PARAMETER(p);
19075   return SQLCIPHER_OK;
19076 }
19077 static void noopMutexLeave(sqlcipher3_mutex *p){ UNUSED_PARAMETER(p); return; }
19078
19079 SQLCIPHER_PRIVATE sqlcipher3_mutex_methods const *sqlcipher3NoopMutex(void){
19080   static const sqlcipher3_mutex_methods sMutex = {
19081     noopMutexInit,
19082     noopMutexEnd,
19083     noopMutexAlloc,
19084     noopMutexFree,
19085     noopMutexEnter,
19086     noopMutexTry,
19087     noopMutexLeave,
19088
19089     0,
19090     0,
19091   };
19092
19093   return &sMutex;
19094 }
19095 #endif /* !SQLCIPHER_DEBUG */
19096
19097 #ifdef SQLCIPHER_DEBUG
19098 /*
19099 ** In this implementation, error checking is provided for testing
19100 ** and debugging purposes.  The mutexes still do not provide any
19101 ** mutual exclusion.
19102 */
19103
19104 /*
19105 ** The mutex object
19106 */
19107 typedef struct sqlcipher3_debug_mutex {
19108   int id;     /* The mutex type */
19109   int cnt;    /* Number of entries without a matching leave */
19110 } sqlcipher3_debug_mutex;
19111
19112 /*
19113 ** The sqlcipher3_mutex_held() and sqlcipher3_mutex_notheld() routine are
19114 ** intended for use inside assert() statements.
19115 */
19116 static int debugMutexHeld(sqlcipher3_mutex *pX){
19117   sqlcipher3_debug_mutex *p = (sqlcipher3_debug_mutex*)pX;
19118   return p==0 || p->cnt>0;
19119 }
19120 static int debugMutexNotheld(sqlcipher3_mutex *pX){
19121   sqlcipher3_debug_mutex *p = (sqlcipher3_debug_mutex*)pX;
19122   return p==0 || p->cnt==0;
19123 }
19124
19125 /*
19126 ** Initialize and deinitialize the mutex subsystem.
19127 */
19128 static int debugMutexInit(void){ return SQLCIPHER_OK; }
19129 static int debugMutexEnd(void){ return SQLCIPHER_OK; }
19130
19131 /*
19132 ** The sqlcipher3_mutex_alloc() routine allocates a new
19133 ** mutex and returns a pointer to it.  If it returns NULL
19134 ** that means that a mutex could not be allocated. 
19135 */
19136 static sqlcipher3_mutex *debugMutexAlloc(int id){
19137   static sqlcipher3_debug_mutex aStatic[6];
19138   sqlcipher3_debug_mutex *pNew = 0;
19139   switch( id ){
19140     case SQLCIPHER_MUTEX_FAST:
19141     case SQLCIPHER_MUTEX_RECURSIVE: {
19142       pNew = sqlcipher3Malloc(sizeof(*pNew));
19143       if( pNew ){
19144         pNew->id = id;
19145         pNew->cnt = 0;
19146       }
19147       break;
19148     }
19149     default: {
19150       assert( id-2 >= 0 );
19151       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
19152       pNew = &aStatic[id-2];
19153       pNew->id = id;
19154       break;
19155     }
19156   }
19157   return (sqlcipher3_mutex*)pNew;
19158 }
19159
19160 /*
19161 ** This routine deallocates a previously allocated mutex.
19162 */
19163 static void debugMutexFree(sqlcipher3_mutex *pX){
19164   sqlcipher3_debug_mutex *p = (sqlcipher3_debug_mutex*)pX;
19165   assert( p->cnt==0 );
19166   assert( p->id==SQLCIPHER_MUTEX_FAST || p->id==SQLCIPHER_MUTEX_RECURSIVE );
19167   sqlcipher3_free(p);
19168 }
19169
19170 /*
19171 ** The sqlcipher3_mutex_enter() and sqlcipher3_mutex_try() routines attempt
19172 ** to enter a mutex.  If another thread is already within the mutex,
19173 ** sqlcipher3_mutex_enter() will block and sqlcipher3_mutex_try() will return
19174 ** SQLCIPHER_BUSY.  The sqlcipher3_mutex_try() interface returns SQLCIPHER_OK
19175 ** upon successful entry.  Mutexes created using SQLCIPHER_MUTEX_RECURSIVE can
19176 ** be entered multiple times by the same thread.  In such cases the,
19177 ** mutex must be exited an equal number of times before another thread
19178 ** can enter.  If the same thread tries to enter any other kind of mutex
19179 ** more than once, the behavior is undefined.
19180 */
19181 static void debugMutexEnter(sqlcipher3_mutex *pX){
19182   sqlcipher3_debug_mutex *p = (sqlcipher3_debug_mutex*)pX;
19183   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
19184   p->cnt++;
19185 }
19186 static int debugMutexTry(sqlcipher3_mutex *pX){
19187   sqlcipher3_debug_mutex *p = (sqlcipher3_debug_mutex*)pX;
19188   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
19189   p->cnt++;
19190   return SQLCIPHER_OK;
19191 }
19192
19193 /*
19194 ** The sqlcipher3_mutex_leave() routine exits a mutex that was
19195 ** previously entered by the same thread.  The behavior
19196 ** is undefined if the mutex is not currently entered or
19197 ** is not currently allocated.  SQLite will never do either.
19198 */
19199 static void debugMutexLeave(sqlcipher3_mutex *pX){
19200   sqlcipher3_debug_mutex *p = (sqlcipher3_debug_mutex*)pX;
19201   assert( debugMutexHeld(pX) );
19202   p->cnt--;
19203   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
19204 }
19205
19206 SQLCIPHER_PRIVATE sqlcipher3_mutex_methods const *sqlcipher3NoopMutex(void){
19207   static const sqlcipher3_mutex_methods sMutex = {
19208     debugMutexInit,
19209     debugMutexEnd,
19210     debugMutexAlloc,
19211     debugMutexFree,
19212     debugMutexEnter,
19213     debugMutexTry,
19214     debugMutexLeave,
19215
19216     debugMutexHeld,
19217     debugMutexNotheld
19218   };
19219
19220   return &sMutex;
19221 }
19222 #endif /* SQLCIPHER_DEBUG */
19223
19224 /*
19225 ** If compiled with SQLCIPHER_MUTEX_NOOP, then the no-op mutex implementation
19226 ** is used regardless of the run-time threadsafety setting.
19227 */
19228 #ifdef SQLCIPHER_MUTEX_NOOP
19229 SQLCIPHER_PRIVATE sqlcipher3_mutex_methods const *sqlcipher3DefaultMutex(void){
19230   return sqlcipher3NoopMutex();
19231 }
19232 #endif /* SQLCIPHER_MUTEX_NOOP */
19233 #endif /* SQLCIPHER_MUTEX_OMIT */
19234
19235 /************** End of mutex_noop.c ******************************************/
19236 /************** Begin file mutex_os2.c ***************************************/
19237 /*
19238 ** 2007 August 28
19239 **
19240 ** The author disclaims copyright to this source code.  In place of
19241 ** a legal notice, here is a blessing:
19242 **
19243 **    May you do good and not evil.
19244 **    May you find forgiveness for yourself and forgive others.
19245 **    May you share freely, never taking more than you give.
19246 **
19247 *************************************************************************
19248 ** This file contains the C functions that implement mutexes for OS/2
19249 */
19250
19251 /*
19252 ** The code in this file is only used if SQLCIPHER_MUTEX_OS2 is defined.
19253 ** See the mutex.h file for details.
19254 */
19255 #ifdef SQLCIPHER_MUTEX_OS2
19256
19257 /********************** OS/2 Mutex Implementation **********************
19258 **
19259 ** This implementation of mutexes is built using the OS/2 API.
19260 */
19261
19262 /*
19263 ** The mutex object
19264 ** Each recursive mutex is an instance of the following structure.
19265 */
19266 struct sqlcipher3_mutex {
19267   HMTX mutex;       /* Mutex controlling the lock */
19268   int  id;          /* Mutex type */
19269 #ifdef SQLCIPHER_DEBUG
19270  int   trace;       /* True to trace changes */
19271 #endif
19272 };
19273
19274 #ifdef SQLCIPHER_DEBUG
19275 #define SQLCIPHER3_MUTEX_INITIALIZER { 0, 0, 0 }
19276 #else
19277 #define SQLCIPHER3_MUTEX_INITIALIZER { 0, 0 }
19278 #endif
19279
19280 /*
19281 ** Initialize and deinitialize the mutex subsystem.
19282 */
19283 static int os2MutexInit(void){ return SQLCIPHER_OK; }
19284 static int os2MutexEnd(void){ return SQLCIPHER_OK; }
19285
19286 /*
19287 ** The sqlcipher3_mutex_alloc() routine allocates a new
19288 ** mutex and returns a pointer to it.  If it returns NULL
19289 ** that means that a mutex could not be allocated. 
19290 ** SQLite will unwind its stack and return an error.  The argument
19291 ** to sqlcipher3_mutex_alloc() is one of these integer constants:
19292 **
19293 ** <ul>
19294 ** <li>  SQLCIPHER_MUTEX_FAST
19295 ** <li>  SQLCIPHER_MUTEX_RECURSIVE
19296 ** <li>  SQLCIPHER_MUTEX_STATIC_MASTER
19297 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM
19298 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM2
19299 ** <li>  SQLCIPHER_MUTEX_STATIC_PRNG
19300 ** <li>  SQLCIPHER_MUTEX_STATIC_LRU
19301 ** <li>  SQLCIPHER_MUTEX_STATIC_LRU2
19302 ** </ul>
19303 **
19304 ** The first two constants cause sqlcipher3_mutex_alloc() to create
19305 ** a new mutex.  The new mutex is recursive when SQLCIPHER_MUTEX_RECURSIVE
19306 ** is used but not necessarily so when SQLCIPHER_MUTEX_FAST is used.
19307 ** The mutex implementation does not need to make a distinction
19308 ** between SQLCIPHER_MUTEX_RECURSIVE and SQLCIPHER_MUTEX_FAST if it does
19309 ** not want to.  But SQLite will only request a recursive mutex in
19310 ** cases where it really needs one.  If a faster non-recursive mutex
19311 ** implementation is available on the host platform, the mutex subsystem
19312 ** might return such a mutex in response to SQLCIPHER_MUTEX_FAST.
19313 **
19314 ** The other allowed parameters to sqlcipher3_mutex_alloc() each return
19315 ** a pointer to a static preexisting mutex.  Six static mutexes are
19316 ** used by the current version of SQLite.  Future versions of SQLite
19317 ** may add additional static mutexes.  Static mutexes are for internal
19318 ** use by SQLite only.  Applications that use SQLite mutexes should
19319 ** use only the dynamic mutexes returned by SQLCIPHER_MUTEX_FAST or
19320 ** SQLCIPHER_MUTEX_RECURSIVE.
19321 **
19322 ** Note that if one of the dynamic mutex parameters (SQLCIPHER_MUTEX_FAST
19323 ** or SQLCIPHER_MUTEX_RECURSIVE) is used then sqlcipher3_mutex_alloc()
19324 ** returns a different mutex on every call.  But for the static
19325 ** mutex types, the same mutex is returned on every call that has
19326 ** the same type number.
19327 */
19328 static sqlcipher3_mutex *os2MutexAlloc(int iType){
19329   sqlcipher3_mutex *p = NULL;
19330   switch( iType ){
19331     case SQLCIPHER_MUTEX_FAST:
19332     case SQLCIPHER_MUTEX_RECURSIVE: {
19333       p = sqlcipher3MallocZero( sizeof(*p) );
19334       if( p ){
19335         p->id = iType;
19336         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
19337           sqlcipher3_free( p );
19338           p = NULL;
19339         }
19340       }
19341       break;
19342     }
19343     default: {
19344       static volatile int isInit = 0;
19345       static sqlcipher3_mutex staticMutexes[6] = {
19346         SQLCIPHER3_MUTEX_INITIALIZER,
19347         SQLCIPHER3_MUTEX_INITIALIZER,
19348         SQLCIPHER3_MUTEX_INITIALIZER,
19349         SQLCIPHER3_MUTEX_INITIALIZER,
19350         SQLCIPHER3_MUTEX_INITIALIZER,
19351         SQLCIPHER3_MUTEX_INITIALIZER,
19352       };
19353       if ( !isInit ){
19354         APIRET rc;
19355         PTIB ptib;
19356         PPIB ppib;
19357         HMTX mutex;
19358         char name[32];
19359         DosGetInfoBlocks( &ptib, &ppib );
19360         sqlcipher3_snprintf( sizeof(name), name, "\\SEM32\\SQLCIPHER%04x",
19361                           ppib->pib_ulpid );
19362         while( !isInit ){
19363           mutex = 0;
19364           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
19365           if( rc == NO_ERROR ){
19366             unsigned int i;
19367             if( !isInit ){
19368               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
19369                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
19370               }
19371               isInit = 1;
19372             }
19373             DosCloseMutexSem( mutex );
19374           }else if( rc == ERROR_DUPLICATE_NAME ){
19375             DosSleep( 1 );
19376           }else{
19377             return p;
19378           }
19379         }
19380       }
19381       assert( iType-2 >= 0 );
19382       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
19383       p = &staticMutexes[iType-2];
19384       p->id = iType;
19385       break;
19386     }
19387   }
19388   return p;
19389 }
19390
19391
19392 /*
19393 ** This routine deallocates a previously allocated mutex.
19394 ** SQLite is careful to deallocate every mutex that it allocates.
19395 */
19396 static void os2MutexFree(sqlcipher3_mutex *p){
19397 #ifdef SQLCIPHER_DEBUG
19398   TID tid;
19399   PID pid;
19400   ULONG ulCount;
19401   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
19402   assert( ulCount==0 );
19403   assert( p->id==SQLCIPHER_MUTEX_FAST || p->id==SQLCIPHER_MUTEX_RECURSIVE );
19404 #endif
19405   DosCloseMutexSem( p->mutex );
19406   sqlcipher3_free( p );
19407 }
19408
19409 #ifdef SQLCIPHER_DEBUG
19410 /*
19411 ** The sqlcipher3_mutex_held() and sqlcipher3_mutex_notheld() routine are
19412 ** intended for use inside assert() statements.
19413 */
19414 static int os2MutexHeld(sqlcipher3_mutex *p){
19415   TID tid;
19416   PID pid;
19417   ULONG ulCount;
19418   PTIB ptib;
19419   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
19420   if( ulCount==0 || ( ulCount>1 && p->id!=SQLCIPHER_MUTEX_RECURSIVE ) )
19421     return 0;
19422   DosGetInfoBlocks(&ptib, NULL);
19423   return tid==ptib->tib_ptib2->tib2_ultid;
19424 }
19425 static int os2MutexNotheld(sqlcipher3_mutex *p){
19426   TID tid;
19427   PID pid;
19428   ULONG ulCount;
19429   PTIB ptib;
19430   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
19431   if( ulCount==0 )
19432     return 1;
19433   DosGetInfoBlocks(&ptib, NULL);
19434   return tid!=ptib->tib_ptib2->tib2_ultid;
19435 }
19436 static void os2MutexTrace(sqlcipher3_mutex *p, char *pAction){
19437   TID   tid;
19438   PID   pid;
19439   ULONG ulCount;
19440   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
19441   printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
19442 }
19443 #endif
19444
19445 /*
19446 ** The sqlcipher3_mutex_enter() and sqlcipher3_mutex_try() routines attempt
19447 ** to enter a mutex.  If another thread is already within the mutex,
19448 ** sqlcipher3_mutex_enter() will block and sqlcipher3_mutex_try() will return
19449 ** SQLCIPHER_BUSY.  The sqlcipher3_mutex_try() interface returns SQLCIPHER_OK
19450 ** upon successful entry.  Mutexes created using SQLCIPHER_MUTEX_RECURSIVE can
19451 ** be entered multiple times by the same thread.  In such cases the,
19452 ** mutex must be exited an equal number of times before another thread
19453 ** can enter.  If the same thread tries to enter any other kind of mutex
19454 ** more than once, the behavior is undefined.
19455 */
19456 static void os2MutexEnter(sqlcipher3_mutex *p){
19457   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || os2MutexNotheld(p) );
19458   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
19459 #ifdef SQLCIPHER_DEBUG
19460   if( p->trace ) os2MutexTrace(p, "enter");
19461 #endif
19462 }
19463 static int os2MutexTry(sqlcipher3_mutex *p){
19464   int rc = SQLCIPHER_BUSY;
19465   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || os2MutexNotheld(p) );
19466   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
19467     rc = SQLCIPHER_OK;
19468 #ifdef SQLCIPHER_DEBUG
19469     if( p->trace ) os2MutexTrace(p, "try");
19470 #endif
19471   }
19472   return rc;
19473 }
19474
19475 /*
19476 ** The sqlcipher3_mutex_leave() routine exits a mutex that was
19477 ** previously entered by the same thread.  The behavior
19478 ** is undefined if the mutex is not currently entered or
19479 ** is not currently allocated.  SQLite will never do either.
19480 */
19481 static void os2MutexLeave(sqlcipher3_mutex *p){
19482   assert( os2MutexHeld(p) );
19483   DosReleaseMutexSem(p->mutex);
19484 #ifdef SQLCIPHER_DEBUG
19485   if( p->trace ) os2MutexTrace(p, "leave");
19486 #endif
19487 }
19488
19489 SQLCIPHER_PRIVATE sqlcipher3_mutex_methods const *sqlcipher3DefaultMutex(void){
19490   static const sqlcipher3_mutex_methods sMutex = {
19491     os2MutexInit,
19492     os2MutexEnd,
19493     os2MutexAlloc,
19494     os2MutexFree,
19495     os2MutexEnter,
19496     os2MutexTry,
19497     os2MutexLeave,
19498 #ifdef SQLCIPHER_DEBUG
19499     os2MutexHeld,
19500     os2MutexNotheld
19501 #else
19502     0,
19503     0
19504 #endif
19505   };
19506
19507   return &sMutex;
19508 }
19509 #endif /* SQLCIPHER_MUTEX_OS2 */
19510
19511 /************** End of mutex_os2.c *******************************************/
19512 /************** Begin file mutex_unix.c **************************************/
19513 /*
19514 ** 2007 August 28
19515 **
19516 ** The author disclaims copyright to this source code.  In place of
19517 ** a legal notice, here is a blessing:
19518 **
19519 **    May you do good and not evil.
19520 **    May you find forgiveness for yourself and forgive others.
19521 **    May you share freely, never taking more than you give.
19522 **
19523 *************************************************************************
19524 ** This file contains the C functions that implement mutexes for pthreads
19525 */
19526
19527 /*
19528 ** The code in this file is only used if we are compiling threadsafe
19529 ** under unix with pthreads.
19530 **
19531 ** Note that this implementation requires a version of pthreads that
19532 ** supports recursive mutexes.
19533 */
19534 #ifdef SQLCIPHER_MUTEX_PTHREADS
19535
19536 #include <pthread.h>
19537
19538 /*
19539 ** The sqlcipher3_mutex.id, sqlcipher3_mutex.nRef, and sqlcipher3_mutex.owner fields
19540 ** are necessary under two condidtions:  (1) Debug builds and (2) using
19541 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
19542 */
19543 #if defined(SQLCIPHER_DEBUG) || defined(SQLCIPHER_HOMEGROWN_RECURSIVE_MUTEX)
19544 # define SQLCIPHER_MUTEX_NREF 1
19545 #else
19546 # define SQLCIPHER_MUTEX_NREF 0
19547 #endif
19548
19549 /*
19550 ** Each recursive mutex is an instance of the following structure.
19551 */
19552 struct sqlcipher3_mutex {
19553   pthread_mutex_t mutex;     /* Mutex controlling the lock */
19554 #if SQLCIPHER_MUTEX_NREF
19555   int id;                    /* Mutex type */
19556   volatile int nRef;         /* Number of entrances */
19557   volatile pthread_t owner;  /* Thread that is within this mutex */
19558   int trace;                 /* True to trace changes */
19559 #endif
19560 };
19561 #if SQLCIPHER_MUTEX_NREF
19562 #define SQLCIPHER3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
19563 #else
19564 #define SQLCIPHER3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
19565 #endif
19566
19567 /*
19568 ** The sqlcipher3_mutex_held() and sqlcipher3_mutex_notheld() routine are
19569 ** intended for use only inside assert() statements.  On some platforms,
19570 ** there might be race conditions that can cause these routines to
19571 ** deliver incorrect results.  In particular, if pthread_equal() is
19572 ** not an atomic operation, then these routines might delivery
19573 ** incorrect results.  On most platforms, pthread_equal() is a 
19574 ** comparison of two integers and is therefore atomic.  But we are
19575 ** told that HPUX is not such a platform.  If so, then these routines
19576 ** will not always work correctly on HPUX.
19577 **
19578 ** On those platforms where pthread_equal() is not atomic, SQLite
19579 ** should be compiled without -DSQLCIPHER_DEBUG and with -DNDEBUG to
19580 ** make sure no assert() statements are evaluated and hence these
19581 ** routines are never called.
19582 */
19583 #if !defined(NDEBUG) || defined(SQLCIPHER_DEBUG)
19584 static int pthreadMutexHeld(sqlcipher3_mutex *p){
19585   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
19586 }
19587 static int pthreadMutexNotheld(sqlcipher3_mutex *p){
19588   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
19589 }
19590 #endif
19591
19592 /*
19593 ** Initialize and deinitialize the mutex subsystem.
19594 */
19595 static int pthreadMutexInit(void){ return SQLCIPHER_OK; }
19596 static int pthreadMutexEnd(void){ return SQLCIPHER_OK; }
19597
19598 /*
19599 ** The sqlcipher3_mutex_alloc() routine allocates a new
19600 ** mutex and returns a pointer to it.  If it returns NULL
19601 ** that means that a mutex could not be allocated.  SQLite
19602 ** will unwind its stack and return an error.  The argument
19603 ** to sqlcipher3_mutex_alloc() is one of these integer constants:
19604 **
19605 ** <ul>
19606 ** <li>  SQLCIPHER_MUTEX_FAST
19607 ** <li>  SQLCIPHER_MUTEX_RECURSIVE
19608 ** <li>  SQLCIPHER_MUTEX_STATIC_MASTER
19609 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM
19610 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM2
19611 ** <li>  SQLCIPHER_MUTEX_STATIC_PRNG
19612 ** <li>  SQLCIPHER_MUTEX_STATIC_LRU
19613 ** <li>  SQLCIPHER_MUTEX_STATIC_PMEM
19614 ** </ul>
19615 **
19616 ** The first two constants cause sqlcipher3_mutex_alloc() to create
19617 ** a new mutex.  The new mutex is recursive when SQLCIPHER_MUTEX_RECURSIVE
19618 ** is used but not necessarily so when SQLCIPHER_MUTEX_FAST is used.
19619 ** The mutex implementation does not need to make a distinction
19620 ** between SQLCIPHER_MUTEX_RECURSIVE and SQLCIPHER_MUTEX_FAST if it does
19621 ** not want to.  But SQLite will only request a recursive mutex in
19622 ** cases where it really needs one.  If a faster non-recursive mutex
19623 ** implementation is available on the host platform, the mutex subsystem
19624 ** might return such a mutex in response to SQLCIPHER_MUTEX_FAST.
19625 **
19626 ** The other allowed parameters to sqlcipher3_mutex_alloc() each return
19627 ** a pointer to a static preexisting mutex.  Six static mutexes are
19628 ** used by the current version of SQLite.  Future versions of SQLite
19629 ** may add additional static mutexes.  Static mutexes are for internal
19630 ** use by SQLite only.  Applications that use SQLite mutexes should
19631 ** use only the dynamic mutexes returned by SQLCIPHER_MUTEX_FAST or
19632 ** SQLCIPHER_MUTEX_RECURSIVE.
19633 **
19634 ** Note that if one of the dynamic mutex parameters (SQLCIPHER_MUTEX_FAST
19635 ** or SQLCIPHER_MUTEX_RECURSIVE) is used then sqlcipher3_mutex_alloc()
19636 ** returns a different mutex on every call.  But for the static 
19637 ** mutex types, the same mutex is returned on every call that has
19638 ** the same type number.
19639 */
19640 static sqlcipher3_mutex *pthreadMutexAlloc(int iType){
19641   static sqlcipher3_mutex staticMutexes[] = {
19642     SQLCIPHER3_MUTEX_INITIALIZER,
19643     SQLCIPHER3_MUTEX_INITIALIZER,
19644     SQLCIPHER3_MUTEX_INITIALIZER,
19645     SQLCIPHER3_MUTEX_INITIALIZER,
19646     SQLCIPHER3_MUTEX_INITIALIZER,
19647     SQLCIPHER3_MUTEX_INITIALIZER
19648   };
19649   sqlcipher3_mutex *p;
19650   switch( iType ){
19651     case SQLCIPHER_MUTEX_RECURSIVE: {
19652       p = sqlcipher3MallocZero( sizeof(*p) );
19653       if( p ){
19654 #ifdef SQLCIPHER_HOMEGROWN_RECURSIVE_MUTEX
19655         /* If recursive mutexes are not available, we will have to
19656         ** build our own.  See below. */
19657         pthread_mutex_init(&p->mutex, 0);
19658 #else
19659         /* Use a recursive mutex if it is available */
19660         pthread_mutexattr_t recursiveAttr;
19661         pthread_mutexattr_init(&recursiveAttr);
19662         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
19663         pthread_mutex_init(&p->mutex, &recursiveAttr);
19664         pthread_mutexattr_destroy(&recursiveAttr);
19665 #endif
19666 #if SQLCIPHER_MUTEX_NREF
19667         p->id = iType;
19668 #endif
19669       }
19670       break;
19671     }
19672     case SQLCIPHER_MUTEX_FAST: {
19673       p = sqlcipher3MallocZero( sizeof(*p) );
19674       if( p ){
19675 #if SQLCIPHER_MUTEX_NREF
19676         p->id = iType;
19677 #endif
19678         pthread_mutex_init(&p->mutex, 0);
19679       }
19680       break;
19681     }
19682     default: {
19683       assert( iType-2 >= 0 );
19684       assert( iType-2 < ArraySize(staticMutexes) );
19685       p = &staticMutexes[iType-2];
19686 #if SQLCIPHER_MUTEX_NREF
19687       p->id = iType;
19688 #endif
19689       break;
19690     }
19691   }
19692   return p;
19693 }
19694
19695
19696 /*
19697 ** This routine deallocates a previously
19698 ** allocated mutex.  SQLite is careful to deallocate every
19699 ** mutex that it allocates.
19700 */
19701 static void pthreadMutexFree(sqlcipher3_mutex *p){
19702   assert( p->nRef==0 );
19703   assert( p->id==SQLCIPHER_MUTEX_FAST || p->id==SQLCIPHER_MUTEX_RECURSIVE );
19704   pthread_mutex_destroy(&p->mutex);
19705   sqlcipher3_free(p);
19706 }
19707
19708 /*
19709 ** The sqlcipher3_mutex_enter() and sqlcipher3_mutex_try() routines attempt
19710 ** to enter a mutex.  If another thread is already within the mutex,
19711 ** sqlcipher3_mutex_enter() will block and sqlcipher3_mutex_try() will return
19712 ** SQLCIPHER_BUSY.  The sqlcipher3_mutex_try() interface returns SQLCIPHER_OK
19713 ** upon successful entry.  Mutexes created using SQLCIPHER_MUTEX_RECURSIVE can
19714 ** be entered multiple times by the same thread.  In such cases the,
19715 ** mutex must be exited an equal number of times before another thread
19716 ** can enter.  If the same thread tries to enter any other kind of mutex
19717 ** more than once, the behavior is undefined.
19718 */
19719 static void pthreadMutexEnter(sqlcipher3_mutex *p){
19720   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19721
19722 #ifdef SQLCIPHER_HOMEGROWN_RECURSIVE_MUTEX
19723   /* If recursive mutexes are not available, then we have to grow
19724   ** our own.  This implementation assumes that pthread_equal()
19725   ** is atomic - that it cannot be deceived into thinking self
19726   ** and p->owner are equal if p->owner changes between two values
19727   ** that are not equal to self while the comparison is taking place.
19728   ** This implementation also assumes a coherent cache - that 
19729   ** separate processes cannot read different values from the same
19730   ** address at the same time.  If either of these two conditions
19731   ** are not met, then the mutexes will fail and problems will result.
19732   */
19733   {
19734     pthread_t self = pthread_self();
19735     if( p->nRef>0 && pthread_equal(p->owner, self) ){
19736       p->nRef++;
19737     }else{
19738       pthread_mutex_lock(&p->mutex);
19739       assert( p->nRef==0 );
19740       p->owner = self;
19741       p->nRef = 1;
19742     }
19743   }
19744 #else
19745   /* Use the built-in recursive mutexes if they are available.
19746   */
19747   pthread_mutex_lock(&p->mutex);
19748 #if SQLCIPHER_MUTEX_NREF
19749   assert( p->nRef>0 || p->owner==0 );
19750   p->owner = pthread_self();
19751   p->nRef++;
19752 #endif
19753 #endif
19754
19755 #ifdef SQLCIPHER_DEBUG
19756   if( p->trace ){
19757     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19758   }
19759 #endif
19760 }
19761 static int pthreadMutexTry(sqlcipher3_mutex *p){
19762   int rc;
19763   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19764
19765 #ifdef SQLCIPHER_HOMEGROWN_RECURSIVE_MUTEX
19766   /* If recursive mutexes are not available, then we have to grow
19767   ** our own.  This implementation assumes that pthread_equal()
19768   ** is atomic - that it cannot be deceived into thinking self
19769   ** and p->owner are equal if p->owner changes between two values
19770   ** that are not equal to self while the comparison is taking place.
19771   ** This implementation also assumes a coherent cache - that 
19772   ** separate processes cannot read different values from the same
19773   ** address at the same time.  If either of these two conditions
19774   ** are not met, then the mutexes will fail and problems will result.
19775   */
19776   {
19777     pthread_t self = pthread_self();
19778     if( p->nRef>0 && pthread_equal(p->owner, self) ){
19779       p->nRef++;
19780       rc = SQLCIPHER_OK;
19781     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
19782       assert( p->nRef==0 );
19783       p->owner = self;
19784       p->nRef = 1;
19785       rc = SQLCIPHER_OK;
19786     }else{
19787       rc = SQLCIPHER_BUSY;
19788     }
19789   }
19790 #else
19791   /* Use the built-in recursive mutexes if they are available.
19792   */
19793   if( pthread_mutex_trylock(&p->mutex)==0 ){
19794 #if SQLCIPHER_MUTEX_NREF
19795     p->owner = pthread_self();
19796     p->nRef++;
19797 #endif
19798     rc = SQLCIPHER_OK;
19799   }else{
19800     rc = SQLCIPHER_BUSY;
19801   }
19802 #endif
19803
19804 #ifdef SQLCIPHER_DEBUG
19805   if( rc==SQLCIPHER_OK && p->trace ){
19806     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19807   }
19808 #endif
19809   return rc;
19810 }
19811
19812 /*
19813 ** The sqlcipher3_mutex_leave() routine exits a mutex that was
19814 ** previously entered by the same thread.  The behavior
19815 ** is undefined if the mutex is not currently entered or
19816 ** is not currently allocated.  SQLite will never do either.
19817 */
19818 static void pthreadMutexLeave(sqlcipher3_mutex *p){
19819   assert( pthreadMutexHeld(p) );
19820 #if SQLCIPHER_MUTEX_NREF
19821   p->nRef--;
19822   if( p->nRef==0 ) p->owner = 0;
19823 #endif
19824   assert( p->nRef==0 || p->id==SQLCIPHER_MUTEX_RECURSIVE );
19825
19826 #ifdef SQLCIPHER_HOMEGROWN_RECURSIVE_MUTEX
19827   if( p->nRef==0 ){
19828     pthread_mutex_unlock(&p->mutex);
19829   }
19830 #else
19831   pthread_mutex_unlock(&p->mutex);
19832 #endif
19833
19834 #ifdef SQLCIPHER_DEBUG
19835   if( p->trace ){
19836     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19837   }
19838 #endif
19839 }
19840
19841 SQLCIPHER_PRIVATE sqlcipher3_mutex_methods const *sqlcipher3DefaultMutex(void){
19842   static const sqlcipher3_mutex_methods sMutex = {
19843     pthreadMutexInit,
19844     pthreadMutexEnd,
19845     pthreadMutexAlloc,
19846     pthreadMutexFree,
19847     pthreadMutexEnter,
19848     pthreadMutexTry,
19849     pthreadMutexLeave,
19850 #ifdef SQLCIPHER_DEBUG
19851     pthreadMutexHeld,
19852     pthreadMutexNotheld
19853 #else
19854     0,
19855     0
19856 #endif
19857   };
19858
19859   return &sMutex;
19860 }
19861
19862 #endif /* SQLCIPHER_MUTEX_PTHREAD */
19863
19864 /************** End of mutex_unix.c ******************************************/
19865 /************** Begin file mutex_w32.c ***************************************/
19866 /*
19867 ** 2007 August 14
19868 **
19869 ** The author disclaims copyright to this source code.  In place of
19870 ** a legal notice, here is a blessing:
19871 **
19872 **    May you do good and not evil.
19873 **    May you find forgiveness for yourself and forgive others.
19874 **    May you share freely, never taking more than you give.
19875 **
19876 *************************************************************************
19877 ** This file contains the C functions that implement mutexes for win32
19878 */
19879
19880 /*
19881 ** The code in this file is only used if we are compiling multithreaded
19882 ** on a win32 system.
19883 */
19884 #ifdef SQLCIPHER_MUTEX_W32
19885
19886 /*
19887 ** Each recursive mutex is an instance of the following structure.
19888 */
19889 struct sqlcipher3_mutex {
19890   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
19891   int id;                    /* Mutex type */
19892 #ifdef SQLCIPHER_DEBUG
19893   volatile int nRef;         /* Number of enterances */
19894   volatile DWORD owner;      /* Thread holding this mutex */
19895   int trace;                 /* True to trace changes */
19896 #endif
19897 };
19898 #define SQLCIPHER_W32_MUTEX_INITIALIZER { 0 }
19899 #ifdef SQLCIPHER_DEBUG
19900 #define SQLCIPHER3_MUTEX_INITIALIZER { SQLCIPHER_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
19901 #else
19902 #define SQLCIPHER3_MUTEX_INITIALIZER { SQLCIPHER_W32_MUTEX_INITIALIZER, 0 }
19903 #endif
19904
19905 /*
19906 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
19907 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
19908 **
19909 ** Here is an interesting observation:  Win95, Win98, and WinME lack
19910 ** the LockFileEx() API.  But we can still statically link against that
19911 ** API as long as we don't call it win running Win95/98/ME.  A call to
19912 ** this routine is used to determine if the host is Win95/98/ME or
19913 ** WinNT/2K/XP so that we will know whether or not we can safely call
19914 ** the LockFileEx() API.
19915 **
19916 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
19917 ** which is only available if your application was compiled with 
19918 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
19919 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
19920 ** this out as well.
19921 */
19922 #if 0
19923 #if SQLCIPHER_OS_WINCE
19924 # define mutexIsNT()  (1)
19925 #else
19926   static int mutexIsNT(void){
19927     static int osType = 0;
19928     if( osType==0 ){
19929       OSVERSIONINFO sInfo;
19930       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
19931       GetVersionEx(&sInfo);
19932       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
19933     }
19934     return osType==2;
19935   }
19936 #endif /* SQLCIPHER_OS_WINCE */
19937 #endif
19938
19939 #ifdef SQLCIPHER_DEBUG
19940 /*
19941 ** The sqlcipher3_mutex_held() and sqlcipher3_mutex_notheld() routine are
19942 ** intended for use only inside assert() statements.
19943 */
19944 static int winMutexHeld(sqlcipher3_mutex *p){
19945   return p->nRef!=0 && p->owner==GetCurrentThreadId();
19946 }
19947 static int winMutexNotheld2(sqlcipher3_mutex *p, DWORD tid){
19948   return p->nRef==0 || p->owner!=tid;
19949 }
19950 static int winMutexNotheld(sqlcipher3_mutex *p){
19951   DWORD tid = GetCurrentThreadId(); 
19952   return winMutexNotheld2(p, tid);
19953 }
19954 #endif
19955
19956
19957 /*
19958 ** Initialize and deinitialize the mutex subsystem.
19959 */
19960 static sqlcipher3_mutex winMutex_staticMutexes[6] = {
19961   SQLCIPHER3_MUTEX_INITIALIZER,
19962   SQLCIPHER3_MUTEX_INITIALIZER,
19963   SQLCIPHER3_MUTEX_INITIALIZER,
19964   SQLCIPHER3_MUTEX_INITIALIZER,
19965   SQLCIPHER3_MUTEX_INITIALIZER,
19966   SQLCIPHER3_MUTEX_INITIALIZER
19967 };
19968 static int winMutex_isInit = 0;
19969 /* As winMutexInit() and winMutexEnd() are called as part
19970 ** of the sqlcipher3_initialize and sqlcipher3_shutdown()
19971 ** processing, the "interlocked" magic is probably not
19972 ** strictly necessary.
19973 */
19974 static long winMutex_lock = 0;
19975
19976 static int winMutexInit(void){ 
19977   /* The first to increment to 1 does actual initialization */
19978   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
19979     int i;
19980     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
19981       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
19982     }
19983     winMutex_isInit = 1;
19984   }else{
19985     /* Someone else is in the process of initing the static mutexes */
19986     while( !winMutex_isInit ){
19987       Sleep(1);
19988     }
19989   }
19990   return SQLCIPHER_OK; 
19991 }
19992
19993 static int winMutexEnd(void){ 
19994   /* The first to decrement to 0 does actual shutdown 
19995   ** (which should be the last to shutdown.) */
19996   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
19997     if( winMutex_isInit==1 ){
19998       int i;
19999       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
20000         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
20001       }
20002       winMutex_isInit = 0;
20003     }
20004   }
20005   return SQLCIPHER_OK; 
20006 }
20007
20008 /*
20009 ** The sqlcipher3_mutex_alloc() routine allocates a new
20010 ** mutex and returns a pointer to it.  If it returns NULL
20011 ** that means that a mutex could not be allocated.  SQLite
20012 ** will unwind its stack and return an error.  The argument
20013 ** to sqlcipher3_mutex_alloc() is one of these integer constants:
20014 **
20015 ** <ul>
20016 ** <li>  SQLCIPHER_MUTEX_FAST
20017 ** <li>  SQLCIPHER_MUTEX_RECURSIVE
20018 ** <li>  SQLCIPHER_MUTEX_STATIC_MASTER
20019 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM
20020 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM2
20021 ** <li>  SQLCIPHER_MUTEX_STATIC_PRNG
20022 ** <li>  SQLCIPHER_MUTEX_STATIC_LRU
20023 ** <li>  SQLCIPHER_MUTEX_STATIC_PMEM
20024 ** </ul>
20025 **
20026 ** The first two constants cause sqlcipher3_mutex_alloc() to create
20027 ** a new mutex.  The new mutex is recursive when SQLCIPHER_MUTEX_RECURSIVE
20028 ** is used but not necessarily so when SQLCIPHER_MUTEX_FAST is used.
20029 ** The mutex implementation does not need to make a distinction
20030 ** between SQLCIPHER_MUTEX_RECURSIVE and SQLCIPHER_MUTEX_FAST if it does
20031 ** not want to.  But SQLite will only request a recursive mutex in
20032 ** cases where it really needs one.  If a faster non-recursive mutex
20033 ** implementation is available on the host platform, the mutex subsystem
20034 ** might return such a mutex in response to SQLCIPHER_MUTEX_FAST.
20035 **
20036 ** The other allowed parameters to sqlcipher3_mutex_alloc() each return
20037 ** a pointer to a static preexisting mutex.  Six static mutexes are
20038 ** used by the current version of SQLite.  Future versions of SQLite
20039 ** may add additional static mutexes.  Static mutexes are for internal
20040 ** use by SQLite only.  Applications that use SQLite mutexes should
20041 ** use only the dynamic mutexes returned by SQLCIPHER_MUTEX_FAST or
20042 ** SQLCIPHER_MUTEX_RECURSIVE.
20043 **
20044 ** Note that if one of the dynamic mutex parameters (SQLCIPHER_MUTEX_FAST
20045 ** or SQLCIPHER_MUTEX_RECURSIVE) is used then sqlcipher3_mutex_alloc()
20046 ** returns a different mutex on every call.  But for the static 
20047 ** mutex types, the same mutex is returned on every call that has
20048 ** the same type number.
20049 */
20050 static sqlcipher3_mutex *winMutexAlloc(int iType){
20051   sqlcipher3_mutex *p;
20052
20053   switch( iType ){
20054     case SQLCIPHER_MUTEX_FAST:
20055     case SQLCIPHER_MUTEX_RECURSIVE: {
20056       p = sqlcipher3MallocZero( sizeof(*p) );
20057       if( p ){  
20058 #ifdef SQLCIPHER_DEBUG
20059         p->id = iType;
20060 #endif
20061         InitializeCriticalSection(&p->mutex);
20062       }
20063       break;
20064     }
20065     default: {
20066       assert( winMutex_isInit==1 );
20067       assert( iType-2 >= 0 );
20068       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
20069       p = &winMutex_staticMutexes[iType-2];
20070 #ifdef SQLCIPHER_DEBUG
20071       p->id = iType;
20072 #endif
20073       break;
20074     }
20075   }
20076   return p;
20077 }
20078
20079
20080 /*
20081 ** This routine deallocates a previously
20082 ** allocated mutex.  SQLite is careful to deallocate every
20083 ** mutex that it allocates.
20084 */
20085 static void winMutexFree(sqlcipher3_mutex *p){
20086   assert( p );
20087   assert( p->nRef==0 && p->owner==0 );
20088   assert( p->id==SQLCIPHER_MUTEX_FAST || p->id==SQLCIPHER_MUTEX_RECURSIVE );
20089   DeleteCriticalSection(&p->mutex);
20090   sqlcipher3_free(p);
20091 }
20092
20093 /*
20094 ** The sqlcipher3_mutex_enter() and sqlcipher3_mutex_try() routines attempt
20095 ** to enter a mutex.  If another thread is already within the mutex,
20096 ** sqlcipher3_mutex_enter() will block and sqlcipher3_mutex_try() will return
20097 ** SQLCIPHER_BUSY.  The sqlcipher3_mutex_try() interface returns SQLCIPHER_OK
20098 ** upon successful entry.  Mutexes created using SQLCIPHER_MUTEX_RECURSIVE can
20099 ** be entered multiple times by the same thread.  In such cases the,
20100 ** mutex must be exited an equal number of times before another thread
20101 ** can enter.  If the same thread tries to enter any other kind of mutex
20102 ** more than once, the behavior is undefined.
20103 */
20104 static void winMutexEnter(sqlcipher3_mutex *p){
20105 #ifdef SQLCIPHER_DEBUG
20106   DWORD tid = GetCurrentThreadId(); 
20107   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
20108 #endif
20109   EnterCriticalSection(&p->mutex);
20110 #ifdef SQLCIPHER_DEBUG
20111   assert( p->nRef>0 || p->owner==0 );
20112   p->owner = tid; 
20113   p->nRef++;
20114   if( p->trace ){
20115     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20116   }
20117 #endif
20118 }
20119 static int winMutexTry(sqlcipher3_mutex *p){
20120 #ifndef NDEBUG
20121   DWORD tid = GetCurrentThreadId(); 
20122 #endif
20123   int rc = SQLCIPHER_BUSY;
20124   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
20125   /*
20126   ** The sqlcipher3_mutex_try() routine is very rarely used, and when it
20127   ** is used it is merely an optimization.  So it is OK for it to always
20128   ** fail.  
20129   **
20130   ** The TryEnterCriticalSection() interface is only available on WinNT.
20131   ** And some windows compilers complain if you try to use it without
20132   ** first doing some #defines that prevent SQLite from building on Win98.
20133   ** For that reason, we will omit this optimization for now.  See
20134   ** ticket #2685.
20135   */
20136 #if 0
20137   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
20138     p->owner = tid;
20139     p->nRef++;
20140     rc = SQLCIPHER_OK;
20141   }
20142 #else
20143   UNUSED_PARAMETER(p);
20144 #endif
20145 #ifdef SQLCIPHER_DEBUG
20146   if( rc==SQLCIPHER_OK && p->trace ){
20147     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20148   }
20149 #endif
20150   return rc;
20151 }
20152
20153 /*
20154 ** The sqlcipher3_mutex_leave() routine exits a mutex that was
20155 ** previously entered by the same thread.  The behavior
20156 ** is undefined if the mutex is not currently entered or
20157 ** is not currently allocated.  SQLite will never do either.
20158 */
20159 static void winMutexLeave(sqlcipher3_mutex *p){
20160 #ifndef NDEBUG
20161   DWORD tid = GetCurrentThreadId();
20162   assert( p->nRef>0 );
20163   assert( p->owner==tid );
20164   p->nRef--;
20165   if( p->nRef==0 ) p->owner = 0;
20166   assert( p->nRef==0 || p->id==SQLCIPHER_MUTEX_RECURSIVE );
20167 #endif
20168   LeaveCriticalSection(&p->mutex);
20169 #ifdef SQLCIPHER_DEBUG
20170   if( p->trace ){
20171     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20172   }
20173 #endif
20174 }
20175
20176 SQLCIPHER_PRIVATE sqlcipher3_mutex_methods const *sqlcipher3DefaultMutex(void){
20177   static const sqlcipher3_mutex_methods sMutex = {
20178     winMutexInit,
20179     winMutexEnd,
20180     winMutexAlloc,
20181     winMutexFree,
20182     winMutexEnter,
20183     winMutexTry,
20184     winMutexLeave,
20185 #ifdef SQLCIPHER_DEBUG
20186     winMutexHeld,
20187     winMutexNotheld
20188 #else
20189     0,
20190     0
20191 #endif
20192   };
20193
20194   return &sMutex;
20195 }
20196 #endif /* SQLCIPHER_MUTEX_W32 */
20197
20198 /************** End of mutex_w32.c *******************************************/
20199 /************** Begin file malloc.c ******************************************/
20200 /*
20201 ** 2001 September 15
20202 **
20203 ** The author disclaims copyright to this source code.  In place of
20204 ** a legal notice, here is a blessing:
20205 **
20206 **    May you do good and not evil.
20207 **    May you find forgiveness for yourself and forgive others.
20208 **    May you share freely, never taking more than you give.
20209 **
20210 *************************************************************************
20211 **
20212 ** Memory allocation functions used throughout sqlcipher.
20213 */
20214 /* #include <stdarg.h> */
20215
20216 /*
20217 ** Attempt to release up to n bytes of non-essential memory currently
20218 ** held by SQLite. An example of non-essential memory is memory used to
20219 ** cache database pages that are not currently in use.
20220 */
20221 SQLCIPHER_API int sqlcipher3_release_memory(int n){
20222 #ifdef SQLCIPHER_ENABLE_MEMORY_MANAGEMENT
20223   return sqlcipher3PcacheReleaseMemory(n);
20224 #else
20225   /* IMPLEMENTATION-OF: R-34391-24921 The sqlcipher3_release_memory() routine
20226   ** is a no-op returning zero if SQLite is not compiled with
20227   ** SQLCIPHER_ENABLE_MEMORY_MANAGEMENT. */
20228   UNUSED_PARAMETER(n);
20229   return 0;
20230 #endif
20231 }
20232
20233 /*
20234 ** An instance of the following object records the location of
20235 ** each unused scratch buffer.
20236 */
20237 typedef struct ScratchFreeslot {
20238   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
20239 } ScratchFreeslot;
20240
20241 /*
20242 ** State information local to the memory allocation subsystem.
20243 */
20244 static SQLCIPHER_WSD struct Mem0Global {
20245   sqlcipher3_mutex *mutex;         /* Mutex to serialize access */
20246
20247   /*
20248   ** The alarm callback and its arguments.  The mem0.mutex lock will
20249   ** be held while the callback is running.  Recursive calls into
20250   ** the memory subsystem are allowed, but no new callbacks will be
20251   ** issued.
20252   */
20253   sqlcipher3_int64 alarmThreshold;
20254   void (*alarmCallback)(void*, sqlcipher3_int64,int);
20255   void *alarmArg;
20256
20257   /*
20258   ** Pointers to the end of sqlcipher3GlobalConfig.pScratch memory
20259   ** (so that a range test can be used to determine if an allocation
20260   ** being freed came from pScratch) and a pointer to the list of
20261   ** unused scratch allocations.
20262   */
20263   void *pScratchEnd;
20264   ScratchFreeslot *pScratchFree;
20265   u32 nScratchFree;
20266
20267   /*
20268   ** True if heap is nearly "full" where "full" is defined by the
20269   ** sqlcipher3_soft_heap_limit() setting.
20270   */
20271   int nearlyFull;
20272 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
20273
20274 #define mem0 GLOBAL(struct Mem0Global, mem0)
20275
20276 /*
20277 ** This routine runs when the memory allocator sees that the
20278 ** total memory allocation is about to exceed the soft heap
20279 ** limit.
20280 */
20281 static void softHeapLimitEnforcer(
20282   void *NotUsed, 
20283   sqlcipher3_int64 NotUsed2,
20284   int allocSize
20285 ){
20286   UNUSED_PARAMETER2(NotUsed, NotUsed2);
20287   sqlcipher3_release_memory(allocSize);
20288 }
20289
20290 /*
20291 ** Change the alarm callback
20292 */
20293 static int sqlcipher3MemoryAlarm(
20294   void(*xCallback)(void *pArg, sqlcipher3_int64 used,int N),
20295   void *pArg,
20296   sqlcipher3_int64 iThreshold
20297 ){
20298   int nUsed;
20299   sqlcipher3_mutex_enter(mem0.mutex);
20300   mem0.alarmCallback = xCallback;
20301   mem0.alarmArg = pArg;
20302   mem0.alarmThreshold = iThreshold;
20303   nUsed = sqlcipher3StatusValue(SQLCIPHER_STATUS_MEMORY_USED);
20304   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
20305   sqlcipher3_mutex_leave(mem0.mutex);
20306   return SQLCIPHER_OK;
20307 }
20308
20309 #ifndef SQLCIPHER_OMIT_DEPRECATED
20310 /*
20311 ** Deprecated external interface.  Internal/core SQLite code
20312 ** should call sqlcipher3MemoryAlarm.
20313 */
20314 SQLCIPHER_API int sqlcipher3_memory_alarm(
20315   void(*xCallback)(void *pArg, sqlcipher3_int64 used,int N),
20316   void *pArg,
20317   sqlcipher3_int64 iThreshold
20318 ){
20319   return sqlcipher3MemoryAlarm(xCallback, pArg, iThreshold);
20320 }
20321 #endif
20322
20323 /*
20324 ** Set the soft heap-size limit for the library. Passing a zero or 
20325 ** negative value indicates no limit.
20326 */
20327 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_soft_heap_limit64(sqlcipher3_int64 n){
20328   sqlcipher3_int64 priorLimit;
20329   sqlcipher3_int64 excess;
20330 #ifndef SQLCIPHER_OMIT_AUTOINIT
20331   sqlcipher3_initialize();
20332 #endif
20333   sqlcipher3_mutex_enter(mem0.mutex);
20334   priorLimit = mem0.alarmThreshold;
20335   sqlcipher3_mutex_leave(mem0.mutex);
20336   if( n<0 ) return priorLimit;
20337   if( n>0 ){
20338     sqlcipher3MemoryAlarm(softHeapLimitEnforcer, 0, n);
20339   }else{
20340     sqlcipher3MemoryAlarm(0, 0, 0);
20341   }
20342   excess = sqlcipher3_memory_used() - n;
20343   if( excess>0 ) sqlcipher3_release_memory((int)(excess & 0x7fffffff));
20344   return priorLimit;
20345 }
20346 SQLCIPHER_API void sqlcipher3_soft_heap_limit(int n){
20347   if( n<0 ) n = 0;
20348   sqlcipher3_soft_heap_limit64(n);
20349 }
20350
20351 /*
20352 ** Initialize the memory allocation subsystem.
20353 */
20354 SQLCIPHER_PRIVATE int sqlcipher3MallocInit(void){
20355   if( sqlcipher3GlobalConfig.m.xMalloc==0 ){
20356     sqlcipher3MemSetDefault();
20357   }
20358   memset(&mem0, 0, sizeof(mem0));
20359   if( sqlcipher3GlobalConfig.bCoreMutex ){
20360     mem0.mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MEM);
20361   }
20362   if( sqlcipher3GlobalConfig.pScratch && sqlcipher3GlobalConfig.szScratch>=100
20363       && sqlcipher3GlobalConfig.nScratch>0 ){
20364     int i, n, sz;
20365     ScratchFreeslot *pSlot;
20366     sz = ROUNDDOWN8(sqlcipher3GlobalConfig.szScratch);
20367     sqlcipher3GlobalConfig.szScratch = sz;
20368     pSlot = (ScratchFreeslot*)sqlcipher3GlobalConfig.pScratch;
20369     n = sqlcipher3GlobalConfig.nScratch;
20370     mem0.pScratchFree = pSlot;
20371     mem0.nScratchFree = n;
20372     for(i=0; i<n-1; i++){
20373       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
20374       pSlot = pSlot->pNext;
20375     }
20376     pSlot->pNext = 0;
20377     mem0.pScratchEnd = (void*)&pSlot[1];
20378   }else{
20379     mem0.pScratchEnd = 0;
20380     sqlcipher3GlobalConfig.pScratch = 0;
20381     sqlcipher3GlobalConfig.szScratch = 0;
20382     sqlcipher3GlobalConfig.nScratch = 0;
20383   }
20384   if( sqlcipher3GlobalConfig.pPage==0 || sqlcipher3GlobalConfig.szPage<512
20385       || sqlcipher3GlobalConfig.nPage<1 ){
20386     sqlcipher3GlobalConfig.pPage = 0;
20387     sqlcipher3GlobalConfig.szPage = 0;
20388     sqlcipher3GlobalConfig.nPage = 0;
20389   }
20390   return sqlcipher3GlobalConfig.m.xInit(sqlcipher3GlobalConfig.m.pAppData);
20391 }
20392
20393 /*
20394 ** Return true if the heap is currently under memory pressure - in other
20395 ** words if the amount of heap used is close to the limit set by
20396 ** sqlcipher3_soft_heap_limit().
20397 */
20398 SQLCIPHER_PRIVATE int sqlcipher3HeapNearlyFull(void){
20399   return mem0.nearlyFull;
20400 }
20401
20402 /*
20403 ** Deinitialize the memory allocation subsystem.
20404 */
20405 SQLCIPHER_PRIVATE void sqlcipher3MallocEnd(void){
20406   if( sqlcipher3GlobalConfig.m.xShutdown ){
20407     sqlcipher3GlobalConfig.m.xShutdown(sqlcipher3GlobalConfig.m.pAppData);
20408   }
20409   memset(&mem0, 0, sizeof(mem0));
20410 }
20411
20412 /*
20413 ** Return the amount of memory currently checked out.
20414 */
20415 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_memory_used(void){
20416   int n, mx;
20417   sqlcipher3_int64 res;
20418   sqlcipher3_status(SQLCIPHER_STATUS_MEMORY_USED, &n, &mx, 0);
20419   res = (sqlcipher3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
20420   return res;
20421 }
20422
20423 /*
20424 ** Return the maximum amount of memory that has ever been
20425 ** checked out since either the beginning of this process
20426 ** or since the most recent reset.
20427 */
20428 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_memory_highwater(int resetFlag){
20429   int n, mx;
20430   sqlcipher3_int64 res;
20431   sqlcipher3_status(SQLCIPHER_STATUS_MEMORY_USED, &n, &mx, resetFlag);
20432   res = (sqlcipher3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
20433   return res;
20434 }
20435
20436 /*
20437 ** Trigger the alarm 
20438 */
20439 static void sqlcipher3MallocAlarm(int nByte){
20440   void (*xCallback)(void*,sqlcipher3_int64,int);
20441   sqlcipher3_int64 nowUsed;
20442   void *pArg;
20443   if( mem0.alarmCallback==0 ) return;
20444   xCallback = mem0.alarmCallback;
20445   nowUsed = sqlcipher3StatusValue(SQLCIPHER_STATUS_MEMORY_USED);
20446   pArg = mem0.alarmArg;
20447   mem0.alarmCallback = 0;
20448   sqlcipher3_mutex_leave(mem0.mutex);
20449   xCallback(pArg, nowUsed, nByte);
20450   sqlcipher3_mutex_enter(mem0.mutex);
20451   mem0.alarmCallback = xCallback;
20452   mem0.alarmArg = pArg;
20453 }
20454
20455 /*
20456 ** Do a memory allocation with statistics and alarms.  Assume the
20457 ** lock is already held.
20458 */
20459 static int mallocWithAlarm(int n, void **pp){
20460   int nFull;
20461   void *p;
20462   assert( sqlcipher3_mutex_held(mem0.mutex) );
20463   nFull = sqlcipher3GlobalConfig.m.xRoundup(n);
20464   sqlcipher3StatusSet(SQLCIPHER_STATUS_MALLOC_SIZE, n);
20465   if( mem0.alarmCallback!=0 ){
20466     int nUsed = sqlcipher3StatusValue(SQLCIPHER_STATUS_MEMORY_USED);
20467     if( nUsed >= mem0.alarmThreshold - nFull ){
20468       mem0.nearlyFull = 1;
20469       sqlcipher3MallocAlarm(nFull);
20470     }else{
20471       mem0.nearlyFull = 0;
20472     }
20473   }
20474   p = sqlcipher3GlobalConfig.m.xMalloc(nFull);
20475 #ifdef SQLCIPHER_ENABLE_MEMORY_MANAGEMENT
20476   if( p==0 && mem0.alarmCallback ){
20477     sqlcipher3MallocAlarm(nFull);
20478     p = sqlcipher3GlobalConfig.m.xMalloc(nFull);
20479   }
20480 #endif
20481   if( p ){
20482     nFull = sqlcipher3MallocSize(p);
20483     sqlcipher3StatusAdd(SQLCIPHER_STATUS_MEMORY_USED, nFull);
20484     sqlcipher3StatusAdd(SQLCIPHER_STATUS_MALLOC_COUNT, 1);
20485   }
20486   *pp = p;
20487   return nFull;
20488 }
20489
20490 /*
20491 ** Allocate memory.  This routine is like sqlcipher3_malloc() except that it
20492 ** assumes the memory subsystem has already been initialized.
20493 */
20494 SQLCIPHER_PRIVATE void *sqlcipher3Malloc(int n){
20495   void *p;
20496   if( n<=0               /* IMP: R-65312-04917 */ 
20497    || n>=0x7fffff00
20498   ){
20499     /* A memory allocation of a number of bytes which is near the maximum
20500     ** signed integer value might cause an integer overflow inside of the
20501     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
20502     ** 255 bytes of overhead.  SQLite itself will never use anything near
20503     ** this amount.  The only way to reach the limit is with sqlcipher3_malloc() */
20504     p = 0;
20505   }else if( sqlcipher3GlobalConfig.bMemstat ){
20506     sqlcipher3_mutex_enter(mem0.mutex);
20507     mallocWithAlarm(n, &p);
20508     sqlcipher3_mutex_leave(mem0.mutex);
20509   }else{
20510     p = sqlcipher3GlobalConfig.m.xMalloc(n);
20511   }
20512   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
20513   return p;
20514 }
20515
20516 /*
20517 ** This version of the memory allocation is for use by the application.
20518 ** First make sure the memory subsystem is initialized, then do the
20519 ** allocation.
20520 */
20521 SQLCIPHER_API void *sqlcipher3_malloc(int n){
20522 #ifndef SQLCIPHER_OMIT_AUTOINIT
20523   if( sqlcipher3_initialize() ) return 0;
20524 #endif
20525   return sqlcipher3Malloc(n);
20526 }
20527
20528 /*
20529 ** Each thread may only have a single outstanding allocation from
20530 ** xScratchMalloc().  We verify this constraint in the single-threaded
20531 ** case by setting scratchAllocOut to 1 when an allocation
20532 ** is outstanding clearing it when the allocation is freed.
20533 */
20534 #if SQLCIPHER_THREADSAFE==0 && !defined(NDEBUG)
20535 static int scratchAllocOut = 0;
20536 #endif
20537
20538
20539 /*
20540 ** Allocate memory that is to be used and released right away.
20541 ** This routine is similar to alloca() in that it is not intended
20542 ** for situations where the memory might be held long-term.  This
20543 ** routine is intended to get memory to old large transient data
20544 ** structures that would not normally fit on the stack of an
20545 ** embedded processor.
20546 */
20547 SQLCIPHER_PRIVATE void *sqlcipher3ScratchMalloc(int n){
20548   void *p;
20549   assert( n>0 );
20550
20551   sqlcipher3_mutex_enter(mem0.mutex);
20552   if( mem0.nScratchFree && sqlcipher3GlobalConfig.szScratch>=n ){
20553     p = mem0.pScratchFree;
20554     mem0.pScratchFree = mem0.pScratchFree->pNext;
20555     mem0.nScratchFree--;
20556     sqlcipher3StatusAdd(SQLCIPHER_STATUS_SCRATCH_USED, 1);
20557     sqlcipher3StatusSet(SQLCIPHER_STATUS_SCRATCH_SIZE, n);
20558     sqlcipher3_mutex_leave(mem0.mutex);
20559   }else{
20560     if( sqlcipher3GlobalConfig.bMemstat ){
20561       sqlcipher3StatusSet(SQLCIPHER_STATUS_SCRATCH_SIZE, n);
20562       n = mallocWithAlarm(n, &p);
20563       if( p ) sqlcipher3StatusAdd(SQLCIPHER_STATUS_SCRATCH_OVERFLOW, n);
20564       sqlcipher3_mutex_leave(mem0.mutex);
20565     }else{
20566       sqlcipher3_mutex_leave(mem0.mutex);
20567       p = sqlcipher3GlobalConfig.m.xMalloc(n);
20568     }
20569     sqlcipher3MemdebugSetType(p, MEMTYPE_SCRATCH);
20570   }
20571   assert( sqlcipher3_mutex_notheld(mem0.mutex) );
20572
20573
20574 #if SQLCIPHER_THREADSAFE==0 && !defined(NDEBUG)
20575   /* Verify that no more than two scratch allocations per thread
20576   ** are outstanding at one time.  (This is only checked in the
20577   ** single-threaded case since checking in the multi-threaded case
20578   ** would be much more complicated.) */
20579   assert( scratchAllocOut<=1 );
20580   if( p ) scratchAllocOut++;
20581 #endif
20582
20583   return p;
20584 }
20585 SQLCIPHER_PRIVATE void sqlcipher3ScratchFree(void *p){
20586   if( p ){
20587
20588 #if SQLCIPHER_THREADSAFE==0 && !defined(NDEBUG)
20589     /* Verify that no more than two scratch allocation per thread
20590     ** is outstanding at one time.  (This is only checked in the
20591     ** single-threaded case since checking in the multi-threaded case
20592     ** would be much more complicated.) */
20593     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
20594     scratchAllocOut--;
20595 #endif
20596
20597     if( p>=sqlcipher3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
20598       /* Release memory from the SQLCIPHER_CONFIG_SCRATCH allocation */
20599       ScratchFreeslot *pSlot;
20600       pSlot = (ScratchFreeslot*)p;
20601       sqlcipher3_mutex_enter(mem0.mutex);
20602       pSlot->pNext = mem0.pScratchFree;
20603       mem0.pScratchFree = pSlot;
20604       mem0.nScratchFree++;
20605       assert( mem0.nScratchFree <= (u32)sqlcipher3GlobalConfig.nScratch );
20606       sqlcipher3StatusAdd(SQLCIPHER_STATUS_SCRATCH_USED, -1);
20607       sqlcipher3_mutex_leave(mem0.mutex);
20608     }else{
20609       /* Release memory back to the heap */
20610       assert( sqlcipher3MemdebugHasType(p, MEMTYPE_SCRATCH) );
20611       assert( sqlcipher3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
20612       sqlcipher3MemdebugSetType(p, MEMTYPE_HEAP);
20613       if( sqlcipher3GlobalConfig.bMemstat ){
20614         int iSize = sqlcipher3MallocSize(p);
20615         sqlcipher3_mutex_enter(mem0.mutex);
20616         sqlcipher3StatusAdd(SQLCIPHER_STATUS_SCRATCH_OVERFLOW, -iSize);
20617         sqlcipher3StatusAdd(SQLCIPHER_STATUS_MEMORY_USED, -iSize);
20618         sqlcipher3StatusAdd(SQLCIPHER_STATUS_MALLOC_COUNT, -1);
20619         sqlcipher3GlobalConfig.m.xFree(p);
20620         sqlcipher3_mutex_leave(mem0.mutex);
20621       }else{
20622         sqlcipher3GlobalConfig.m.xFree(p);
20623       }
20624     }
20625   }
20626 }
20627
20628 /*
20629 ** TRUE if p is a lookaside memory allocation from db
20630 */
20631 #ifndef SQLCIPHER_OMIT_LOOKASIDE
20632 static int isLookaside(sqlcipher3 *db, void *p){
20633   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
20634 }
20635 #else
20636 #define isLookaside(A,B) 0
20637 #endif
20638
20639 /*
20640 ** Return the size of a memory allocation previously obtained from
20641 ** sqlcipher3Malloc() or sqlcipher3_malloc().
20642 */
20643 SQLCIPHER_PRIVATE int sqlcipher3MallocSize(void *p){
20644   assert( sqlcipher3MemdebugHasType(p, MEMTYPE_HEAP) );
20645   assert( sqlcipher3MemdebugNoType(p, MEMTYPE_DB) );
20646   return sqlcipher3GlobalConfig.m.xSize(p);
20647 }
20648 SQLCIPHER_PRIVATE int sqlcipher3DbMallocSize(sqlcipher3 *db, void *p){
20649   assert( db==0 || sqlcipher3_mutex_held(db->mutex) );
20650   if( db && isLookaside(db, p) ){
20651     return db->lookaside.sz;
20652   }else{
20653     assert( sqlcipher3MemdebugHasType(p, MEMTYPE_DB) );
20654     assert( sqlcipher3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
20655     assert( db!=0 || sqlcipher3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
20656     return sqlcipher3GlobalConfig.m.xSize(p);
20657   }
20658 }
20659
20660 /*
20661 ** Free memory previously obtained from sqlcipher3Malloc().
20662 */
20663 SQLCIPHER_API void sqlcipher3_free(void *p){
20664   if( p==0 ) return;  /* IMP: R-49053-54554 */
20665   assert( sqlcipher3MemdebugNoType(p, MEMTYPE_DB) );
20666   assert( sqlcipher3MemdebugHasType(p, MEMTYPE_HEAP) );
20667   if( sqlcipher3GlobalConfig.bMemstat ){
20668     sqlcipher3_mutex_enter(mem0.mutex);
20669     sqlcipher3StatusAdd(SQLCIPHER_STATUS_MEMORY_USED, -sqlcipher3MallocSize(p));
20670     sqlcipher3StatusAdd(SQLCIPHER_STATUS_MALLOC_COUNT, -1);
20671     sqlcipher3GlobalConfig.m.xFree(p);
20672     sqlcipher3_mutex_leave(mem0.mutex);
20673   }else{
20674     sqlcipher3GlobalConfig.m.xFree(p);
20675   }
20676 }
20677
20678 /*
20679 ** Free memory that might be associated with a particular database
20680 ** connection.
20681 */
20682 SQLCIPHER_PRIVATE void sqlcipher3DbFree(sqlcipher3 *db, void *p){
20683   assert( db==0 || sqlcipher3_mutex_held(db->mutex) );
20684   if( db ){
20685     if( db->pnBytesFreed ){
20686       *db->pnBytesFreed += sqlcipher3DbMallocSize(db, p);
20687       return;
20688     }
20689     if( isLookaside(db, p) ){
20690       LookasideSlot *pBuf = (LookasideSlot*)p;
20691       pBuf->pNext = db->lookaside.pFree;
20692       db->lookaside.pFree = pBuf;
20693       db->lookaside.nOut--;
20694       return;
20695     }
20696   }
20697   assert( sqlcipher3MemdebugHasType(p, MEMTYPE_DB) );
20698   assert( sqlcipher3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
20699   assert( db!=0 || sqlcipher3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
20700   sqlcipher3MemdebugSetType(p, MEMTYPE_HEAP);
20701   sqlcipher3_free(p);
20702 }
20703
20704 /*
20705 ** Change the size of an existing memory allocation
20706 */
20707 SQLCIPHER_PRIVATE void *sqlcipher3Realloc(void *pOld, int nBytes){
20708   int nOld, nNew, nDiff;
20709   void *pNew;
20710   if( pOld==0 ){
20711     return sqlcipher3Malloc(nBytes); /* IMP: R-28354-25769 */
20712   }
20713   if( nBytes<=0 ){
20714     sqlcipher3_free(pOld); /* IMP: R-31593-10574 */
20715     return 0;
20716   }
20717   if( nBytes>=0x7fffff00 ){
20718     /* The 0x7ffff00 limit term is explained in comments on sqlcipher3Malloc() */
20719     return 0;
20720   }
20721   nOld = sqlcipher3MallocSize(pOld);
20722   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
20723   ** argument to xRealloc is always a value returned by a prior call to
20724   ** xRoundup. */
20725   nNew = sqlcipher3GlobalConfig.m.xRoundup(nBytes);
20726   if( nOld==nNew ){
20727     pNew = pOld;
20728   }else if( sqlcipher3GlobalConfig.bMemstat ){
20729     sqlcipher3_mutex_enter(mem0.mutex);
20730     sqlcipher3StatusSet(SQLCIPHER_STATUS_MALLOC_SIZE, nBytes);
20731     nDiff = nNew - nOld;
20732     if( sqlcipher3StatusValue(SQLCIPHER_STATUS_MEMORY_USED) >= 
20733           mem0.alarmThreshold-nDiff ){
20734       sqlcipher3MallocAlarm(nDiff);
20735     }
20736     assert( sqlcipher3MemdebugHasType(pOld, MEMTYPE_HEAP) );
20737     assert( sqlcipher3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
20738     pNew = sqlcipher3GlobalConfig.m.xRealloc(pOld, nNew);
20739     if( pNew==0 && mem0.alarmCallback ){
20740       sqlcipher3MallocAlarm(nBytes);
20741       pNew = sqlcipher3GlobalConfig.m.xRealloc(pOld, nNew);
20742     }
20743     if( pNew ){
20744       nNew = sqlcipher3MallocSize(pNew);
20745       sqlcipher3StatusAdd(SQLCIPHER_STATUS_MEMORY_USED, nNew-nOld);
20746     }
20747     sqlcipher3_mutex_leave(mem0.mutex);
20748   }else{
20749     pNew = sqlcipher3GlobalConfig.m.xRealloc(pOld, nNew);
20750   }
20751   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
20752   return pNew;
20753 }
20754
20755 /*
20756 ** The public interface to sqlcipher3Realloc.  Make sure that the memory
20757 ** subsystem is initialized prior to invoking sqlcipherRealloc.
20758 */
20759 SQLCIPHER_API void *sqlcipher3_realloc(void *pOld, int n){
20760 #ifndef SQLCIPHER_OMIT_AUTOINIT
20761   if( sqlcipher3_initialize() ) return 0;
20762 #endif
20763   return sqlcipher3Realloc(pOld, n);
20764 }
20765
20766
20767 /*
20768 ** Allocate and zero memory.
20769 */ 
20770 SQLCIPHER_PRIVATE void *sqlcipher3MallocZero(int n){
20771   void *p = sqlcipher3Malloc(n);
20772   if( p ){
20773     memset(p, 0, n);
20774   }
20775   return p;
20776 }
20777
20778 /*
20779 ** Allocate and zero memory.  If the allocation fails, make
20780 ** the mallocFailed flag in the connection pointer.
20781 */
20782 SQLCIPHER_PRIVATE void *sqlcipher3DbMallocZero(sqlcipher3 *db, int n){
20783   void *p = sqlcipher3DbMallocRaw(db, n);
20784   if( p ){
20785     memset(p, 0, n);
20786   }
20787   return p;
20788 }
20789
20790 /*
20791 ** Allocate and zero memory.  If the allocation fails, make
20792 ** the mallocFailed flag in the connection pointer.
20793 **
20794 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
20795 ** failure on the same database connection) then always return 0.
20796 ** Hence for a particular database connection, once malloc starts
20797 ** failing, it fails consistently until mallocFailed is reset.
20798 ** This is an important assumption.  There are many places in the
20799 ** code that do things like this:
20800 **
20801 **         int *a = (int*)sqlcipher3DbMallocRaw(db, 100);
20802 **         int *b = (int*)sqlcipher3DbMallocRaw(db, 200);
20803 **         if( b ) a[10] = 9;
20804 **
20805 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
20806 ** that all prior mallocs (ex: "a") worked too.
20807 */
20808 SQLCIPHER_PRIVATE void *sqlcipher3DbMallocRaw(sqlcipher3 *db, int n){
20809   void *p;
20810   assert( db==0 || sqlcipher3_mutex_held(db->mutex) );
20811   assert( db==0 || db->pnBytesFreed==0 );
20812 #ifndef SQLCIPHER_OMIT_LOOKASIDE
20813   if( db ){
20814     LookasideSlot *pBuf;
20815     if( db->mallocFailed ){
20816       return 0;
20817     }
20818     if( db->lookaside.bEnabled ){
20819       if( n>db->lookaside.sz ){
20820         db->lookaside.anStat[1]++;
20821       }else if( (pBuf = db->lookaside.pFree)==0 ){
20822         db->lookaside.anStat[2]++;
20823       }else{
20824         db->lookaside.pFree = pBuf->pNext;
20825         db->lookaside.nOut++;
20826         db->lookaside.anStat[0]++;
20827         if( db->lookaside.nOut>db->lookaside.mxOut ){
20828           db->lookaside.mxOut = db->lookaside.nOut;
20829         }
20830         return (void*)pBuf;
20831       }
20832     }
20833   }
20834 #else
20835   if( db && db->mallocFailed ){
20836     return 0;
20837   }
20838 #endif
20839   p = sqlcipher3Malloc(n);
20840   if( !p && db ){
20841     db->mallocFailed = 1;
20842   }
20843   sqlcipher3MemdebugSetType(p, MEMTYPE_DB |
20844          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
20845   return p;
20846 }
20847
20848 /*
20849 ** Resize the block of memory pointed to by p to n bytes. If the
20850 ** resize fails, set the mallocFailed flag in the connection object.
20851 */
20852 SQLCIPHER_PRIVATE void *sqlcipher3DbRealloc(sqlcipher3 *db, void *p, int n){
20853   void *pNew = 0;
20854   assert( db!=0 );
20855   assert( sqlcipher3_mutex_held(db->mutex) );
20856   if( db->mallocFailed==0 ){
20857     if( p==0 ){
20858       return sqlcipher3DbMallocRaw(db, n);
20859     }
20860     if( isLookaside(db, p) ){
20861       if( n<=db->lookaside.sz ){
20862         return p;
20863       }
20864       pNew = sqlcipher3DbMallocRaw(db, n);
20865       if( pNew ){
20866         memcpy(pNew, p, db->lookaside.sz);
20867         sqlcipher3DbFree(db, p);
20868       }
20869     }else{
20870       assert( sqlcipher3MemdebugHasType(p, MEMTYPE_DB) );
20871       assert( sqlcipher3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
20872       sqlcipher3MemdebugSetType(p, MEMTYPE_HEAP);
20873       pNew = sqlcipher3_realloc(p, n);
20874       if( !pNew ){
20875         sqlcipher3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
20876         db->mallocFailed = 1;
20877       }
20878       sqlcipher3MemdebugSetType(pNew, MEMTYPE_DB | 
20879             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
20880     }
20881   }
20882   return pNew;
20883 }
20884
20885 /*
20886 ** Attempt to reallocate p.  If the reallocation fails, then free p
20887 ** and set the mallocFailed flag in the database connection.
20888 */
20889 SQLCIPHER_PRIVATE void *sqlcipher3DbReallocOrFree(sqlcipher3 *db, void *p, int n){
20890   void *pNew;
20891   pNew = sqlcipher3DbRealloc(db, p, n);
20892   if( !pNew ){
20893     sqlcipher3DbFree(db, p);
20894   }
20895   return pNew;
20896 }
20897
20898 /*
20899 ** Make a copy of a string in memory obtained from sqlcipherMalloc(). These 
20900 ** functions call sqlcipher3MallocRaw() directly instead of sqlcipherMalloc(). This
20901 ** is because when memory debugging is turned on, these two functions are 
20902 ** called via macros that record the current file and line number in the
20903 ** ThreadData structure.
20904 */
20905 SQLCIPHER_PRIVATE char *sqlcipher3DbStrDup(sqlcipher3 *db, const char *z){
20906   char *zNew;
20907   size_t n;
20908   if( z==0 ){
20909     return 0;
20910   }
20911   n = sqlcipher3Strlen30(z) + 1;
20912   assert( (n&0x7fffffff)==n );
20913   zNew = sqlcipher3DbMallocRaw(db, (int)n);
20914   if( zNew ){
20915     memcpy(zNew, z, n);
20916   }
20917   return zNew;
20918 }
20919 SQLCIPHER_PRIVATE char *sqlcipher3DbStrNDup(sqlcipher3 *db, const char *z, int n){
20920   char *zNew;
20921   if( z==0 ){
20922     return 0;
20923   }
20924   assert( (n&0x7fffffff)==n );
20925   zNew = sqlcipher3DbMallocRaw(db, n+1);
20926   if( zNew ){
20927     memcpy(zNew, z, n);
20928     zNew[n] = 0;
20929   }
20930   return zNew;
20931 }
20932
20933 /*
20934 ** Create a string from the zFromat argument and the va_list that follows.
20935 ** Store the string in memory obtained from sqlcipherMalloc() and make *pz
20936 ** point to that string.
20937 */
20938 SQLCIPHER_PRIVATE void sqlcipher3SetString(char **pz, sqlcipher3 *db, const char *zFormat, ...){
20939   va_list ap;
20940   char *z;
20941
20942   va_start(ap, zFormat);
20943   z = sqlcipher3VMPrintf(db, zFormat, ap);
20944   va_end(ap);
20945   sqlcipher3DbFree(db, *pz);
20946   *pz = z;
20947 }
20948
20949
20950 /*
20951 ** This function must be called before exiting any API function (i.e. 
20952 ** returning control to the user) that has called sqlcipher3_malloc or
20953 ** sqlcipher3_realloc.
20954 **
20955 ** The returned value is normally a copy of the second argument to this
20956 ** function. However, if a malloc() failure has occurred since the previous
20957 ** invocation SQLCIPHER_NOMEM is returned instead. 
20958 **
20959 ** If the first argument, db, is not NULL and a malloc() error has occurred,
20960 ** then the connection error-code (the value returned by sqlcipher3_errcode())
20961 ** is set to SQLCIPHER_NOMEM.
20962 */
20963 SQLCIPHER_PRIVATE int sqlcipher3ApiExit(sqlcipher3* db, int rc){
20964   /* If the db handle is not NULL, then we must hold the connection handle
20965   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
20966   ** is unsafe, as is the call to sqlcipher3Error().
20967   */
20968   assert( !db || sqlcipher3_mutex_held(db->mutex) );
20969   if( db && (db->mallocFailed || rc==SQLCIPHER_IOERR_NOMEM) ){
20970     sqlcipher3Error(db, SQLCIPHER_NOMEM, 0);
20971     db->mallocFailed = 0;
20972     rc = SQLCIPHER_NOMEM;
20973   }
20974   return rc & (db ? db->errMask : 0xff);
20975 }
20976
20977 /************** End of malloc.c **********************************************/
20978 /************** Begin file printf.c ******************************************/
20979 /*
20980 ** The "printf" code that follows dates from the 1980's.  It is in
20981 ** the public domain.  The original comments are included here for
20982 ** completeness.  They are very out-of-date but might be useful as
20983 ** an historical reference.  Most of the "enhancements" have been backed
20984 ** out so that the functionality is now the same as standard printf().
20985 **
20986 **************************************************************************
20987 **
20988 ** This file contains code for a set of "printf"-like routines.  These
20989 ** routines format strings much like the printf() from the standard C
20990 ** library, though the implementation here has enhancements to support
20991 ** SQLlite.
20992 */
20993
20994 /*
20995 ** Conversion types fall into various categories as defined by the
20996 ** following enumeration.
20997 */
20998 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
20999 #define etFLOAT       2 /* Floating point.  %f */
21000 #define etEXP         3 /* Exponentional notation. %e and %E */
21001 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
21002 #define etSIZE        5 /* Return number of characters processed so far. %n */
21003 #define etSTRING      6 /* Strings. %s */
21004 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
21005 #define etPERCENT     8 /* Percent symbol. %% */
21006 #define etCHARX       9 /* Characters. %c */
21007 /* The rest are extensions, not normally found in printf() */
21008 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
21009 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
21010                           NULL pointers replaced by SQL NULL.  %Q */
21011 #define etTOKEN      12 /* a pointer to a Token structure */
21012 #define etSRCLIST    13 /* a pointer to a SrcList */
21013 #define etPOINTER    14 /* The %p conversion */
21014 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
21015 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
21016
21017 #define etINVALID     0 /* Any unrecognized conversion type */
21018
21019
21020 /*
21021 ** An "etByte" is an 8-bit unsigned value.
21022 */
21023 typedef unsigned char etByte;
21024
21025 /*
21026 ** Each builtin conversion character (ex: the 'd' in "%d") is described
21027 ** by an instance of the following structure
21028 */
21029 typedef struct et_info {   /* Information about each format field */
21030   char fmttype;            /* The format field code letter */
21031   etByte base;             /* The base for radix conversion */
21032   etByte flags;            /* One or more of FLAG_ constants below */
21033   etByte type;             /* Conversion paradigm */
21034   etByte charset;          /* Offset into aDigits[] of the digits string */
21035   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
21036 } et_info;
21037
21038 /*
21039 ** Allowed values for et_info.flags
21040 */
21041 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
21042 #define FLAG_INTERN  2     /* True if for internal use only */
21043 #define FLAG_STRING  4     /* Allow infinity precision */
21044
21045
21046 /*
21047 ** The following table is searched linearly, so it is good to put the
21048 ** most frequently used conversion types first.
21049 */
21050 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
21051 static const char aPrefix[] = "-x0\000X0";
21052 static const et_info fmtinfo[] = {
21053   {  'd', 10, 1, etRADIX,      0,  0 },
21054   {  's',  0, 4, etSTRING,     0,  0 },
21055   {  'g',  0, 1, etGENERIC,    30, 0 },
21056   {  'z',  0, 4, etDYNSTRING,  0,  0 },
21057   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
21058   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
21059   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
21060   {  'c',  0, 0, etCHARX,      0,  0 },
21061   {  'o',  8, 0, etRADIX,      0,  2 },
21062   {  'u', 10, 0, etRADIX,      0,  0 },
21063   {  'x', 16, 0, etRADIX,      16, 1 },
21064   {  'X', 16, 0, etRADIX,      0,  4 },
21065 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
21066   {  'f',  0, 1, etFLOAT,      0,  0 },
21067   {  'e',  0, 1, etEXP,        30, 0 },
21068   {  'E',  0, 1, etEXP,        14, 0 },
21069   {  'G',  0, 1, etGENERIC,    14, 0 },
21070 #endif
21071   {  'i', 10, 1, etRADIX,      0,  0 },
21072   {  'n',  0, 0, etSIZE,       0,  0 },
21073   {  '%',  0, 0, etPERCENT,    0,  0 },
21074   {  'p', 16, 0, etPOINTER,    0,  1 },
21075
21076 /* All the rest have the FLAG_INTERN bit set and are thus for internal
21077 ** use only */
21078   {  'T',  0, 2, etTOKEN,      0,  0 },
21079   {  'S',  0, 2, etSRCLIST,    0,  0 },
21080   {  'r', 10, 3, etORDINAL,    0,  0 },
21081 };
21082
21083 /*
21084 ** If SQLCIPHER_OMIT_FLOATING_POINT is defined, then none of the floating point
21085 ** conversions will work.
21086 */
21087 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
21088 /*
21089 ** "*val" is a double such that 0.1 <= *val < 10.0
21090 ** Return the ascii code for the leading digit of *val, then
21091 ** multiply "*val" by 10.0 to renormalize.
21092 **
21093 ** Example:
21094 **     input:     *val = 3.14159
21095 **     output:    *val = 1.4159    function return = '3'
21096 **
21097 ** The counter *cnt is incremented each time.  After counter exceeds
21098 ** 16 (the number of significant digits in a 64-bit float) '0' is
21099 ** always returned.
21100 */
21101 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
21102   int digit;
21103   LONGDOUBLE_TYPE d;
21104   if( (*cnt)++ >= 16 ) return '0';
21105   digit = (int)*val;
21106   d = digit;
21107   digit += '0';
21108   *val = (*val - d)*10.0;
21109   return (char)digit;
21110 }
21111 #endif /* SQLCIPHER_OMIT_FLOATING_POINT */
21112
21113 /*
21114 ** Append N space characters to the given string buffer.
21115 */
21116 static void appendSpace(StrAccum *pAccum, int N){
21117   static const char zSpaces[] = "                             ";
21118   while( N>=(int)sizeof(zSpaces)-1 ){
21119     sqlcipher3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
21120     N -= sizeof(zSpaces)-1;
21121   }
21122   if( N>0 ){
21123     sqlcipher3StrAccumAppend(pAccum, zSpaces, N);
21124   }
21125 }
21126
21127 /*
21128 ** On machines with a small stack size, you can redefine the
21129 ** SQLCIPHER_PRINT_BUF_SIZE to be something smaller, if desired.
21130 */
21131 #ifndef SQLCIPHER_PRINT_BUF_SIZE
21132 # define SQLCIPHER_PRINT_BUF_SIZE 70
21133 #endif
21134 #define etBUFSIZE SQLCIPHER_PRINT_BUF_SIZE  /* Size of the output buffer */
21135
21136 /*
21137 ** Render a string given by "fmt" into the StrAccum object.
21138 */
21139 SQLCIPHER_PRIVATE void sqlcipher3VXPrintf(
21140   StrAccum *pAccum,                  /* Accumulate results here */
21141   int useExtended,                   /* Allow extended %-conversions */
21142   const char *fmt,                   /* Format string */
21143   va_list ap                         /* arguments */
21144 ){
21145   int c;                     /* Next character in the format string */
21146   char *bufpt;               /* Pointer to the conversion buffer */
21147   int precision;             /* Precision of the current field */
21148   int length;                /* Length of the field */
21149   int idx;                   /* A general purpose loop counter */
21150   int width;                 /* Width of the current field */
21151   etByte flag_leftjustify;   /* True if "-" flag is present */
21152   etByte flag_plussign;      /* True if "+" flag is present */
21153   etByte flag_blanksign;     /* True if " " flag is present */
21154   etByte flag_alternateform; /* True if "#" flag is present */
21155   etByte flag_altform2;      /* True if "!" flag is present */
21156   etByte flag_zeropad;       /* True if field width constant starts with zero */
21157   etByte flag_long;          /* True if "l" flag is present */
21158   etByte flag_longlong;      /* True if the "ll" flag is present */
21159   etByte done;               /* Loop termination flag */
21160   etByte xtype = 0;          /* Conversion paradigm */
21161   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
21162   sqlcipher_uint64 longvalue;   /* Value for integer types */
21163   LONGDOUBLE_TYPE realvalue; /* Value for real types */
21164   const et_info *infop;      /* Pointer to the appropriate info structure */
21165   char *zOut;                /* Rendering buffer */
21166   int nOut;                  /* Size of the rendering buffer */
21167   char *zExtra;              /* Malloced memory used by some conversion */
21168 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
21169   int  exp, e2;              /* exponent of real numbers */
21170   int nsd;                   /* Number of significant digits returned */
21171   double rounder;            /* Used for rounding floating point values */
21172   etByte flag_dp;            /* True if decimal point should be shown */
21173   etByte flag_rtz;           /* True if trailing zeros should be removed */
21174 #endif
21175   char buf[etBUFSIZE];       /* Conversion buffer */
21176
21177   bufpt = 0;
21178   for(; (c=(*fmt))!=0; ++fmt){
21179     if( c!='%' ){
21180       int amt;
21181       bufpt = (char *)fmt;
21182       amt = 1;
21183       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
21184       sqlcipher3StrAccumAppend(pAccum, bufpt, amt);
21185       if( c==0 ) break;
21186     }
21187     if( (c=(*++fmt))==0 ){
21188       sqlcipher3StrAccumAppend(pAccum, "%", 1);
21189       break;
21190     }
21191     /* Find out what flags are present */
21192     flag_leftjustify = flag_plussign = flag_blanksign = 
21193      flag_alternateform = flag_altform2 = flag_zeropad = 0;
21194     done = 0;
21195     do{
21196       switch( c ){
21197         case '-':   flag_leftjustify = 1;     break;
21198         case '+':   flag_plussign = 1;        break;
21199         case ' ':   flag_blanksign = 1;       break;
21200         case '#':   flag_alternateform = 1;   break;
21201         case '!':   flag_altform2 = 1;        break;
21202         case '0':   flag_zeropad = 1;         break;
21203         default:    done = 1;                 break;
21204       }
21205     }while( !done && (c=(*++fmt))!=0 );
21206     /* Get the field width */
21207     width = 0;
21208     if( c=='*' ){
21209       width = va_arg(ap,int);
21210       if( width<0 ){
21211         flag_leftjustify = 1;
21212         width = -width;
21213       }
21214       c = *++fmt;
21215     }else{
21216       while( c>='0' && c<='9' ){
21217         width = width*10 + c - '0';
21218         c = *++fmt;
21219       }
21220     }
21221     /* Get the precision */
21222     if( c=='.' ){
21223       precision = 0;
21224       c = *++fmt;
21225       if( c=='*' ){
21226         precision = va_arg(ap,int);
21227         if( precision<0 ) precision = -precision;
21228         c = *++fmt;
21229       }else{
21230         while( c>='0' && c<='9' ){
21231           precision = precision*10 + c - '0';
21232           c = *++fmt;
21233         }
21234       }
21235     }else{
21236       precision = -1;
21237     }
21238     /* Get the conversion type modifier */
21239     if( c=='l' ){
21240       flag_long = 1;
21241       c = *++fmt;
21242       if( c=='l' ){
21243         flag_longlong = 1;
21244         c = *++fmt;
21245       }else{
21246         flag_longlong = 0;
21247       }
21248     }else{
21249       flag_long = flag_longlong = 0;
21250     }
21251     /* Fetch the info entry for the field */
21252     infop = &fmtinfo[0];
21253     xtype = etINVALID;
21254     for(idx=0; idx<ArraySize(fmtinfo); idx++){
21255       if( c==fmtinfo[idx].fmttype ){
21256         infop = &fmtinfo[idx];
21257         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
21258           xtype = infop->type;
21259         }else{
21260           return;
21261         }
21262         break;
21263       }
21264     }
21265     zExtra = 0;
21266
21267     /*
21268     ** At this point, variables are initialized as follows:
21269     **
21270     **   flag_alternateform          TRUE if a '#' is present.
21271     **   flag_altform2               TRUE if a '!' is present.
21272     **   flag_plussign               TRUE if a '+' is present.
21273     **   flag_leftjustify            TRUE if a '-' is present or if the
21274     **                               field width was negative.
21275     **   flag_zeropad                TRUE if the width began with 0.
21276     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
21277     **                               the conversion character.
21278     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
21279     **                               the conversion character.
21280     **   flag_blanksign              TRUE if a ' ' is present.
21281     **   width                       The specified field width.  This is
21282     **                               always non-negative.  Zero is the default.
21283     **   precision                   The specified precision.  The default
21284     **                               is -1.
21285     **   xtype                       The class of the conversion.
21286     **   infop                       Pointer to the appropriate info struct.
21287     */
21288     switch( xtype ){
21289       case etPOINTER:
21290         flag_longlong = sizeof(char*)==sizeof(i64);
21291         flag_long = sizeof(char*)==sizeof(long int);
21292         /* Fall through into the next case */
21293       case etORDINAL:
21294       case etRADIX:
21295         if( infop->flags & FLAG_SIGNED ){
21296           i64 v;
21297           if( flag_longlong ){
21298             v = va_arg(ap,i64);
21299           }else if( flag_long ){
21300             v = va_arg(ap,long int);
21301           }else{
21302             v = va_arg(ap,int);
21303           }
21304           if( v<0 ){
21305             if( v==SMALLEST_INT64 ){
21306               longvalue = ((u64)1)<<63;
21307             }else{
21308               longvalue = -v;
21309             }
21310             prefix = '-';
21311           }else{
21312             longvalue = v;
21313             if( flag_plussign )        prefix = '+';
21314             else if( flag_blanksign )  prefix = ' ';
21315             else                       prefix = 0;
21316           }
21317         }else{
21318           if( flag_longlong ){
21319             longvalue = va_arg(ap,u64);
21320           }else if( flag_long ){
21321             longvalue = va_arg(ap,unsigned long int);
21322           }else{
21323             longvalue = va_arg(ap,unsigned int);
21324           }
21325           prefix = 0;
21326         }
21327         if( longvalue==0 ) flag_alternateform = 0;
21328         if( flag_zeropad && precision<width-(prefix!=0) ){
21329           precision = width-(prefix!=0);
21330         }
21331         if( precision<etBUFSIZE-10 ){
21332           nOut = etBUFSIZE;
21333           zOut = buf;
21334         }else{
21335           nOut = precision + 10;
21336           zOut = zExtra = sqlcipher3Malloc( nOut );
21337           if( zOut==0 ){
21338             pAccum->mallocFailed = 1;
21339             return;
21340           }
21341         }
21342         bufpt = &zOut[nOut-1];
21343         if( xtype==etORDINAL ){
21344           static const char zOrd[] = "thstndrd";
21345           int x = (int)(longvalue % 10);
21346           if( x>=4 || (longvalue/10)%10==1 ){
21347             x = 0;
21348           }
21349           *(--bufpt) = zOrd[x*2+1];
21350           *(--bufpt) = zOrd[x*2];
21351         }
21352         {
21353           register const char *cset;      /* Use registers for speed */
21354           register int base;
21355           cset = &aDigits[infop->charset];
21356           base = infop->base;
21357           do{                                           /* Convert to ascii */
21358             *(--bufpt) = cset[longvalue%base];
21359             longvalue = longvalue/base;
21360           }while( longvalue>0 );
21361         }
21362         length = (int)(&zOut[nOut-1]-bufpt);
21363         for(idx=precision-length; idx>0; idx--){
21364           *(--bufpt) = '0';                             /* Zero pad */
21365         }
21366         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
21367         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
21368           const char *pre;
21369           char x;
21370           pre = &aPrefix[infop->prefix];
21371           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
21372         }
21373         length = (int)(&zOut[nOut-1]-bufpt);
21374         break;
21375       case etFLOAT:
21376       case etEXP:
21377       case etGENERIC:
21378         realvalue = va_arg(ap,double);
21379 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
21380         length = 0;
21381 #else
21382         if( precision<0 ) precision = 6;         /* Set default precision */
21383         if( realvalue<0.0 ){
21384           realvalue = -realvalue;
21385           prefix = '-';
21386         }else{
21387           if( flag_plussign )          prefix = '+';
21388           else if( flag_blanksign )    prefix = ' ';
21389           else                         prefix = 0;
21390         }
21391         if( xtype==etGENERIC && precision>0 ) precision--;
21392 #if 0
21393         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
21394         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
21395 #else
21396         /* It makes more sense to use 0.5 */
21397         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
21398 #endif
21399         if( xtype==etFLOAT ) realvalue += rounder;
21400         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
21401         exp = 0;
21402         if( sqlcipher3IsNaN((double)realvalue) ){
21403           bufpt = "NaN";
21404           length = 3;
21405           break;
21406         }
21407         if( realvalue>0.0 ){
21408           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
21409           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
21410           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
21411           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
21412           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
21413           if( exp>350 ){
21414             if( prefix=='-' ){
21415               bufpt = "-Inf";
21416             }else if( prefix=='+' ){
21417               bufpt = "+Inf";
21418             }else{
21419               bufpt = "Inf";
21420             }
21421             length = sqlcipher3Strlen30(bufpt);
21422             break;
21423           }
21424         }
21425         bufpt = buf;
21426         /*
21427         ** If the field type is etGENERIC, then convert to either etEXP
21428         ** or etFLOAT, as appropriate.
21429         */
21430         if( xtype!=etFLOAT ){
21431           realvalue += rounder;
21432           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
21433         }
21434         if( xtype==etGENERIC ){
21435           flag_rtz = !flag_alternateform;
21436           if( exp<-4 || exp>precision ){
21437             xtype = etEXP;
21438           }else{
21439             precision = precision - exp;
21440             xtype = etFLOAT;
21441           }
21442         }else{
21443           flag_rtz = 0;
21444         }
21445         if( xtype==etEXP ){
21446           e2 = 0;
21447         }else{
21448           e2 = exp;
21449         }
21450         if( e2+precision+width > etBUFSIZE - 15 ){
21451           bufpt = zExtra = sqlcipher3Malloc( e2+precision+width+15 );
21452           if( bufpt==0 ){
21453             pAccum->mallocFailed = 1;
21454             return;
21455           }
21456         }
21457         zOut = bufpt;
21458         nsd = 0;
21459         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
21460         /* The sign in front of the number */
21461         if( prefix ){
21462           *(bufpt++) = prefix;
21463         }
21464         /* Digits prior to the decimal point */
21465         if( e2<0 ){
21466           *(bufpt++) = '0';
21467         }else{
21468           for(; e2>=0; e2--){
21469             *(bufpt++) = et_getdigit(&realvalue,&nsd);
21470           }
21471         }
21472         /* The decimal point */
21473         if( flag_dp ){
21474           *(bufpt++) = '.';
21475         }
21476         /* "0" digits after the decimal point but before the first
21477         ** significant digit of the number */
21478         for(e2++; e2<0; precision--, e2++){
21479           assert( precision>0 );
21480           *(bufpt++) = '0';
21481         }
21482         /* Significant digits after the decimal point */
21483         while( (precision--)>0 ){
21484           *(bufpt++) = et_getdigit(&realvalue,&nsd);
21485         }
21486         /* Remove trailing zeros and the "." if no digits follow the "." */
21487         if( flag_rtz && flag_dp ){
21488           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
21489           assert( bufpt>zOut );
21490           if( bufpt[-1]=='.' ){
21491             if( flag_altform2 ){
21492               *(bufpt++) = '0';
21493             }else{
21494               *(--bufpt) = 0;
21495             }
21496           }
21497         }
21498         /* Add the "eNNN" suffix */
21499         if( xtype==etEXP ){
21500           *(bufpt++) = aDigits[infop->charset];
21501           if( exp<0 ){
21502             *(bufpt++) = '-'; exp = -exp;
21503           }else{
21504             *(bufpt++) = '+';
21505           }
21506           if( exp>=100 ){
21507             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
21508             exp %= 100;
21509           }
21510           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
21511           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
21512         }
21513         *bufpt = 0;
21514
21515         /* The converted number is in buf[] and zero terminated. Output it.
21516         ** Note that the number is in the usual order, not reversed as with
21517         ** integer conversions. */
21518         length = (int)(bufpt-zOut);
21519         bufpt = zOut;
21520
21521         /* Special case:  Add leading zeros if the flag_zeropad flag is
21522         ** set and we are not left justified */
21523         if( flag_zeropad && !flag_leftjustify && length < width){
21524           int i;
21525           int nPad = width - length;
21526           for(i=width; i>=nPad; i--){
21527             bufpt[i] = bufpt[i-nPad];
21528           }
21529           i = prefix!=0;
21530           while( nPad-- ) bufpt[i++] = '0';
21531           length = width;
21532         }
21533 #endif /* !defined(SQLCIPHER_OMIT_FLOATING_POINT) */
21534         break;
21535       case etSIZE:
21536         *(va_arg(ap,int*)) = pAccum->nChar;
21537         length = width = 0;
21538         break;
21539       case etPERCENT:
21540         buf[0] = '%';
21541         bufpt = buf;
21542         length = 1;
21543         break;
21544       case etCHARX:
21545         c = va_arg(ap,int);
21546         buf[0] = (char)c;
21547         if( precision>=0 ){
21548           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
21549           length = precision;
21550         }else{
21551           length =1;
21552         }
21553         bufpt = buf;
21554         break;
21555       case etSTRING:
21556       case etDYNSTRING:
21557         bufpt = va_arg(ap,char*);
21558         if( bufpt==0 ){
21559           bufpt = "";
21560         }else if( xtype==etDYNSTRING ){
21561           zExtra = bufpt;
21562         }
21563         if( precision>=0 ){
21564           for(length=0; length<precision && bufpt[length]; length++){}
21565         }else{
21566           length = sqlcipher3Strlen30(bufpt);
21567         }
21568         break;
21569       case etSQLESCAPE:
21570       case etSQLESCAPE2:
21571       case etSQLESCAPE3: {
21572         int i, j, k, n, isnull;
21573         int needQuote;
21574         char ch;
21575         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
21576         char *escarg = va_arg(ap,char*);
21577         isnull = escarg==0;
21578         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
21579         k = precision;
21580         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
21581           if( ch==q )  n++;
21582         }
21583         needQuote = !isnull && xtype==etSQLESCAPE2;
21584         n += i + 1 + needQuote*2;
21585         if( n>etBUFSIZE ){
21586           bufpt = zExtra = sqlcipher3Malloc( n );
21587           if( bufpt==0 ){
21588             pAccum->mallocFailed = 1;
21589             return;
21590           }
21591         }else{
21592           bufpt = buf;
21593         }
21594         j = 0;
21595         if( needQuote ) bufpt[j++] = q;
21596         k = i;
21597         for(i=0; i<k; i++){
21598           bufpt[j++] = ch = escarg[i];
21599           if( ch==q ) bufpt[j++] = ch;
21600         }
21601         if( needQuote ) bufpt[j++] = q;
21602         bufpt[j] = 0;
21603         length = j;
21604         /* The precision in %q and %Q means how many input characters to
21605         ** consume, not the length of the output...
21606         ** if( precision>=0 && precision<length ) length = precision; */
21607         break;
21608       }
21609       case etTOKEN: {
21610         Token *pToken = va_arg(ap, Token*);
21611         if( pToken ){
21612           sqlcipher3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
21613         }
21614         length = width = 0;
21615         break;
21616       }
21617       case etSRCLIST: {
21618         SrcList *pSrc = va_arg(ap, SrcList*);
21619         int k = va_arg(ap, int);
21620         struct SrcList_item *pItem = &pSrc->a[k];
21621         assert( k>=0 && k<pSrc->nSrc );
21622         if( pItem->zDatabase ){
21623           sqlcipher3StrAccumAppend(pAccum, pItem->zDatabase, -1);
21624           sqlcipher3StrAccumAppend(pAccum, ".", 1);
21625         }
21626         sqlcipher3StrAccumAppend(pAccum, pItem->zName, -1);
21627         length = width = 0;
21628         break;
21629       }
21630       default: {
21631         assert( xtype==etINVALID );
21632         return;
21633       }
21634     }/* End switch over the format type */
21635     /*
21636     ** The text of the conversion is pointed to by "bufpt" and is
21637     ** "length" characters long.  The field width is "width".  Do
21638     ** the output.
21639     */
21640     if( !flag_leftjustify ){
21641       register int nspace;
21642       nspace = width-length;
21643       if( nspace>0 ){
21644         appendSpace(pAccum, nspace);
21645       }
21646     }
21647     if( length>0 ){
21648       sqlcipher3StrAccumAppend(pAccum, bufpt, length);
21649     }
21650     if( flag_leftjustify ){
21651       register int nspace;
21652       nspace = width-length;
21653       if( nspace>0 ){
21654         appendSpace(pAccum, nspace);
21655       }
21656     }
21657     sqlcipher3_free(zExtra);
21658   }/* End for loop over the format string */
21659 } /* End of function */
21660
21661 /*
21662 ** Append N bytes of text from z to the StrAccum object.
21663 */
21664 SQLCIPHER_PRIVATE void sqlcipher3StrAccumAppend(StrAccum *p, const char *z, int N){
21665   assert( z!=0 || N==0 );
21666   if( p->tooBig | p->mallocFailed ){
21667     testcase(p->tooBig);
21668     testcase(p->mallocFailed);
21669     return;
21670   }
21671   assert( p->zText!=0 || p->nChar==0 );
21672   if( N<0 ){
21673     N = sqlcipher3Strlen30(z);
21674   }
21675   if( N==0 || NEVER(z==0) ){
21676     return;
21677   }
21678   if( p->nChar+N >= p->nAlloc ){
21679     char *zNew;
21680     if( !p->useMalloc ){
21681       p->tooBig = 1;
21682       N = p->nAlloc - p->nChar - 1;
21683       if( N<=0 ){
21684         return;
21685       }
21686     }else{
21687       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
21688       i64 szNew = p->nChar;
21689       szNew += N + 1;
21690       if( szNew > p->mxAlloc ){
21691         sqlcipher3StrAccumReset(p);
21692         p->tooBig = 1;
21693         return;
21694       }else{
21695         p->nAlloc = (int)szNew;
21696       }
21697       if( p->useMalloc==1 ){
21698         zNew = sqlcipher3DbRealloc(p->db, zOld, p->nAlloc);
21699       }else{
21700         zNew = sqlcipher3_realloc(zOld, p->nAlloc);
21701       }
21702       if( zNew ){
21703         if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
21704         p->zText = zNew;
21705       }else{
21706         p->mallocFailed = 1;
21707         sqlcipher3StrAccumReset(p);
21708         return;
21709       }
21710     }
21711   }
21712   assert( p->zText );
21713   memcpy(&p->zText[p->nChar], z, N);
21714   p->nChar += N;
21715 }
21716
21717 /*
21718 ** Finish off a string by making sure it is zero-terminated.
21719 ** Return a pointer to the resulting string.  Return a NULL
21720 ** pointer if any kind of error was encountered.
21721 */
21722 SQLCIPHER_PRIVATE char *sqlcipher3StrAccumFinish(StrAccum *p){
21723   if( p->zText ){
21724     p->zText[p->nChar] = 0;
21725     if( p->useMalloc && p->zText==p->zBase ){
21726       if( p->useMalloc==1 ){
21727         p->zText = sqlcipher3DbMallocRaw(p->db, p->nChar+1 );
21728       }else{
21729         p->zText = sqlcipher3_malloc(p->nChar+1);
21730       }
21731       if( p->zText ){
21732         memcpy(p->zText, p->zBase, p->nChar+1);
21733       }else{
21734         p->mallocFailed = 1;
21735       }
21736     }
21737   }
21738   return p->zText;
21739 }
21740
21741 /*
21742 ** Reset an StrAccum string.  Reclaim all malloced memory.
21743 */
21744 SQLCIPHER_PRIVATE void sqlcipher3StrAccumReset(StrAccum *p){
21745   if( p->zText!=p->zBase ){
21746     if( p->useMalloc==1 ){
21747       sqlcipher3DbFree(p->db, p->zText);
21748     }else{
21749       sqlcipher3_free(p->zText);
21750     }
21751   }
21752   p->zText = 0;
21753 }
21754
21755 /*
21756 ** Initialize a string accumulator
21757 */
21758 SQLCIPHER_PRIVATE void sqlcipher3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
21759   p->zText = p->zBase = zBase;
21760   p->db = 0;
21761   p->nChar = 0;
21762   p->nAlloc = n;
21763   p->mxAlloc = mx;
21764   p->useMalloc = 1;
21765   p->tooBig = 0;
21766   p->mallocFailed = 0;
21767 }
21768
21769 /*
21770 ** Print into memory obtained from sqlcipherMalloc().  Use the internal
21771 ** %-conversion extensions.
21772 */
21773 SQLCIPHER_PRIVATE char *sqlcipher3VMPrintf(sqlcipher3 *db, const char *zFormat, va_list ap){
21774   char *z;
21775   char zBase[SQLCIPHER_PRINT_BUF_SIZE];
21776   StrAccum acc;
21777   assert( db!=0 );
21778   sqlcipher3StrAccumInit(&acc, zBase, sizeof(zBase),
21779                       db->aLimit[SQLCIPHER_LIMIT_LENGTH]);
21780   acc.db = db;
21781   sqlcipher3VXPrintf(&acc, 1, zFormat, ap);
21782   z = sqlcipher3StrAccumFinish(&acc);
21783   if( acc.mallocFailed ){
21784     db->mallocFailed = 1;
21785   }
21786   return z;
21787 }
21788
21789 /*
21790 ** Print into memory obtained from sqlcipherMalloc().  Use the internal
21791 ** %-conversion extensions.
21792 */
21793 SQLCIPHER_PRIVATE char *sqlcipher3MPrintf(sqlcipher3 *db, const char *zFormat, ...){
21794   va_list ap;
21795   char *z;
21796   va_start(ap, zFormat);
21797   z = sqlcipher3VMPrintf(db, zFormat, ap);
21798   va_end(ap);
21799   return z;
21800 }
21801
21802 /*
21803 ** Like sqlcipher3MPrintf(), but call sqlcipher3DbFree() on zStr after formatting
21804 ** the string and before returnning.  This routine is intended to be used
21805 ** to modify an existing string.  For example:
21806 **
21807 **       x = sqlcipher3MPrintf(db, x, "prefix %s suffix", x);
21808 **
21809 */
21810 SQLCIPHER_PRIVATE char *sqlcipher3MAppendf(sqlcipher3 *db, char *zStr, const char *zFormat, ...){
21811   va_list ap;
21812   char *z;
21813   va_start(ap, zFormat);
21814   z = sqlcipher3VMPrintf(db, zFormat, ap);
21815   va_end(ap);
21816   sqlcipher3DbFree(db, zStr);
21817   return z;
21818 }
21819
21820 /*
21821 ** Print into memory obtained from sqlcipher3_malloc().  Omit the internal
21822 ** %-conversion extensions.
21823 */
21824 SQLCIPHER_API char *sqlcipher3_vmprintf(const char *zFormat, va_list ap){
21825   char *z;
21826   char zBase[SQLCIPHER_PRINT_BUF_SIZE];
21827   StrAccum acc;
21828 #ifndef SQLCIPHER_OMIT_AUTOINIT
21829   if( sqlcipher3_initialize() ) return 0;
21830 #endif
21831   sqlcipher3StrAccumInit(&acc, zBase, sizeof(zBase), SQLCIPHER_MAX_LENGTH);
21832   acc.useMalloc = 2;
21833   sqlcipher3VXPrintf(&acc, 0, zFormat, ap);
21834   z = sqlcipher3StrAccumFinish(&acc);
21835   return z;
21836 }
21837
21838 /*
21839 ** Print into memory obtained from sqlcipher3_malloc()().  Omit the internal
21840 ** %-conversion extensions.
21841 */
21842 SQLCIPHER_API char *sqlcipher3_mprintf(const char *zFormat, ...){
21843   va_list ap;
21844   char *z;
21845 #ifndef SQLCIPHER_OMIT_AUTOINIT
21846   if( sqlcipher3_initialize() ) return 0;
21847 #endif
21848   va_start(ap, zFormat);
21849   z = sqlcipher3_vmprintf(zFormat, ap);
21850   va_end(ap);
21851   return z;
21852 }
21853
21854 /*
21855 ** sqlcipher3_snprintf() works like snprintf() except that it ignores the
21856 ** current locale settings.  This is important for SQLite because we
21857 ** are not able to use a "," as the decimal point in place of "." as
21858 ** specified by some locales.
21859 **
21860 ** Oops:  The first two arguments of sqlcipher3_snprintf() are backwards
21861 ** from the snprintf() standard.  Unfortunately, it is too late to change
21862 ** this without breaking compatibility, so we just have to live with the
21863 ** mistake.
21864 **
21865 ** sqlcipher3_vsnprintf() is the varargs version.
21866 */
21867 SQLCIPHER_API char *sqlcipher3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
21868   StrAccum acc;
21869   if( n<=0 ) return zBuf;
21870   sqlcipher3StrAccumInit(&acc, zBuf, n, 0);
21871   acc.useMalloc = 0;
21872   sqlcipher3VXPrintf(&acc, 0, zFormat, ap);
21873   return sqlcipher3StrAccumFinish(&acc);
21874 }
21875 SQLCIPHER_API char *sqlcipher3_snprintf(int n, char *zBuf, const char *zFormat, ...){
21876   char *z;
21877   va_list ap;
21878   va_start(ap,zFormat);
21879   z = sqlcipher3_vsnprintf(n, zBuf, zFormat, ap);
21880   va_end(ap);
21881   return z;
21882 }
21883
21884 /*
21885 ** This is the routine that actually formats the sqlcipher3_log() message.
21886 ** We house it in a separate routine from sqlcipher3_log() to avoid using
21887 ** stack space on small-stack systems when logging is disabled.
21888 **
21889 ** sqlcipher3_log() must render into a static buffer.  It cannot dynamically
21890 ** allocate memory because it might be called while the memory allocator
21891 ** mutex is held.
21892 */
21893 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
21894   StrAccum acc;                          /* String accumulator */
21895   char zMsg[SQLCIPHER_PRINT_BUF_SIZE*3];    /* Complete log message */
21896
21897   sqlcipher3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
21898   acc.useMalloc = 0;
21899   sqlcipher3VXPrintf(&acc, 0, zFormat, ap);
21900   sqlcipher3GlobalConfig.xLog(sqlcipher3GlobalConfig.pLogArg, iErrCode,
21901                            sqlcipher3StrAccumFinish(&acc));
21902 }
21903
21904 /*
21905 ** Format and write a message to the log if logging is enabled.
21906 */
21907 SQLCIPHER_API void sqlcipher3_log(int iErrCode, const char *zFormat, ...){
21908   va_list ap;                             /* Vararg list */
21909   if( sqlcipher3GlobalConfig.xLog ){
21910     va_start(ap, zFormat);
21911     renderLogMsg(iErrCode, zFormat, ap);
21912     va_end(ap);
21913   }
21914 }
21915
21916 #if defined(SQLCIPHER_DEBUG)
21917 /*
21918 ** A version of printf() that understands %lld.  Used for debugging.
21919 ** The printf() built into some versions of windows does not understand %lld
21920 ** and segfaults if you give it a long long int.
21921 */
21922 SQLCIPHER_PRIVATE void sqlcipher3DebugPrintf(const char *zFormat, ...){
21923   va_list ap;
21924   StrAccum acc;
21925   char zBuf[500];
21926   sqlcipher3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
21927   acc.useMalloc = 0;
21928   va_start(ap,zFormat);
21929   sqlcipher3VXPrintf(&acc, 0, zFormat, ap);
21930   va_end(ap);
21931   sqlcipher3StrAccumFinish(&acc);
21932   fprintf(stdout,"%s", zBuf);
21933   fflush(stdout);
21934 }
21935 #endif
21936
21937 #ifndef SQLCIPHER_OMIT_TRACE
21938 /*
21939 ** variable-argument wrapper around sqlcipher3VXPrintf().
21940 */
21941 SQLCIPHER_PRIVATE void sqlcipher3XPrintf(StrAccum *p, const char *zFormat, ...){
21942   va_list ap;
21943   va_start(ap,zFormat);
21944   sqlcipher3VXPrintf(p, 1, zFormat, ap);
21945   va_end(ap);
21946 }
21947 #endif
21948
21949 /************** End of printf.c **********************************************/
21950 /************** Begin file random.c ******************************************/
21951 /*
21952 ** 2001 September 15
21953 **
21954 ** The author disclaims copyright to this source code.  In place of
21955 ** a legal notice, here is a blessing:
21956 **
21957 **    May you do good and not evil.
21958 **    May you find forgiveness for yourself and forgive others.
21959 **    May you share freely, never taking more than you give.
21960 **
21961 *************************************************************************
21962 ** This file contains code to implement a pseudo-random number
21963 ** generator (PRNG) for SQLite.
21964 **
21965 ** Random numbers are used by some of the database backends in order
21966 ** to generate random integer keys for tables or random filenames.
21967 */
21968
21969
21970 /* All threads share a single random number generator.
21971 ** This structure is the current state of the generator.
21972 */
21973 static SQLCIPHER_WSD struct sqlcipher3PrngType {
21974   unsigned char isInit;          /* True if initialized */
21975   unsigned char i, j;            /* State variables */
21976   unsigned char s[256];          /* State variables */
21977 } sqlcipher3Prng;
21978
21979 /*
21980 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
21981 ** must be held while executing this routine.
21982 **
21983 ** Why not just use a library random generator like lrand48() for this?
21984 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
21985 ** good source of random numbers.  The lrand48() library function may
21986 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
21987 ** subtle problems on some systems that could cause problems.  It is hard
21988 ** to know.  To minimize the risk of problems due to bad lrand48()
21989 ** implementations, SQLite uses this random number generator based
21990 ** on RC4, which we know works very well.
21991 **
21992 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
21993 ** randomness any more.  But we will leave this code in all the same.
21994 */
21995 static u8 randomByte(void){
21996   unsigned char t;
21997
21998
21999   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
22000   ** state vector.  If writable static data is unsupported on the target,
22001   ** we have to locate the state vector at run-time.  In the more common
22002   ** case where writable static data is supported, wsdPrng can refer directly
22003   ** to the "sqlcipher3Prng" state vector declared above.
22004   */
22005 #ifdef SQLCIPHER_OMIT_WSD
22006   struct sqlcipher3PrngType *p = &GLOBAL(struct sqlcipher3PrngType, sqlcipher3Prng);
22007 # define wsdPrng p[0]
22008 #else
22009 # define wsdPrng sqlcipher3Prng
22010 #endif
22011
22012
22013   /* Initialize the state of the random number generator once,
22014   ** the first time this routine is called.  The seed value does
22015   ** not need to contain a lot of randomness since we are not
22016   ** trying to do secure encryption or anything like that...
22017   **
22018   ** Nothing in this file or anywhere else in SQLite does any kind of
22019   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
22020   ** number generator) not as an encryption device.
22021   */
22022   if( !wsdPrng.isInit ){
22023     int i;
22024     char k[256];
22025     wsdPrng.j = 0;
22026     wsdPrng.i = 0;
22027     sqlcipher3OsRandomness(sqlcipher3_vfs_find(0), 256, k);
22028     for(i=0; i<256; i++){
22029       wsdPrng.s[i] = (u8)i;
22030     }
22031     for(i=0; i<256; i++){
22032       wsdPrng.j += wsdPrng.s[i] + k[i];
22033       t = wsdPrng.s[wsdPrng.j];
22034       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
22035       wsdPrng.s[i] = t;
22036     }
22037     wsdPrng.isInit = 1;
22038   }
22039
22040   /* Generate and return single random byte
22041   */
22042   wsdPrng.i++;
22043   t = wsdPrng.s[wsdPrng.i];
22044   wsdPrng.j += t;
22045   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
22046   wsdPrng.s[wsdPrng.j] = t;
22047   t += wsdPrng.s[wsdPrng.i];
22048   return wsdPrng.s[t];
22049 }
22050
22051 /*
22052 ** Return N random bytes.
22053 */
22054 SQLCIPHER_API void sqlcipher3_randomness(int N, void *pBuf){
22055   unsigned char *zBuf = pBuf;
22056 #if SQLCIPHER_THREADSAFE
22057   sqlcipher3_mutex *mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_PRNG);
22058 #endif
22059   sqlcipher3_mutex_enter(mutex);
22060   while( N-- ){
22061     *(zBuf++) = randomByte();
22062   }
22063   sqlcipher3_mutex_leave(mutex);
22064 }
22065
22066 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
22067 /*
22068 ** For testing purposes, we sometimes want to preserve the state of
22069 ** PRNG and restore the PRNG to its saved state at a later time, or
22070 ** to reset the PRNG to its initial state.  These routines accomplish
22071 ** those tasks.
22072 **
22073 ** The sqlcipher3_test_control() interface calls these routines to
22074 ** control the PRNG.
22075 */
22076 static SQLCIPHER_WSD struct sqlcipher3PrngType sqlcipher3SavedPrng;
22077 SQLCIPHER_PRIVATE void sqlcipher3PrngSaveState(void){
22078   memcpy(
22079     &GLOBAL(struct sqlcipher3PrngType, sqlcipher3SavedPrng),
22080     &GLOBAL(struct sqlcipher3PrngType, sqlcipher3Prng),
22081     sizeof(sqlcipher3Prng)
22082   );
22083 }
22084 SQLCIPHER_PRIVATE void sqlcipher3PrngRestoreState(void){
22085   memcpy(
22086     &GLOBAL(struct sqlcipher3PrngType, sqlcipher3Prng),
22087     &GLOBAL(struct sqlcipher3PrngType, sqlcipher3SavedPrng),
22088     sizeof(sqlcipher3Prng)
22089   );
22090 }
22091 SQLCIPHER_PRIVATE void sqlcipher3PrngResetState(void){
22092   GLOBAL(struct sqlcipher3PrngType, sqlcipher3Prng).isInit = 0;
22093 }
22094 #endif /* SQLCIPHER_OMIT_BUILTIN_TEST */
22095
22096 /************** End of random.c **********************************************/
22097 /************** Begin file utf.c *********************************************/
22098 /*
22099 ** 2004 April 13
22100 **
22101 ** The author disclaims copyright to this source code.  In place of
22102 ** a legal notice, here is a blessing:
22103 **
22104 **    May you do good and not evil.
22105 **    May you find forgiveness for yourself and forgive others.
22106 **    May you share freely, never taking more than you give.
22107 **
22108 *************************************************************************
22109 ** This file contains routines used to translate between UTF-8, 
22110 ** UTF-16, UTF-16BE, and UTF-16LE.
22111 **
22112 ** Notes on UTF-8:
22113 **
22114 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
22115 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
22116 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
22117 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
22118 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
22119 **
22120 **
22121 ** Notes on UTF-16:  (with wwww+1==uuuuu)
22122 **
22123 **      Word-0               Word-1          Value
22124 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
22125 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
22126 **
22127 **
22128 ** BOM or Byte Order Mark:
22129 **     0xff 0xfe   little-endian utf-16 follows
22130 **     0xfe 0xff   big-endian utf-16 follows
22131 **
22132 */
22133 /* #include <assert.h> */
22134
22135 #ifndef SQLCIPHER_AMALGAMATION
22136 /*
22137 ** The following constant value is used by the SQLCIPHER_BIGENDIAN and
22138 ** SQLCIPHER_LITTLEENDIAN macros.
22139 */
22140 SQLCIPHER_PRIVATE const int sqlcipher3one = 1;
22141 #endif /* SQLCIPHER_AMALGAMATION */
22142
22143 /*
22144 ** This lookup table is used to help decode the first byte of
22145 ** a multi-byte UTF8 character.
22146 */
22147 static const unsigned char sqlcipher3Utf8Trans1[] = {
22148   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22149   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22150   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
22151   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
22152   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22153   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22154   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22155   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
22156 };
22157
22158
22159 #define WRITE_UTF8(zOut, c) {                          \
22160   if( c<0x00080 ){                                     \
22161     *zOut++ = (u8)(c&0xFF);                            \
22162   }                                                    \
22163   else if( c<0x00800 ){                                \
22164     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
22165     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22166   }                                                    \
22167   else if( c<0x10000 ){                                \
22168     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
22169     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
22170     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22171   }else{                                               \
22172     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
22173     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
22174     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
22175     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22176   }                                                    \
22177 }
22178
22179 #define WRITE_UTF16LE(zOut, c) {                                    \
22180   if( c<=0xFFFF ){                                                  \
22181     *zOut++ = (u8)(c&0x00FF);                                       \
22182     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
22183   }else{                                                            \
22184     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
22185     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
22186     *zOut++ = (u8)(c&0x00FF);                                       \
22187     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
22188   }                                                                 \
22189 }
22190
22191 #define WRITE_UTF16BE(zOut, c) {                                    \
22192   if( c<=0xFFFF ){                                                  \
22193     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
22194     *zOut++ = (u8)(c&0x00FF);                                       \
22195   }else{                                                            \
22196     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
22197     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
22198     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
22199     *zOut++ = (u8)(c&0x00FF);                                       \
22200   }                                                                 \
22201 }
22202
22203 #define READ_UTF16LE(zIn, TERM, c){                                   \
22204   c = (*zIn++);                                                       \
22205   c += ((*zIn++)<<8);                                                 \
22206   if( c>=0xD800 && c<0xE000 && TERM ){                                \
22207     int c2 = (*zIn++);                                                \
22208     c2 += ((*zIn++)<<8);                                              \
22209     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
22210   }                                                                   \
22211 }
22212
22213 #define READ_UTF16BE(zIn, TERM, c){                                   \
22214   c = ((*zIn++)<<8);                                                  \
22215   c += (*zIn++);                                                      \
22216   if( c>=0xD800 && c<0xE000 && TERM ){                                \
22217     int c2 = ((*zIn++)<<8);                                           \
22218     c2 += (*zIn++);                                                   \
22219     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
22220   }                                                                   \
22221 }
22222
22223 /*
22224 ** Translate a single UTF-8 character.  Return the unicode value.
22225 **
22226 ** During translation, assume that the byte that zTerm points
22227 ** is a 0x00.
22228 **
22229 ** Write a pointer to the next unread byte back into *pzNext.
22230 **
22231 ** Notes On Invalid UTF-8:
22232 **
22233 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
22234 **     be encoded as a multi-byte character.  Any multi-byte character that
22235 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
22236 **
22237 **  *  This routine never allows a UTF16 surrogate value to be encoded.
22238 **     If a multi-byte character attempts to encode a value between
22239 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
22240 **
22241 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
22242 **     byte of a character are interpreted as single-byte characters
22243 **     and rendered as themselves even though they are technically
22244 **     invalid characters.
22245 **
22246 **  *  This routine accepts an infinite number of different UTF8 encodings
22247 **     for unicode values 0x80 and greater.  It do not change over-length
22248 **     encodings to 0xfffd as some systems recommend.
22249 */
22250 #define READ_UTF8(zIn, zTerm, c)                           \
22251   c = *(zIn++);                                            \
22252   if( c>=0xc0 ){                                           \
22253     c = sqlcipher3Utf8Trans1[c-0xc0];                         \
22254     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
22255       c = (c<<6) + (0x3f & *(zIn++));                      \
22256     }                                                      \
22257     if( c<0x80                                             \
22258         || (c&0xFFFFF800)==0xD800                          \
22259         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
22260   }
22261 SQLCIPHER_PRIVATE u32 sqlcipher3Utf8Read(
22262   const unsigned char *zIn,       /* First byte of UTF-8 character */
22263   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
22264 ){
22265   unsigned int c;
22266
22267   /* Same as READ_UTF8() above but without the zTerm parameter.
22268   ** For this routine, we assume the UTF8 string is always zero-terminated.
22269   */
22270   c = *(zIn++);
22271   if( c>=0xc0 ){
22272     c = sqlcipher3Utf8Trans1[c-0xc0];
22273     while( (*zIn & 0xc0)==0x80 ){
22274       c = (c<<6) + (0x3f & *(zIn++));
22275     }
22276     if( c<0x80
22277         || (c&0xFFFFF800)==0xD800
22278         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
22279   }
22280   *pzNext = zIn;
22281   return c;
22282 }
22283
22284
22285
22286
22287 /*
22288 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
22289 ** printed on stderr on the way into and out of sqlcipher3VdbeMemTranslate().
22290 */ 
22291 /* #define TRANSLATE_TRACE 1 */
22292
22293 #ifndef SQLCIPHER_OMIT_UTF16
22294 /*
22295 ** This routine transforms the internal text encoding used by pMem to
22296 ** desiredEnc. It is an error if the string is already of the desired
22297 ** encoding, or if *pMem does not contain a string value.
22298 */
22299 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
22300   int len;                    /* Maximum length of output string in bytes */
22301   unsigned char *zOut;                  /* Output buffer */
22302   unsigned char *zIn;                   /* Input iterator */
22303   unsigned char *zTerm;                 /* End of input */
22304   unsigned char *z;                     /* Output iterator */
22305   unsigned int c;
22306
22307   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
22308   assert( pMem->flags&MEM_Str );
22309   assert( pMem->enc!=desiredEnc );
22310   assert( pMem->enc!=0 );
22311   assert( pMem->n>=0 );
22312
22313 #if defined(TRANSLATE_TRACE) && defined(SQLCIPHER_DEBUG)
22314   {
22315     char zBuf[100];
22316     sqlcipher3VdbeMemPrettyPrint(pMem, zBuf);
22317     fprintf(stderr, "INPUT:  %s\n", zBuf);
22318   }
22319 #endif
22320
22321   /* If the translation is between UTF-16 little and big endian, then 
22322   ** all that is required is to swap the byte order. This case is handled
22323   ** differently from the others.
22324   */
22325   if( pMem->enc!=SQLCIPHER_UTF8 && desiredEnc!=SQLCIPHER_UTF8 ){
22326     u8 temp;
22327     int rc;
22328     rc = sqlcipher3VdbeMemMakeWriteable(pMem);
22329     if( rc!=SQLCIPHER_OK ){
22330       assert( rc==SQLCIPHER_NOMEM );
22331       return SQLCIPHER_NOMEM;
22332     }
22333     zIn = (u8*)pMem->z;
22334     zTerm = &zIn[pMem->n&~1];
22335     while( zIn<zTerm ){
22336       temp = *zIn;
22337       *zIn = *(zIn+1);
22338       zIn++;
22339       *zIn++ = temp;
22340     }
22341     pMem->enc = desiredEnc;
22342     goto translate_out;
22343   }
22344
22345   /* Set len to the maximum number of bytes required in the output buffer. */
22346   if( desiredEnc==SQLCIPHER_UTF8 ){
22347     /* When converting from UTF-16, the maximum growth results from
22348     ** translating a 2-byte character to a 4-byte UTF-8 character.
22349     ** A single byte is required for the output string
22350     ** nul-terminator.
22351     */
22352     pMem->n &= ~1;
22353     len = pMem->n * 2 + 1;
22354   }else{
22355     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
22356     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
22357     ** character. Two bytes are required in the output buffer for the
22358     ** nul-terminator.
22359     */
22360     len = pMem->n * 2 + 2;
22361   }
22362
22363   /* Set zIn to point at the start of the input buffer and zTerm to point 1
22364   ** byte past the end.
22365   **
22366   ** Variable zOut is set to point at the output buffer, space obtained
22367   ** from sqlcipher3_malloc().
22368   */
22369   zIn = (u8*)pMem->z;
22370   zTerm = &zIn[pMem->n];
22371   zOut = sqlcipher3DbMallocRaw(pMem->db, len);
22372   if( !zOut ){
22373     return SQLCIPHER_NOMEM;
22374   }
22375   z = zOut;
22376
22377   if( pMem->enc==SQLCIPHER_UTF8 ){
22378     if( desiredEnc==SQLCIPHER_UTF16LE ){
22379       /* UTF-8 -> UTF-16 Little-endian */
22380       while( zIn<zTerm ){
22381         /* c = sqlcipher3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
22382         READ_UTF8(zIn, zTerm, c);
22383         WRITE_UTF16LE(z, c);
22384       }
22385     }else{
22386       assert( desiredEnc==SQLCIPHER_UTF16BE );
22387       /* UTF-8 -> UTF-16 Big-endian */
22388       while( zIn<zTerm ){
22389         /* c = sqlcipher3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
22390         READ_UTF8(zIn, zTerm, c);
22391         WRITE_UTF16BE(z, c);
22392       }
22393     }
22394     pMem->n = (int)(z - zOut);
22395     *z++ = 0;
22396   }else{
22397     assert( desiredEnc==SQLCIPHER_UTF8 );
22398     if( pMem->enc==SQLCIPHER_UTF16LE ){
22399       /* UTF-16 Little-endian -> UTF-8 */
22400       while( zIn<zTerm ){
22401         READ_UTF16LE(zIn, zIn<zTerm, c); 
22402         WRITE_UTF8(z, c);
22403       }
22404     }else{
22405       /* UTF-16 Big-endian -> UTF-8 */
22406       while( zIn<zTerm ){
22407         READ_UTF16BE(zIn, zIn<zTerm, c); 
22408         WRITE_UTF8(z, c);
22409       }
22410     }
22411     pMem->n = (int)(z - zOut);
22412   }
22413   *z = 0;
22414   assert( (pMem->n+(desiredEnc==SQLCIPHER_UTF8?1:2))<=len );
22415
22416   sqlcipher3VdbeMemRelease(pMem);
22417   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
22418   pMem->enc = desiredEnc;
22419   pMem->flags |= (MEM_Term|MEM_Dyn);
22420   pMem->z = (char*)zOut;
22421   pMem->zMalloc = pMem->z;
22422
22423 translate_out:
22424 #if defined(TRANSLATE_TRACE) && defined(SQLCIPHER_DEBUG)
22425   {
22426     char zBuf[100];
22427     sqlcipher3VdbeMemPrettyPrint(pMem, zBuf);
22428     fprintf(stderr, "OUTPUT: %s\n", zBuf);
22429   }
22430 #endif
22431   return SQLCIPHER_OK;
22432 }
22433
22434 /*
22435 ** This routine checks for a byte-order mark at the beginning of the 
22436 ** UTF-16 string stored in *pMem. If one is present, it is removed and
22437 ** the encoding of the Mem adjusted. This routine does not do any
22438 ** byte-swapping, it just sets Mem.enc appropriately.
22439 **
22440 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
22441 ** changed by this function.
22442 */
22443 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemHandleBom(Mem *pMem){
22444   int rc = SQLCIPHER_OK;
22445   u8 bom = 0;
22446
22447   assert( pMem->n>=0 );
22448   if( pMem->n>1 ){
22449     u8 b1 = *(u8 *)pMem->z;
22450     u8 b2 = *(((u8 *)pMem->z) + 1);
22451     if( b1==0xFE && b2==0xFF ){
22452       bom = SQLCIPHER_UTF16BE;
22453     }
22454     if( b1==0xFF && b2==0xFE ){
22455       bom = SQLCIPHER_UTF16LE;
22456     }
22457   }
22458   
22459   if( bom ){
22460     rc = sqlcipher3VdbeMemMakeWriteable(pMem);
22461     if( rc==SQLCIPHER_OK ){
22462       pMem->n -= 2;
22463       memmove(pMem->z, &pMem->z[2], pMem->n);
22464       pMem->z[pMem->n] = '\0';
22465       pMem->z[pMem->n+1] = '\0';
22466       pMem->flags |= MEM_Term;
22467       pMem->enc = bom;
22468     }
22469   }
22470   return rc;
22471 }
22472 #endif /* SQLCIPHER_OMIT_UTF16 */
22473
22474 /*
22475 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
22476 ** return the number of unicode characters in pZ up to (but not including)
22477 ** the first 0x00 byte. If nByte is not less than zero, return the
22478 ** number of unicode characters in the first nByte of pZ (or up to 
22479 ** the first 0x00, whichever comes first).
22480 */
22481 SQLCIPHER_PRIVATE int sqlcipher3Utf8CharLen(const char *zIn, int nByte){
22482   int r = 0;
22483   const u8 *z = (const u8*)zIn;
22484   const u8 *zTerm;
22485   if( nByte>=0 ){
22486     zTerm = &z[nByte];
22487   }else{
22488     zTerm = (const u8*)(-1);
22489   }
22490   assert( z<=zTerm );
22491   while( *z!=0 && z<zTerm ){
22492     SQLCIPHER_SKIP_UTF8(z);
22493     r++;
22494   }
22495   return r;
22496 }
22497
22498 /* This test function is not currently used by the automated test-suite. 
22499 ** Hence it is only available in debug builds.
22500 */
22501 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
22502 /*
22503 ** Translate UTF-8 to UTF-8.
22504 **
22505 ** This has the effect of making sure that the string is well-formed
22506 ** UTF-8.  Miscoded characters are removed.
22507 **
22508 ** The translation is done in-place and aborted if the output
22509 ** overruns the input.
22510 */
22511 SQLCIPHER_PRIVATE int sqlcipher3Utf8To8(unsigned char *zIn){
22512   unsigned char *zOut = zIn;
22513   unsigned char *zStart = zIn;
22514   u32 c;
22515
22516   while( zIn[0] && zOut<=zIn ){
22517     c = sqlcipher3Utf8Read(zIn, (const u8**)&zIn);
22518     if( c!=0xfffd ){
22519       WRITE_UTF8(zOut, c);
22520     }
22521   }
22522   *zOut = 0;
22523   return (int)(zOut - zStart);
22524 }
22525 #endif
22526
22527 #ifndef SQLCIPHER_OMIT_UTF16
22528 /*
22529 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
22530 ** Memory to hold the UTF-8 string is obtained from sqlcipher3_malloc and must
22531 ** be freed by the calling function.
22532 **
22533 ** NULL is returned if there is an allocation error.
22534 */
22535 SQLCIPHER_PRIVATE char *sqlcipher3Utf16to8(sqlcipher3 *db, const void *z, int nByte, u8 enc){
22536   Mem m;
22537   memset(&m, 0, sizeof(m));
22538   m.db = db;
22539   sqlcipher3VdbeMemSetStr(&m, z, nByte, enc, SQLCIPHER_STATIC);
22540   sqlcipher3VdbeChangeEncoding(&m, SQLCIPHER_UTF8);
22541   if( db->mallocFailed ){
22542     sqlcipher3VdbeMemRelease(&m);
22543     m.z = 0;
22544   }
22545   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
22546   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
22547   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
22548   assert( m.z || db->mallocFailed );
22549   return m.z;
22550 }
22551
22552 /*
22553 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
22554 ** enc. A pointer to the new string is returned, and the value of *pnOut
22555 ** is set to the length of the returned string in bytes. The call should
22556 ** arrange to call sqlcipher3DbFree() on the returned pointer when it is
22557 ** no longer required.
22558 ** 
22559 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
22560 ** flag set.
22561 */
22562 #ifdef SQLCIPHER_ENABLE_STAT3
22563 SQLCIPHER_PRIVATE char *sqlcipher3Utf8to16(sqlcipher3 *db, u8 enc, char *z, int n, int *pnOut){
22564   Mem m;
22565   memset(&m, 0, sizeof(m));
22566   m.db = db;
22567   sqlcipher3VdbeMemSetStr(&m, z, n, SQLCIPHER_UTF8, SQLCIPHER_STATIC);
22568   if( sqlcipher3VdbeMemTranslate(&m, enc) ){
22569     assert( db->mallocFailed );
22570     return 0;
22571   }
22572   assert( m.z==m.zMalloc );
22573   *pnOut = m.n;
22574   return m.z;
22575 }
22576 #endif
22577
22578 /*
22579 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
22580 ** Return the number of bytes in the first nChar unicode characters
22581 ** in pZ.  nChar must be non-negative.
22582 */
22583 SQLCIPHER_PRIVATE int sqlcipher3Utf16ByteLen(const void *zIn, int nChar){
22584   int c;
22585   unsigned char const *z = zIn;
22586   int n = 0;
22587   
22588   if( SQLCIPHER_UTF16NATIVE==SQLCIPHER_UTF16BE ){
22589     while( n<nChar ){
22590       READ_UTF16BE(z, 1, c);
22591       n++;
22592     }
22593   }else{
22594     while( n<nChar ){
22595       READ_UTF16LE(z, 1, c);
22596       n++;
22597     }
22598   }
22599   return (int)(z-(unsigned char const *)zIn);
22600 }
22601
22602 #if defined(SQLCIPHER_TEST)
22603 /*
22604 ** This routine is called from the TCL test function "translate_selftest".
22605 ** It checks that the primitives for serializing and deserializing
22606 ** characters in each encoding are inverses of each other.
22607 */
22608 SQLCIPHER_PRIVATE void sqlcipher3UtfSelfTest(void){
22609   unsigned int i, t;
22610   unsigned char zBuf[20];
22611   unsigned char *z;
22612   int n;
22613   unsigned int c;
22614
22615   for(i=0; i<0x00110000; i++){
22616     z = zBuf;
22617     WRITE_UTF8(z, i);
22618     n = (int)(z-zBuf);
22619     assert( n>0 && n<=4 );
22620     z[0] = 0;
22621     z = zBuf;
22622     c = sqlcipher3Utf8Read(z, (const u8**)&z);
22623     t = i;
22624     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
22625     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
22626     assert( c==t );
22627     assert( (z-zBuf)==n );
22628   }
22629   for(i=0; i<0x00110000; i++){
22630     if( i>=0xD800 && i<0xE000 ) continue;
22631     z = zBuf;
22632     WRITE_UTF16LE(z, i);
22633     n = (int)(z-zBuf);
22634     assert( n>0 && n<=4 );
22635     z[0] = 0;
22636     z = zBuf;
22637     READ_UTF16LE(z, 1, c);
22638     assert( c==i );
22639     assert( (z-zBuf)==n );
22640   }
22641   for(i=0; i<0x00110000; i++){
22642     if( i>=0xD800 && i<0xE000 ) continue;
22643     z = zBuf;
22644     WRITE_UTF16BE(z, i);
22645     n = (int)(z-zBuf);
22646     assert( n>0 && n<=4 );
22647     z[0] = 0;
22648     z = zBuf;
22649     READ_UTF16BE(z, 1, c);
22650     assert( c==i );
22651     assert( (z-zBuf)==n );
22652   }
22653 }
22654 #endif /* SQLCIPHER_TEST */
22655 #endif /* SQLCIPHER_OMIT_UTF16 */
22656
22657 /************** End of utf.c *************************************************/
22658 /************** Begin file util.c ********************************************/
22659 /*
22660 ** 2001 September 15
22661 **
22662 ** The author disclaims copyright to this source code.  In place of
22663 ** a legal notice, here is a blessing:
22664 **
22665 **    May you do good and not evil.
22666 **    May you find forgiveness for yourself and forgive others.
22667 **    May you share freely, never taking more than you give.
22668 **
22669 *************************************************************************
22670 ** Utility functions used throughout sqlcipher.
22671 **
22672 ** This file contains functions for allocating memory, comparing
22673 ** strings, and stuff like that.
22674 **
22675 */
22676 /* #include <stdarg.h> */
22677 #ifdef SQLCIPHER_HAVE_ISNAN
22678 # include <math.h>
22679 #endif
22680
22681 /*
22682 ** Routine needed to support the testcase() macro.
22683 */
22684 #ifdef SQLCIPHER_COVERAGE_TEST
22685 SQLCIPHER_PRIVATE void sqlcipher3Coverage(int x){
22686   static unsigned dummy = 0;
22687   dummy += (unsigned)x;
22688 }
22689 #endif
22690
22691 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
22692 /*
22693 ** Return true if the floating point value is Not a Number (NaN).
22694 **
22695 ** Use the math library isnan() function if compiled with SQLCIPHER_HAVE_ISNAN.
22696 ** Otherwise, we have our own implementation that works on most systems.
22697 */
22698 SQLCIPHER_PRIVATE int sqlcipher3IsNaN(double x){
22699   int rc;   /* The value return */
22700 #if !defined(SQLCIPHER_HAVE_ISNAN)
22701   /*
22702   ** Systems that support the isnan() library function should probably
22703   ** make use of it by compiling with -DSQLCIPHER_HAVE_ISNAN.  But we have
22704   ** found that many systems do not have a working isnan() function so
22705   ** this implementation is provided as an alternative.
22706   **
22707   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
22708   ** On the other hand, the use of -ffast-math comes with the following
22709   ** warning:
22710   **
22711   **      This option [-ffast-math] should never be turned on by any
22712   **      -O option since it can result in incorrect output for programs
22713   **      which depend on an exact implementation of IEEE or ISO 
22714   **      rules/specifications for math functions.
22715   **
22716   ** Under MSVC, this NaN test may fail if compiled with a floating-
22717   ** point precision mode other than /fp:precise.  From the MSDN 
22718   ** documentation:
22719   **
22720   **      The compiler [with /fp:precise] will properly handle comparisons 
22721   **      involving NaN. For example, x != x evaluates to true if x is NaN 
22722   **      ...
22723   */
22724 #ifdef __FAST_MATH__
22725 # error SQLite will not work correctly with the -ffast-math option of GCC.
22726 #endif
22727   volatile double y = x;
22728   volatile double z = y;
22729   rc = (y!=z);
22730 #else  /* if defined(SQLCIPHER_HAVE_ISNAN) */
22731   rc = isnan(x);
22732 #endif /* SQLCIPHER_HAVE_ISNAN */
22733   testcase( rc );
22734   return rc;
22735 }
22736 #endif /* SQLCIPHER_OMIT_FLOATING_POINT */
22737
22738 /*
22739 ** Compute a string length that is limited to what can be stored in
22740 ** lower 30 bits of a 32-bit signed integer.
22741 **
22742 ** The value returned will never be negative.  Nor will it ever be greater
22743 ** than the actual length of the string.  For very long strings (greater
22744 ** than 1GiB) the value returned might be less than the true string length.
22745 */
22746 SQLCIPHER_PRIVATE int sqlcipher3Strlen30(const char *z){
22747   const char *z2 = z;
22748   if( z==0 ) return 0;
22749   while( *z2 ){ z2++; }
22750   return 0x3fffffff & (int)(z2 - z);
22751 }
22752
22753 /*
22754 ** Set the most recent error code and error string for the sqlcipher
22755 ** handle "db". The error code is set to "err_code".
22756 **
22757 ** If it is not NULL, string zFormat specifies the format of the
22758 ** error string in the style of the printf functions: The following
22759 ** format characters are allowed:
22760 **
22761 **      %s      Insert a string
22762 **      %z      A string that should be freed after use
22763 **      %d      Insert an integer
22764 **      %T      Insert a token
22765 **      %S      Insert the first element of a SrcList
22766 **
22767 ** zFormat and any string tokens that follow it are assumed to be
22768 ** encoded in UTF-8.
22769 **
22770 ** To clear the most recent error for sqlcipher handle "db", sqlcipher3Error
22771 ** should be called with err_code set to SQLCIPHER_OK and zFormat set
22772 ** to NULL.
22773 */
22774 SQLCIPHER_PRIVATE void sqlcipher3Error(sqlcipher3 *db, int err_code, const char *zFormat, ...){
22775   if( db && (db->pErr || (db->pErr = sqlcipher3ValueNew(db))!=0) ){
22776     db->errCode = err_code;
22777     if( zFormat ){
22778       char *z;
22779       va_list ap;
22780       va_start(ap, zFormat);
22781       z = sqlcipher3VMPrintf(db, zFormat, ap);
22782       va_end(ap);
22783       sqlcipher3ValueSetStr(db->pErr, -1, z, SQLCIPHER_UTF8, SQLCIPHER_DYNAMIC);
22784     }else{
22785       sqlcipher3ValueSetStr(db->pErr, 0, 0, SQLCIPHER_UTF8, SQLCIPHER_STATIC);
22786     }
22787   }
22788 }
22789
22790 /*
22791 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
22792 ** The following formatting characters are allowed:
22793 **
22794 **      %s      Insert a string
22795 **      %z      A string that should be freed after use
22796 **      %d      Insert an integer
22797 **      %T      Insert a token
22798 **      %S      Insert the first element of a SrcList
22799 **
22800 ** This function should be used to report any error that occurs whilst
22801 ** compiling an SQL statement (i.e. within sqlcipher3_prepare()). The
22802 ** last thing the sqlcipher3_prepare() function does is copy the error
22803 ** stored by this function into the database handle using sqlcipher3Error().
22804 ** Function sqlcipher3Error() should be used during statement execution
22805 ** (sqlcipher3_step() etc.).
22806 */
22807 SQLCIPHER_PRIVATE void sqlcipher3ErrorMsg(Parse *pParse, const char *zFormat, ...){
22808   char *zMsg;
22809   va_list ap;
22810   sqlcipher3 *db = pParse->db;
22811   va_start(ap, zFormat);
22812   zMsg = sqlcipher3VMPrintf(db, zFormat, ap);
22813   va_end(ap);
22814   if( db->suppressErr ){
22815     sqlcipher3DbFree(db, zMsg);
22816   }else{
22817     pParse->nErr++;
22818     sqlcipher3DbFree(db, pParse->zErrMsg);
22819     pParse->zErrMsg = zMsg;
22820     pParse->rc = SQLCIPHER_ERROR;
22821   }
22822 }
22823
22824 /*
22825 ** Convert an SQL-style quoted string into a normal string by removing
22826 ** the quote characters.  The conversion is done in-place.  If the
22827 ** input does not begin with a quote character, then this routine
22828 ** is a no-op.
22829 **
22830 ** The input string must be zero-terminated.  A new zero-terminator
22831 ** is added to the dequoted string.
22832 **
22833 ** The return value is -1 if no dequoting occurs or the length of the
22834 ** dequoted string, exclusive of the zero terminator, if dequoting does
22835 ** occur.
22836 **
22837 ** 2002-Feb-14: This routine is extended to remove MS-Access style
22838 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
22839 ** "a-b-c".
22840 */
22841 SQLCIPHER_PRIVATE int sqlcipher3Dequote(char *z){
22842   char quote;
22843   int i, j;
22844   if( z==0 ) return -1;
22845   quote = z[0];
22846   switch( quote ){
22847     case '\'':  break;
22848     case '"':   break;
22849     case '`':   break;                /* For MySQL compatibility */
22850     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
22851     default:    return -1;
22852   }
22853   for(i=1, j=0; ALWAYS(z[i]); i++){
22854     if( z[i]==quote ){
22855       if( z[i+1]==quote ){
22856         z[j++] = quote;
22857         i++;
22858       }else{
22859         break;
22860       }
22861     }else{
22862       z[j++] = z[i];
22863     }
22864   }
22865   z[j] = 0;
22866   return j;
22867 }
22868
22869 /* Convenient short-hand */
22870 #define UpperToLower sqlcipher3UpperToLower
22871
22872 /*
22873 ** Some systems have stricmp().  Others have strcasecmp().  Because
22874 ** there is no consistency, we will define our own.
22875 **
22876 ** IMPLEMENTATION-OF: R-20522-24639 The sqlcipher3_strnicmp() API allows
22877 ** applications and extensions to compare the contents of two buffers
22878 ** containing UTF-8 strings in a case-independent fashion, using the same
22879 ** definition of case independence that SQLite uses internally when
22880 ** comparing identifiers.
22881 */
22882 SQLCIPHER_PRIVATE int sqlcipher3StrICmp(const char *zLeft, const char *zRight){
22883   register unsigned char *a, *b;
22884   a = (unsigned char *)zLeft;
22885   b = (unsigned char *)zRight;
22886   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
22887   return UpperToLower[*a] - UpperToLower[*b];
22888 }
22889 SQLCIPHER_API int sqlcipher3_strnicmp(const char *zLeft, const char *zRight, int N){
22890   register unsigned char *a, *b;
22891   a = (unsigned char *)zLeft;
22892   b = (unsigned char *)zRight;
22893   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
22894   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
22895 }
22896
22897 /*
22898 ** The string z[] is an text representation of a real number.
22899 ** Convert this string to a double and write it into *pResult.
22900 **
22901 ** The string z[] is length bytes in length (bytes, not characters) and
22902 ** uses the encoding enc.  The string is not necessarily zero-terminated.
22903 **
22904 ** Return TRUE if the result is a valid real number (or integer) and FALSE
22905 ** if the string is empty or contains extraneous text.  Valid numbers
22906 ** are in one of these formats:
22907 **
22908 **    [+-]digits[E[+-]digits]
22909 **    [+-]digits.[digits][E[+-]digits]
22910 **    [+-].digits[E[+-]digits]
22911 **
22912 ** Leading and trailing whitespace is ignored for the purpose of determining
22913 ** validity.
22914 **
22915 ** If some prefix of the input string is a valid number, this routine
22916 ** returns FALSE but it still converts the prefix and writes the result
22917 ** into *pResult.
22918 */
22919 SQLCIPHER_PRIVATE int sqlcipher3AtoF(const char *z, double *pResult, int length, u8 enc){
22920 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
22921   int incr = (enc==SQLCIPHER_UTF8?1:2);
22922   const char *zEnd = z + length;
22923   /* sign * significand * (10 ^ (esign * exponent)) */
22924   int sign = 1;    /* sign of significand */
22925   i64 s = 0;       /* significand */
22926   int d = 0;       /* adjust exponent for shifting decimal point */
22927   int esign = 1;   /* sign of exponent */
22928   int e = 0;       /* exponent */
22929   int eValid = 1;  /* True exponent is either not used or is well-formed */
22930   double result;
22931   int nDigits = 0;
22932
22933   *pResult = 0.0;   /* Default return value, in case of an error */
22934
22935   if( enc==SQLCIPHER_UTF16BE ) z++;
22936
22937   /* skip leading spaces */
22938   while( z<zEnd && sqlcipher3Isspace(*z) ) z+=incr;
22939   if( z>=zEnd ) return 0;
22940
22941   /* get sign of significand */
22942   if( *z=='-' ){
22943     sign = -1;
22944     z+=incr;
22945   }else if( *z=='+' ){
22946     z+=incr;
22947   }
22948
22949   /* skip leading zeroes */
22950   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
22951
22952   /* copy max significant digits to significand */
22953   while( z<zEnd && sqlcipher3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
22954     s = s*10 + (*z - '0');
22955     z+=incr, nDigits++;
22956   }
22957
22958   /* skip non-significant significand digits
22959   ** (increase exponent by d to shift decimal left) */
22960   while( z<zEnd && sqlcipher3Isdigit(*z) ) z+=incr, nDigits++, d++;
22961   if( z>=zEnd ) goto do_atof_calc;
22962
22963   /* if decimal point is present */
22964   if( *z=='.' ){
22965     z+=incr;
22966     /* copy digits from after decimal to significand
22967     ** (decrease exponent by d to shift decimal right) */
22968     while( z<zEnd && sqlcipher3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
22969       s = s*10 + (*z - '0');
22970       z+=incr, nDigits++, d--;
22971     }
22972     /* skip non-significant digits */
22973     while( z<zEnd && sqlcipher3Isdigit(*z) ) z+=incr, nDigits++;
22974   }
22975   if( z>=zEnd ) goto do_atof_calc;
22976
22977   /* if exponent is present */
22978   if( *z=='e' || *z=='E' ){
22979     z+=incr;
22980     eValid = 0;
22981     if( z>=zEnd ) goto do_atof_calc;
22982     /* get sign of exponent */
22983     if( *z=='-' ){
22984       esign = -1;
22985       z+=incr;
22986     }else if( *z=='+' ){
22987       z+=incr;
22988     }
22989     /* copy digits to exponent */
22990     while( z<zEnd && sqlcipher3Isdigit(*z) ){
22991       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
22992       z+=incr;
22993       eValid = 1;
22994     }
22995   }
22996
22997   /* skip trailing spaces */
22998   if( nDigits && eValid ){
22999     while( z<zEnd && sqlcipher3Isspace(*z) ) z+=incr;
23000   }
23001
23002 do_atof_calc:
23003   /* adjust exponent by d, and update sign */
23004   e = (e*esign) + d;
23005   if( e<0 ) {
23006     esign = -1;
23007     e *= -1;
23008   } else {
23009     esign = 1;
23010   }
23011
23012   /* if 0 significand */
23013   if( !s ) {
23014     /* In the IEEE 754 standard, zero is signed.
23015     ** Add the sign if we've seen at least one digit */
23016     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
23017   } else {
23018     /* attempt to reduce exponent */
23019     if( esign>0 ){
23020       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
23021     }else{
23022       while( !(s%10) && e>0 ) e--,s/=10;
23023     }
23024
23025     /* adjust the sign of significand */
23026     s = sign<0 ? -s : s;
23027
23028     /* if exponent, scale significand as appropriate
23029     ** and store in result. */
23030     if( e ){
23031       double scale = 1.0;
23032       /* attempt to handle extremely small/large numbers better */
23033       if( e>307 && e<342 ){
23034         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
23035         if( esign<0 ){
23036           result = s / scale;
23037           result /= 1.0e+308;
23038         }else{
23039           result = s * scale;
23040           result *= 1.0e+308;
23041         }
23042       }else if( e>=342 ){
23043         if( esign<0 ){
23044           result = 0.0*s;
23045         }else{
23046           result = 1e308*1e308*s;  /* Infinity */
23047         }
23048       }else{
23049         /* 1.0e+22 is the largest power of 10 than can be 
23050         ** represented exactly. */
23051         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
23052         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
23053         if( esign<0 ){
23054           result = s / scale;
23055         }else{
23056           result = s * scale;
23057         }
23058       }
23059     } else {
23060       result = (double)s;
23061     }
23062   }
23063
23064   /* store the result */
23065   *pResult = result;
23066
23067   /* return true if number and no extra non-whitespace chracters after */
23068   return z>=zEnd && nDigits>0 && eValid;
23069 #else
23070   return !sqlcipher3Atoi64(z, pResult, length, enc);
23071 #endif /* SQLCIPHER_OMIT_FLOATING_POINT */
23072 }
23073
23074 /*
23075 ** Compare the 19-character string zNum against the text representation
23076 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
23077 ** if zNum is less than, equal to, or greater than the string.
23078 ** Note that zNum must contain exactly 19 characters.
23079 **
23080 ** Unlike memcmp() this routine is guaranteed to return the difference
23081 ** in the values of the last digit if the only difference is in the
23082 ** last digit.  So, for example,
23083 **
23084 **      compare2pow63("9223372036854775800", 1)
23085 **
23086 ** will return -8.
23087 */
23088 static int compare2pow63(const char *zNum, int incr){
23089   int c = 0;
23090   int i;
23091                     /* 012345678901234567 */
23092   const char *pow63 = "922337203685477580";
23093   for(i=0; c==0 && i<18; i++){
23094     c = (zNum[i*incr]-pow63[i])*10;
23095   }
23096   if( c==0 ){
23097     c = zNum[18*incr] - '8';
23098     testcase( c==(-1) );
23099     testcase( c==0 );
23100     testcase( c==(+1) );
23101   }
23102   return c;
23103 }
23104
23105
23106 /*
23107 ** Convert zNum to a 64-bit signed integer.
23108 **
23109 ** If the zNum value is representable as a 64-bit twos-complement 
23110 ** integer, then write that value into *pNum and return 0.
23111 **
23112 ** If zNum is exactly 9223372036854665808, return 2.  This special
23113 ** case is broken out because while 9223372036854665808 cannot be a 
23114 ** signed 64-bit integer, its negative -9223372036854665808 can be.
23115 **
23116 ** If zNum is too big for a 64-bit integer and is not
23117 ** 9223372036854665808 then return 1.
23118 **
23119 ** length is the number of bytes in the string (bytes, not characters).
23120 ** The string is not necessarily zero-terminated.  The encoding is
23121 ** given by enc.
23122 */
23123 SQLCIPHER_PRIVATE int sqlcipher3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
23124   int incr = (enc==SQLCIPHER_UTF8?1:2);
23125   u64 u = 0;
23126   int neg = 0; /* assume positive */
23127   int i;
23128   int c = 0;
23129   const char *zStart;
23130   const char *zEnd = zNum + length;
23131   if( enc==SQLCIPHER_UTF16BE ) zNum++;
23132   while( zNum<zEnd && sqlcipher3Isspace(*zNum) ) zNum+=incr;
23133   if( zNum<zEnd ){
23134     if( *zNum=='-' ){
23135       neg = 1;
23136       zNum+=incr;
23137     }else if( *zNum=='+' ){
23138       zNum+=incr;
23139     }
23140   }
23141   zStart = zNum;
23142   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
23143   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
23144     u = u*10 + c - '0';
23145   }
23146   if( u>LARGEST_INT64 ){
23147     *pNum = SMALLEST_INT64;
23148   }else if( neg ){
23149     *pNum = -(i64)u;
23150   }else{
23151     *pNum = (i64)u;
23152   }
23153   testcase( i==18 );
23154   testcase( i==19 );
23155   testcase( i==20 );
23156   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
23157     /* zNum is empty or contains non-numeric text or is longer
23158     ** than 19 digits (thus guaranteeing that it is too large) */
23159     return 1;
23160   }else if( i<19*incr ){
23161     /* Less than 19 digits, so we know that it fits in 64 bits */
23162     assert( u<=LARGEST_INT64 );
23163     return 0;
23164   }else{
23165     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
23166     c = compare2pow63(zNum, incr);
23167     if( c<0 ){
23168       /* zNum is less than 9223372036854775808 so it fits */
23169       assert( u<=LARGEST_INT64 );
23170       return 0;
23171     }else if( c>0 ){
23172       /* zNum is greater than 9223372036854775808 so it overflows */
23173       return 1;
23174     }else{
23175       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
23176       ** special case 2 overflow if positive */
23177       assert( u-1==LARGEST_INT64 );
23178       assert( (*pNum)==SMALLEST_INT64 );
23179       return neg ? 0 : 2;
23180     }
23181   }
23182 }
23183
23184 /*
23185 ** If zNum represents an integer that will fit in 32-bits, then set
23186 ** *pValue to that integer and return true.  Otherwise return false.
23187 **
23188 ** Any non-numeric characters that following zNum are ignored.
23189 ** This is different from sqlcipher3Atoi64() which requires the
23190 ** input number to be zero-terminated.
23191 */
23192 SQLCIPHER_PRIVATE int sqlcipher3GetInt32(const char *zNum, int *pValue){
23193   sqlcipher_int64 v = 0;
23194   int i, c;
23195   int neg = 0;
23196   if( zNum[0]=='-' ){
23197     neg = 1;
23198     zNum++;
23199   }else if( zNum[0]=='+' ){
23200     zNum++;
23201   }
23202   while( zNum[0]=='0' ) zNum++;
23203   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
23204     v = v*10 + c;
23205   }
23206
23207   /* The longest decimal representation of a 32 bit integer is 10 digits:
23208   **
23209   **             1234567890
23210   **     2^31 -> 2147483648
23211   */
23212   testcase( i==10 );
23213   if( i>10 ){
23214     return 0;
23215   }
23216   testcase( v-neg==2147483647 );
23217   if( v-neg>2147483647 ){
23218     return 0;
23219   }
23220   if( neg ){
23221     v = -v;
23222   }
23223   *pValue = (int)v;
23224   return 1;
23225 }
23226
23227 /*
23228 ** Return a 32-bit integer value extracted from a string.  If the
23229 ** string is not an integer, just return 0.
23230 */
23231 SQLCIPHER_PRIVATE int sqlcipher3Atoi(const char *z){
23232   int x = 0;
23233   if( z ) sqlcipher3GetInt32(z, &x);
23234   return x;
23235 }
23236
23237 /*
23238 ** The variable-length integer encoding is as follows:
23239 **
23240 ** KEY:
23241 **         A = 0xxxxxxx    7 bits of data and one flag bit
23242 **         B = 1xxxxxxx    7 bits of data and one flag bit
23243 **         C = xxxxxxxx    8 bits of data
23244 **
23245 **  7 bits - A
23246 ** 14 bits - BA
23247 ** 21 bits - BBA
23248 ** 28 bits - BBBA
23249 ** 35 bits - BBBBA
23250 ** 42 bits - BBBBBA
23251 ** 49 bits - BBBBBBA
23252 ** 56 bits - BBBBBBBA
23253 ** 64 bits - BBBBBBBBC
23254 */
23255
23256 /*
23257 ** Write a 64-bit variable-length integer to memory starting at p[0].
23258 ** The length of data write will be between 1 and 9 bytes.  The number
23259 ** of bytes written is returned.
23260 **
23261 ** A variable-length integer consists of the lower 7 bits of each byte
23262 ** for all bytes that have the 8th bit set and one byte with the 8th
23263 ** bit clear.  Except, if we get to the 9th byte, it stores the full
23264 ** 8 bits and is the last byte.
23265 */
23266 SQLCIPHER_PRIVATE int sqlcipher3PutVarint(unsigned char *p, u64 v){
23267   int i, j, n;
23268   u8 buf[10];
23269   if( v & (((u64)0xff000000)<<32) ){
23270     p[8] = (u8)v;
23271     v >>= 8;
23272     for(i=7; i>=0; i--){
23273       p[i] = (u8)((v & 0x7f) | 0x80);
23274       v >>= 7;
23275     }
23276     return 9;
23277   }    
23278   n = 0;
23279   do{
23280     buf[n++] = (u8)((v & 0x7f) | 0x80);
23281     v >>= 7;
23282   }while( v!=0 );
23283   buf[0] &= 0x7f;
23284   assert( n<=9 );
23285   for(i=0, j=n-1; j>=0; j--, i++){
23286     p[i] = buf[j];
23287   }
23288   return n;
23289 }
23290
23291 /*
23292 ** This routine is a faster version of sqlcipher3PutVarint() that only
23293 ** works for 32-bit positive integers and which is optimized for
23294 ** the common case of small integers.  A MACRO version, putVarint32,
23295 ** is provided which inlines the single-byte case.  All code should use
23296 ** the MACRO version as this function assumes the single-byte case has
23297 ** already been handled.
23298 */
23299 SQLCIPHER_PRIVATE int sqlcipher3PutVarint32(unsigned char *p, u32 v){
23300 #ifndef putVarint32
23301   if( (v & ~0x7f)==0 ){
23302     p[0] = v;
23303     return 1;
23304   }
23305 #endif
23306   if( (v & ~0x3fff)==0 ){
23307     p[0] = (u8)((v>>7) | 0x80);
23308     p[1] = (u8)(v & 0x7f);
23309     return 2;
23310   }
23311   return sqlcipher3PutVarint(p, v);
23312 }
23313
23314 /*
23315 ** Bitmasks used by sqlcipher3GetVarint().  These precomputed constants
23316 ** are defined here rather than simply putting the constant expressions
23317 ** inline in order to work around bugs in the RVT compiler.
23318 **
23319 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
23320 **
23321 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
23322 */
23323 #define SLOT_2_0     0x001fc07f
23324 #define SLOT_4_2_0   0xf01fc07f
23325
23326
23327 /*
23328 ** Read a 64-bit variable-length integer from memory starting at p[0].
23329 ** Return the number of bytes read.  The value is stored in *v.
23330 */
23331 SQLCIPHER_PRIVATE u8 sqlcipher3GetVarint(const unsigned char *p, u64 *v){
23332   u32 a,b,s;
23333
23334   a = *p;
23335   /* a: p0 (unmasked) */
23336   if (!(a&0x80))
23337   {
23338     *v = a;
23339     return 1;
23340   }
23341
23342   p++;
23343   b = *p;
23344   /* b: p1 (unmasked) */
23345   if (!(b&0x80))
23346   {
23347     a &= 0x7f;
23348     a = a<<7;
23349     a |= b;
23350     *v = a;
23351     return 2;
23352   }
23353
23354   /* Verify that constants are precomputed correctly */
23355   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
23356   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
23357
23358   p++;
23359   a = a<<14;
23360   a |= *p;
23361   /* a: p0<<14 | p2 (unmasked) */
23362   if (!(a&0x80))
23363   {
23364     a &= SLOT_2_0;
23365     b &= 0x7f;
23366     b = b<<7;
23367     a |= b;
23368     *v = a;
23369     return 3;
23370   }
23371
23372   /* CSE1 from below */
23373   a &= SLOT_2_0;
23374   p++;
23375   b = b<<14;
23376   b |= *p;
23377   /* b: p1<<14 | p3 (unmasked) */
23378   if (!(b&0x80))
23379   {
23380     b &= SLOT_2_0;
23381     /* moved CSE1 up */
23382     /* a &= (0x7f<<14)|(0x7f); */
23383     a = a<<7;
23384     a |= b;
23385     *v = a;
23386     return 4;
23387   }
23388
23389   /* a: p0<<14 | p2 (masked) */
23390   /* b: p1<<14 | p3 (unmasked) */
23391   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23392   /* moved CSE1 up */
23393   /* a &= (0x7f<<14)|(0x7f); */
23394   b &= SLOT_2_0;
23395   s = a;
23396   /* s: p0<<14 | p2 (masked) */
23397
23398   p++;
23399   a = a<<14;
23400   a |= *p;
23401   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
23402   if (!(a&0x80))
23403   {
23404     /* we can skip these cause they were (effectively) done above in calc'ing s */
23405     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
23406     /* b &= (0x7f<<14)|(0x7f); */
23407     b = b<<7;
23408     a |= b;
23409     s = s>>18;
23410     *v = ((u64)s)<<32 | a;
23411     return 5;
23412   }
23413
23414   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23415   s = s<<7;
23416   s |= b;
23417   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23418
23419   p++;
23420   b = b<<14;
23421   b |= *p;
23422   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
23423   if (!(b&0x80))
23424   {
23425     /* we can skip this cause it was (effectively) done above in calc'ing s */
23426     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
23427     a &= SLOT_2_0;
23428     a = a<<7;
23429     a |= b;
23430     s = s>>18;
23431     *v = ((u64)s)<<32 | a;
23432     return 6;
23433   }
23434
23435   p++;
23436   a = a<<14;
23437   a |= *p;
23438   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
23439   if (!(a&0x80))
23440   {
23441     a &= SLOT_4_2_0;
23442     b &= SLOT_2_0;
23443     b = b<<7;
23444     a |= b;
23445     s = s>>11;
23446     *v = ((u64)s)<<32 | a;
23447     return 7;
23448   }
23449
23450   /* CSE2 from below */
23451   a &= SLOT_2_0;
23452   p++;
23453   b = b<<14;
23454   b |= *p;
23455   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
23456   if (!(b&0x80))
23457   {
23458     b &= SLOT_4_2_0;
23459     /* moved CSE2 up */
23460     /* a &= (0x7f<<14)|(0x7f); */
23461     a = a<<7;
23462     a |= b;
23463     s = s>>4;
23464     *v = ((u64)s)<<32 | a;
23465     return 8;
23466   }
23467
23468   p++;
23469   a = a<<15;
23470   a |= *p;
23471   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
23472
23473   /* moved CSE2 up */
23474   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
23475   b &= SLOT_2_0;
23476   b = b<<8;
23477   a |= b;
23478
23479   s = s<<4;
23480   b = p[-4];
23481   b &= 0x7f;
23482   b = b>>3;
23483   s |= b;
23484
23485   *v = ((u64)s)<<32 | a;
23486
23487   return 9;
23488 }
23489
23490 /*
23491 ** Read a 32-bit variable-length integer from memory starting at p[0].
23492 ** Return the number of bytes read.  The value is stored in *v.
23493 **
23494 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
23495 ** integer, then set *v to 0xffffffff.
23496 **
23497 ** A MACRO version, getVarint32, is provided which inlines the 
23498 ** single-byte case.  All code should use the MACRO version as 
23499 ** this function assumes the single-byte case has already been handled.
23500 */
23501 SQLCIPHER_PRIVATE u8 sqlcipher3GetVarint32(const unsigned char *p, u32 *v){
23502   u32 a,b;
23503
23504   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
23505   ** by the getVarin32() macro */
23506   a = *p;
23507   /* a: p0 (unmasked) */
23508 #ifndef getVarint32
23509   if (!(a&0x80))
23510   {
23511     /* Values between 0 and 127 */
23512     *v = a;
23513     return 1;
23514   }
23515 #endif
23516
23517   /* The 2-byte case */
23518   p++;
23519   b = *p;
23520   /* b: p1 (unmasked) */
23521   if (!(b&0x80))
23522   {
23523     /* Values between 128 and 16383 */
23524     a &= 0x7f;
23525     a = a<<7;
23526     *v = a | b;
23527     return 2;
23528   }
23529
23530   /* The 3-byte case */
23531   p++;
23532   a = a<<14;
23533   a |= *p;
23534   /* a: p0<<14 | p2 (unmasked) */
23535   if (!(a&0x80))
23536   {
23537     /* Values between 16384 and 2097151 */
23538     a &= (0x7f<<14)|(0x7f);
23539     b &= 0x7f;
23540     b = b<<7;
23541     *v = a | b;
23542     return 3;
23543   }
23544
23545   /* A 32-bit varint is used to store size information in btrees.
23546   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
23547   ** A 3-byte varint is sufficient, for example, to record the size
23548   ** of a 1048569-byte BLOB or string.
23549   **
23550   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
23551   ** rare larger cases can be handled by the slower 64-bit varint
23552   ** routine.
23553   */
23554 #if 1
23555   {
23556     u64 v64;
23557     u8 n;
23558
23559     p -= 2;
23560     n = sqlcipher3GetVarint(p, &v64);
23561     assert( n>3 && n<=9 );
23562     if( (v64 & SQLCIPHER_MAX_U32)!=v64 ){
23563       *v = 0xffffffff;
23564     }else{
23565       *v = (u32)v64;
23566     }
23567     return n;
23568   }
23569
23570 #else
23571   /* For following code (kept for historical record only) shows an
23572   ** unrolling for the 3- and 4-byte varint cases.  This code is
23573   ** slightly faster, but it is also larger and much harder to test.
23574   */
23575   p++;
23576   b = b<<14;
23577   b |= *p;
23578   /* b: p1<<14 | p3 (unmasked) */
23579   if (!(b&0x80))
23580   {
23581     /* Values between 2097152 and 268435455 */
23582     b &= (0x7f<<14)|(0x7f);
23583     a &= (0x7f<<14)|(0x7f);
23584     a = a<<7;
23585     *v = a | b;
23586     return 4;
23587   }
23588
23589   p++;
23590   a = a<<14;
23591   a |= *p;
23592   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
23593   if (!(a&0x80))
23594   {
23595     /* Values  between 268435456 and 34359738367 */
23596     a &= SLOT_4_2_0;
23597     b &= SLOT_4_2_0;
23598     b = b<<7;
23599     *v = a | b;
23600     return 5;
23601   }
23602
23603   /* We can only reach this point when reading a corrupt database
23604   ** file.  In that case we are not in any hurry.  Use the (relatively
23605   ** slow) general-purpose sqlcipher3GetVarint() routine to extract the
23606   ** value. */
23607   {
23608     u64 v64;
23609     u8 n;
23610
23611     p -= 4;
23612     n = sqlcipher3GetVarint(p, &v64);
23613     assert( n>5 && n<=9 );
23614     *v = (u32)v64;
23615     return n;
23616   }
23617 #endif
23618 }
23619
23620 /*
23621 ** Return the number of bytes that will be needed to store the given
23622 ** 64-bit integer.
23623 */
23624 SQLCIPHER_PRIVATE int sqlcipher3VarintLen(u64 v){
23625   int i = 0;
23626   do{
23627     i++;
23628     v >>= 7;
23629   }while( v!=0 && ALWAYS(i<9) );
23630   return i;
23631 }
23632
23633
23634 /*
23635 ** Read or write a four-byte big-endian integer value.
23636 */
23637 SQLCIPHER_PRIVATE u32 sqlcipher3Get4byte(const u8 *p){
23638   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
23639 }
23640 SQLCIPHER_PRIVATE void sqlcipher3Put4byte(unsigned char *p, u32 v){
23641   p[0] = (u8)(v>>24);
23642   p[1] = (u8)(v>>16);
23643   p[2] = (u8)(v>>8);
23644   p[3] = (u8)v;
23645 }
23646
23647
23648
23649 /*
23650 ** Translate a single byte of Hex into an integer.
23651 ** This routine only works if h really is a valid hexadecimal
23652 ** character:  0..9a..fA..F
23653 */
23654 SQLCIPHER_PRIVATE u8 sqlcipher3HexToInt(int h){
23655   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
23656 #ifdef SQLCIPHER_ASCII
23657   h += 9*(1&(h>>6));
23658 #endif
23659 #ifdef SQLCIPHER_EBCDIC
23660   h += 9*(1&~(h>>4));
23661 #endif
23662   return (u8)(h & 0xf);
23663 }
23664
23665 #if !defined(SQLCIPHER_OMIT_BLOB_LITERAL) || defined(SQLCIPHER_HAS_CODEC)
23666 /*
23667 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
23668 ** value.  Return a pointer to its binary value.  Space to hold the
23669 ** binary value has been obtained from malloc and must be freed by
23670 ** the calling routine.
23671 */
23672 SQLCIPHER_PRIVATE void *sqlcipher3HexToBlob(sqlcipher3 *db, const char *z, int n){
23673   char *zBlob;
23674   int i;
23675
23676   zBlob = (char *)sqlcipher3DbMallocRaw(db, n/2 + 1);
23677   n--;
23678   if( zBlob ){
23679     for(i=0; i<n; i+=2){
23680       zBlob[i/2] = (sqlcipher3HexToInt(z[i])<<4) | sqlcipher3HexToInt(z[i+1]);
23681     }
23682     zBlob[i/2] = 0;
23683   }
23684   return zBlob;
23685 }
23686 #endif /* !SQLCIPHER_OMIT_BLOB_LITERAL || SQLCIPHER_HAS_CODEC */
23687
23688 /*
23689 ** Log an error that is an API call on a connection pointer that should
23690 ** not have been used.  The "type" of connection pointer is given as the
23691 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
23692 */
23693 static void logBadConnection(const char *zType){
23694   sqlcipher3_log(SQLCIPHER_MISUSE, 
23695      "API call with %s database connection pointer",
23696      zType
23697   );
23698 }
23699
23700 /*
23701 ** Check to make sure we have a valid db pointer.  This test is not
23702 ** foolproof but it does provide some measure of protection against
23703 ** misuse of the interface such as passing in db pointers that are
23704 ** NULL or which have been previously closed.  If this routine returns
23705 ** 1 it means that the db pointer is valid and 0 if it should not be
23706 ** dereferenced for any reason.  The calling function should invoke
23707 ** SQLCIPHER_MISUSE immediately.
23708 **
23709 ** sqlcipher3SafetyCheckOk() requires that the db pointer be valid for
23710 ** use.  sqlcipher3SafetyCheckSickOrOk() allows a db pointer that failed to
23711 ** open properly and is not fit for general use but which can be
23712 ** used as an argument to sqlcipher3_errmsg() or sqlcipher3_close().
23713 */
23714 SQLCIPHER_PRIVATE int sqlcipher3SafetyCheckOk(sqlcipher3 *db){
23715   u32 magic;
23716   if( db==0 ){
23717     logBadConnection("NULL");
23718     return 0;
23719   }
23720   magic = db->magic;
23721   if( magic!=SQLCIPHER_MAGIC_OPEN ){
23722     if( sqlcipher3SafetyCheckSickOrOk(db) ){
23723       testcase( sqlcipher3GlobalConfig.xLog!=0 );
23724       logBadConnection("unopened");
23725     }
23726     return 0;
23727   }else{
23728     return 1;
23729   }
23730 }
23731 SQLCIPHER_PRIVATE int sqlcipher3SafetyCheckSickOrOk(sqlcipher3 *db){
23732   u32 magic;
23733   magic = db->magic;
23734   if( magic!=SQLCIPHER_MAGIC_SICK &&
23735       magic!=SQLCIPHER_MAGIC_OPEN &&
23736       magic!=SQLCIPHER_MAGIC_BUSY ){
23737     testcase( sqlcipher3GlobalConfig.xLog!=0 );
23738     logBadConnection("invalid");
23739     return 0;
23740   }else{
23741     return 1;
23742   }
23743 }
23744
23745 /*
23746 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
23747 ** the other 64-bit signed integer at *pA and store the result in *pA.
23748 ** Return 0 on success.  Or if the operation would have resulted in an
23749 ** overflow, leave *pA unchanged and return 1.
23750 */
23751 SQLCIPHER_PRIVATE int sqlcipher3AddInt64(i64 *pA, i64 iB){
23752   i64 iA = *pA;
23753   testcase( iA==0 ); testcase( iA==1 );
23754   testcase( iB==-1 ); testcase( iB==0 );
23755   if( iB>=0 ){
23756     testcase( iA>0 && LARGEST_INT64 - iA == iB );
23757     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
23758     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
23759     *pA += iB;
23760   }else{
23761     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
23762     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
23763     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
23764     *pA += iB;
23765   }
23766   return 0; 
23767 }
23768 SQLCIPHER_PRIVATE int sqlcipher3SubInt64(i64 *pA, i64 iB){
23769   testcase( iB==SMALLEST_INT64+1 );
23770   if( iB==SMALLEST_INT64 ){
23771     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
23772     if( (*pA)>=0 ) return 1;
23773     *pA -= iB;
23774     return 0;
23775   }else{
23776     return sqlcipher3AddInt64(pA, -iB);
23777   }
23778 }
23779 #define TWOPOWER32 (((i64)1)<<32)
23780 #define TWOPOWER31 (((i64)1)<<31)
23781 SQLCIPHER_PRIVATE int sqlcipher3MulInt64(i64 *pA, i64 iB){
23782   i64 iA = *pA;
23783   i64 iA1, iA0, iB1, iB0, r;
23784
23785   iA1 = iA/TWOPOWER32;
23786   iA0 = iA % TWOPOWER32;
23787   iB1 = iB/TWOPOWER32;
23788   iB0 = iB % TWOPOWER32;
23789   if( iA1*iB1 != 0 ) return 1;
23790   assert( iA1*iB0==0 || iA0*iB1==0 );
23791   r = iA1*iB0 + iA0*iB1;
23792   testcase( r==(-TWOPOWER31)-1 );
23793   testcase( r==(-TWOPOWER31) );
23794   testcase( r==TWOPOWER31 );
23795   testcase( r==TWOPOWER31-1 );
23796   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
23797   r *= TWOPOWER32;
23798   if( sqlcipher3AddInt64(&r, iA0*iB0) ) return 1;
23799   *pA = r;
23800   return 0;
23801 }
23802
23803 /*
23804 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
23805 ** if the integer has a value of -2147483648, return +2147483647
23806 */
23807 SQLCIPHER_PRIVATE int sqlcipher3AbsInt32(int x){
23808   if( x>=0 ) return x;
23809   if( x==(int)0x80000000 ) return 0x7fffffff;
23810   return -x;
23811 }
23812
23813 #ifdef SQLCIPHER_ENABLE_8_3_NAMES
23814 /*
23815 ** If SQLCIPHER_ENABLE_8_3_NAMES is set at compile-time and if the database
23816 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
23817 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
23818 ** three characters, then shorten the suffix on z[] to be the last three
23819 ** characters of the original suffix.
23820 **
23821 ** If SQLCIPHER_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
23822 ** do the suffix shortening regardless of URI parameter.
23823 **
23824 ** Examples:
23825 **
23826 **     test.db-journal    =>   test.nal
23827 **     test.db-wal        =>   test.wal
23828 **     test.db-shm        =>   test.shm
23829 */
23830 SQLCIPHER_PRIVATE void sqlcipher3FileSuffix3(const char *zBaseFilename, char *z){
23831 #if SQLCIPHER_ENABLE_8_3_NAMES<2
23832   const char *zOk;
23833   zOk = sqlcipher3_uri_parameter(zBaseFilename, "8_3_names");
23834   if( zOk && sqlcipher3GetBoolean(zOk) )
23835 #endif
23836   {
23837     int i, sz;
23838     sz = sqlcipher3Strlen30(z);
23839     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
23840     if( z[i]=='.' && ALWAYS(sz>i+4) ) memcpy(&z[i+1], &z[sz-3], 4);
23841   }
23842 }
23843 #endif
23844
23845 /************** End of util.c ************************************************/
23846 /************** Begin file hash.c ********************************************/
23847 /*
23848 ** 2001 September 22
23849 **
23850 ** The author disclaims copyright to this source code.  In place of
23851 ** a legal notice, here is a blessing:
23852 **
23853 **    May you do good and not evil.
23854 **    May you find forgiveness for yourself and forgive others.
23855 **    May you share freely, never taking more than you give.
23856 **
23857 *************************************************************************
23858 ** This is the implementation of generic hash-tables
23859 ** used in SQLite.
23860 */
23861 /* #include <assert.h> */
23862
23863 /* Turn bulk memory into a hash table object by initializing the
23864 ** fields of the Hash structure.
23865 **
23866 ** "pNew" is a pointer to the hash table that is to be initialized.
23867 */
23868 SQLCIPHER_PRIVATE void sqlcipher3HashInit(Hash *pNew){
23869   assert( pNew!=0 );
23870   pNew->first = 0;
23871   pNew->count = 0;
23872   pNew->htsize = 0;
23873   pNew->ht = 0;
23874 }
23875
23876 /* Remove all entries from a hash table.  Reclaim all memory.
23877 ** Call this routine to delete a hash table or to reset a hash table
23878 ** to the empty state.
23879 */
23880 SQLCIPHER_PRIVATE void sqlcipher3HashClear(Hash *pH){
23881   HashElem *elem;         /* For looping over all elements of the table */
23882
23883   assert( pH!=0 );
23884   elem = pH->first;
23885   pH->first = 0;
23886   sqlcipher3_free(pH->ht);
23887   pH->ht = 0;
23888   pH->htsize = 0;
23889   while( elem ){
23890     HashElem *next_elem = elem->next;
23891     sqlcipher3_free(elem);
23892     elem = next_elem;
23893   }
23894   pH->count = 0;
23895 }
23896
23897 /*
23898 ** The hashing function.
23899 */
23900 static unsigned int strHash(const char *z, int nKey){
23901   int h = 0;
23902   assert( nKey>=0 );
23903   while( nKey > 0  ){
23904     h = (h<<3) ^ h ^ sqlcipher3UpperToLower[(unsigned char)*z++];
23905     nKey--;
23906   }
23907   return h;
23908 }
23909
23910
23911 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
23912 ** insert pNew into the pEntry hash bucket.
23913 */
23914 static void insertElement(
23915   Hash *pH,              /* The complete hash table */
23916   struct _ht *pEntry,    /* The entry into which pNew is inserted */
23917   HashElem *pNew         /* The element to be inserted */
23918 ){
23919   HashElem *pHead;       /* First element already in pEntry */
23920   if( pEntry ){
23921     pHead = pEntry->count ? pEntry->chain : 0;
23922     pEntry->count++;
23923     pEntry->chain = pNew;
23924   }else{
23925     pHead = 0;
23926   }
23927   if( pHead ){
23928     pNew->next = pHead;
23929     pNew->prev = pHead->prev;
23930     if( pHead->prev ){ pHead->prev->next = pNew; }
23931     else             { pH->first = pNew; }
23932     pHead->prev = pNew;
23933   }else{
23934     pNew->next = pH->first;
23935     if( pH->first ){ pH->first->prev = pNew; }
23936     pNew->prev = 0;
23937     pH->first = pNew;
23938   }
23939 }
23940
23941
23942 /* Resize the hash table so that it cantains "new_size" buckets.
23943 **
23944 ** The hash table might fail to resize if sqlcipher3_malloc() fails or
23945 ** if the new size is the same as the prior size.
23946 ** Return TRUE if the resize occurs and false if not.
23947 */
23948 static int rehash(Hash *pH, unsigned int new_size){
23949   struct _ht *new_ht;            /* The new hash table */
23950   HashElem *elem, *next_elem;    /* For looping over existing elements */
23951
23952 #if SQLCIPHER_MALLOC_SOFT_LIMIT>0
23953   if( new_size*sizeof(struct _ht)>SQLCIPHER_MALLOC_SOFT_LIMIT ){
23954     new_size = SQLCIPHER_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
23955   }
23956   if( new_size==pH->htsize ) return 0;
23957 #endif
23958
23959   /* The inability to allocates space for a larger hash table is
23960   ** a performance hit but it is not a fatal error.  So mark the
23961   ** allocation as a benign.
23962   */
23963   sqlcipher3BeginBenignMalloc();
23964   new_ht = (struct _ht *)sqlcipher3Malloc( new_size*sizeof(struct _ht) );
23965   sqlcipher3EndBenignMalloc();
23966
23967   if( new_ht==0 ) return 0;
23968   sqlcipher3_free(pH->ht);
23969   pH->ht = new_ht;
23970   pH->htsize = new_size = sqlcipher3MallocSize(new_ht)/sizeof(struct _ht);
23971   memset(new_ht, 0, new_size*sizeof(struct _ht));
23972   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
23973     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
23974     next_elem = elem->next;
23975     insertElement(pH, &new_ht[h], elem);
23976   }
23977   return 1;
23978 }
23979
23980 /* This function (for internal use only) locates an element in an
23981 ** hash table that matches the given key.  The hash for this key has
23982 ** already been computed and is passed as the 4th parameter.
23983 */
23984 static HashElem *findElementGivenHash(
23985   const Hash *pH,     /* The pH to be searched */
23986   const char *pKey,   /* The key we are searching for */
23987   int nKey,           /* Bytes in key (not counting zero terminator) */
23988   unsigned int h      /* The hash for this key. */
23989 ){
23990   HashElem *elem;                /* Used to loop thru the element list */
23991   int count;                     /* Number of elements left to test */
23992
23993   if( pH->ht ){
23994     struct _ht *pEntry = &pH->ht[h];
23995     elem = pEntry->chain;
23996     count = pEntry->count;
23997   }else{
23998     elem = pH->first;
23999     count = pH->count;
24000   }
24001   while( count-- && ALWAYS(elem) ){
24002     if( elem->nKey==nKey && sqlcipher3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
24003       return elem;
24004     }
24005     elem = elem->next;
24006   }
24007   return 0;
24008 }
24009
24010 /* Remove a single entry from the hash table given a pointer to that
24011 ** element and a hash on the element's key.
24012 */
24013 static void removeElementGivenHash(
24014   Hash *pH,         /* The pH containing "elem" */
24015   HashElem* elem,   /* The element to be removed from the pH */
24016   unsigned int h    /* Hash value for the element */
24017 ){
24018   struct _ht *pEntry;
24019   if( elem->prev ){
24020     elem->prev->next = elem->next; 
24021   }else{
24022     pH->first = elem->next;
24023   }
24024   if( elem->next ){
24025     elem->next->prev = elem->prev;
24026   }
24027   if( pH->ht ){
24028     pEntry = &pH->ht[h];
24029     if( pEntry->chain==elem ){
24030       pEntry->chain = elem->next;
24031     }
24032     pEntry->count--;
24033     assert( pEntry->count>=0 );
24034   }
24035   sqlcipher3_free( elem );
24036   pH->count--;
24037   if( pH->count<=0 ){
24038     assert( pH->first==0 );
24039     assert( pH->count==0 );
24040     sqlcipher3HashClear(pH);
24041   }
24042 }
24043
24044 /* Attempt to locate an element of the hash table pH with a key
24045 ** that matches pKey,nKey.  Return the data for this element if it is
24046 ** found, or NULL if there is no match.
24047 */
24048 SQLCIPHER_PRIVATE void *sqlcipher3HashFind(const Hash *pH, const char *pKey, int nKey){
24049   HashElem *elem;    /* The element that matches key */
24050   unsigned int h;    /* A hash on key */
24051
24052   assert( pH!=0 );
24053   assert( pKey!=0 );
24054   assert( nKey>=0 );
24055   if( pH->ht ){
24056     h = strHash(pKey, nKey) % pH->htsize;
24057   }else{
24058     h = 0;
24059   }
24060   elem = findElementGivenHash(pH, pKey, nKey, h);
24061   return elem ? elem->data : 0;
24062 }
24063
24064 /* Insert an element into the hash table pH.  The key is pKey,nKey
24065 ** and the data is "data".
24066 **
24067 ** If no element exists with a matching key, then a new
24068 ** element is created and NULL is returned.
24069 **
24070 ** If another element already exists with the same key, then the
24071 ** new data replaces the old data and the old data is returned.
24072 ** The key is not copied in this instance.  If a malloc fails, then
24073 ** the new data is returned and the hash table is unchanged.
24074 **
24075 ** If the "data" parameter to this function is NULL, then the
24076 ** element corresponding to "key" is removed from the hash table.
24077 */
24078 SQLCIPHER_PRIVATE void *sqlcipher3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
24079   unsigned int h;       /* the hash of the key modulo hash table size */
24080   HashElem *elem;       /* Used to loop thru the element list */
24081   HashElem *new_elem;   /* New element added to the pH */
24082
24083   assert( pH!=0 );
24084   assert( pKey!=0 );
24085   assert( nKey>=0 );
24086   if( pH->htsize ){
24087     h = strHash(pKey, nKey) % pH->htsize;
24088   }else{
24089     h = 0;
24090   }
24091   elem = findElementGivenHash(pH,pKey,nKey,h);
24092   if( elem ){
24093     void *old_data = elem->data;
24094     if( data==0 ){
24095       removeElementGivenHash(pH,elem,h);
24096     }else{
24097       elem->data = data;
24098       elem->pKey = pKey;
24099       assert(nKey==elem->nKey);
24100     }
24101     return old_data;
24102   }
24103   if( data==0 ) return 0;
24104   new_elem = (HashElem*)sqlcipher3Malloc( sizeof(HashElem) );
24105   if( new_elem==0 ) return data;
24106   new_elem->pKey = pKey;
24107   new_elem->nKey = nKey;
24108   new_elem->data = data;
24109   pH->count++;
24110   if( pH->count>=10 && pH->count > 2*pH->htsize ){
24111     if( rehash(pH, pH->count*2) ){
24112       assert( pH->htsize>0 );
24113       h = strHash(pKey, nKey) % pH->htsize;
24114     }
24115   }
24116   if( pH->ht ){
24117     insertElement(pH, &pH->ht[h], new_elem);
24118   }else{
24119     insertElement(pH, 0, new_elem);
24120   }
24121   return 0;
24122 }
24123
24124 /************** End of hash.c ************************************************/
24125 /************** Begin file opcodes.c *****************************************/
24126 /* Automatically generated.  Do not edit */
24127 /* See the mkopcodec.awk script for details. */
24128 #if !defined(SQLCIPHER_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLCIPHER_DEBUG)
24129 SQLCIPHER_PRIVATE const char *sqlcipher3OpcodeName(int i){
24130  static const char *const azName[] = { "?",
24131      /*   1 */ "Goto",
24132      /*   2 */ "Gosub",
24133      /*   3 */ "Return",
24134      /*   4 */ "Yield",
24135      /*   5 */ "HaltIfNull",
24136      /*   6 */ "Halt",
24137      /*   7 */ "Integer",
24138      /*   8 */ "Int64",
24139      /*   9 */ "String",
24140      /*  10 */ "Null",
24141      /*  11 */ "Blob",
24142      /*  12 */ "Variable",
24143      /*  13 */ "Move",
24144      /*  14 */ "Copy",
24145      /*  15 */ "SCopy",
24146      /*  16 */ "ResultRow",
24147      /*  17 */ "CollSeq",
24148      /*  18 */ "Function",
24149      /*  19 */ "Not",
24150      /*  20 */ "AddImm",
24151      /*  21 */ "MustBeInt",
24152      /*  22 */ "RealAffinity",
24153      /*  23 */ "Permutation",
24154      /*  24 */ "Compare",
24155      /*  25 */ "Jump",
24156      /*  26 */ "Once",
24157      /*  27 */ "If",
24158      /*  28 */ "IfNot",
24159      /*  29 */ "Column",
24160      /*  30 */ "Affinity",
24161      /*  31 */ "MakeRecord",
24162      /*  32 */ "Count",
24163      /*  33 */ "Savepoint",
24164      /*  34 */ "AutoCommit",
24165      /*  35 */ "Transaction",
24166      /*  36 */ "ReadCookie",
24167      /*  37 */ "SetCookie",
24168      /*  38 */ "VerifyCookie",
24169      /*  39 */ "OpenRead",
24170      /*  40 */ "OpenWrite",
24171      /*  41 */ "OpenAutoindex",
24172      /*  42 */ "OpenEphemeral",
24173      /*  43 */ "SorterOpen",
24174      /*  44 */ "OpenPseudo",
24175      /*  45 */ "Close",
24176      /*  46 */ "SeekLt",
24177      /*  47 */ "SeekLe",
24178      /*  48 */ "SeekGe",
24179      /*  49 */ "SeekGt",
24180      /*  50 */ "Seek",
24181      /*  51 */ "NotFound",
24182      /*  52 */ "Found",
24183      /*  53 */ "IsUnique",
24184      /*  54 */ "NotExists",
24185      /*  55 */ "Sequence",
24186      /*  56 */ "NewRowid",
24187      /*  57 */ "Insert",
24188      /*  58 */ "InsertInt",
24189      /*  59 */ "Delete",
24190      /*  60 */ "ResetCount",
24191      /*  61 */ "SorterCompare",
24192      /*  62 */ "SorterData",
24193      /*  63 */ "RowKey",
24194      /*  64 */ "RowData",
24195      /*  65 */ "Rowid",
24196      /*  66 */ "NullRow",
24197      /*  67 */ "Last",
24198      /*  68 */ "Or",
24199      /*  69 */ "And",
24200      /*  70 */ "SorterSort",
24201      /*  71 */ "Sort",
24202      /*  72 */ "Rewind",
24203      /*  73 */ "IsNull",
24204      /*  74 */ "NotNull",
24205      /*  75 */ "Ne",
24206      /*  76 */ "Eq",
24207      /*  77 */ "Gt",
24208      /*  78 */ "Le",
24209      /*  79 */ "Lt",
24210      /*  80 */ "Ge",
24211      /*  81 */ "SorterNext",
24212      /*  82 */ "BitAnd",
24213      /*  83 */ "BitOr",
24214      /*  84 */ "ShiftLeft",
24215      /*  85 */ "ShiftRight",
24216      /*  86 */ "Add",
24217      /*  87 */ "Subtract",
24218      /*  88 */ "Multiply",
24219      /*  89 */ "Divide",
24220      /*  90 */ "Remainder",
24221      /*  91 */ "Concat",
24222      /*  92 */ "Prev",
24223      /*  93 */ "BitNot",
24224      /*  94 */ "String8",
24225      /*  95 */ "Next",
24226      /*  96 */ "SorterInsert",
24227      /*  97 */ "IdxInsert",
24228      /*  98 */ "IdxDelete",
24229      /*  99 */ "IdxRowid",
24230      /* 100 */ "IdxLT",
24231      /* 101 */ "IdxGE",
24232      /* 102 */ "Destroy",
24233      /* 103 */ "Clear",
24234      /* 104 */ "CreateIndex",
24235      /* 105 */ "CreateTable",
24236      /* 106 */ "ParseSchema",
24237      /* 107 */ "LoadAnalysis",
24238      /* 108 */ "DropTable",
24239      /* 109 */ "DropIndex",
24240      /* 110 */ "DropTrigger",
24241      /* 111 */ "IntegrityCk",
24242      /* 112 */ "RowSetAdd",
24243      /* 113 */ "RowSetRead",
24244      /* 114 */ "RowSetTest",
24245      /* 115 */ "Program",
24246      /* 116 */ "Param",
24247      /* 117 */ "FkCounter",
24248      /* 118 */ "FkIfZero",
24249      /* 119 */ "MemMax",
24250      /* 120 */ "IfPos",
24251      /* 121 */ "IfNeg",
24252      /* 122 */ "IfZero",
24253      /* 123 */ "AggStep",
24254      /* 124 */ "AggFinal",
24255      /* 125 */ "Checkpoint",
24256      /* 126 */ "JournalMode",
24257      /* 127 */ "Vacuum",
24258      /* 128 */ "IncrVacuum",
24259      /* 129 */ "Expire",
24260      /* 130 */ "Real",
24261      /* 131 */ "TableLock",
24262      /* 132 */ "VBegin",
24263      /* 133 */ "VCreate",
24264      /* 134 */ "VDestroy",
24265      /* 135 */ "VOpen",
24266      /* 136 */ "VFilter",
24267      /* 137 */ "VColumn",
24268      /* 138 */ "VNext",
24269      /* 139 */ "VRename",
24270      /* 140 */ "VUpdate",
24271      /* 141 */ "ToText",
24272      /* 142 */ "ToBlob",
24273      /* 143 */ "ToNumeric",
24274      /* 144 */ "ToInt",
24275      /* 145 */ "ToReal",
24276      /* 146 */ "Pagecount",
24277      /* 147 */ "MaxPgcnt",
24278      /* 148 */ "Trace",
24279      /* 149 */ "Noop",
24280      /* 150 */ "Explain",
24281   };
24282   return azName[i];
24283 }
24284 #endif
24285
24286 /************** End of opcodes.c *********************************************/
24287 /************** Begin file os_os2.c ******************************************/
24288 /*
24289 ** 2006 Feb 14
24290 **
24291 ** The author disclaims copyright to this source code.  In place of
24292 ** a legal notice, here is a blessing:
24293 **
24294 **    May you do good and not evil.
24295 **    May you find forgiveness for yourself and forgive others.
24296 **    May you share freely, never taking more than you give.
24297 **
24298 ******************************************************************************
24299 **
24300 ** This file contains code that is specific to OS/2.
24301 */
24302
24303
24304 #if SQLCIPHER_OS_OS2
24305
24306 /*
24307 ** A Note About Memory Allocation:
24308 **
24309 ** This driver uses malloc()/free() directly rather than going through
24310 ** the SQLite-wrappers sqlcipher3_malloc()/sqlcipher3_free().  Those wrappers
24311 ** are designed for use on embedded systems where memory is scarce and
24312 ** malloc failures happen frequently.  OS/2 does not typically run on
24313 ** embedded systems, and when it does the developers normally have bigger
24314 ** problems to worry about than running out of memory.  So there is not
24315 ** a compelling need to use the wrappers.
24316 **
24317 ** But there is a good reason to not use the wrappers.  If we use the
24318 ** wrappers then we will get simulated malloc() failures within this
24319 ** driver.  And that causes all kinds of problems for our tests.  We
24320 ** could enhance SQLite to deal with simulated malloc failures within
24321 ** the OS driver, but the code to deal with those failure would not
24322 ** be exercised on Linux (which does not need to malloc() in the driver)
24323 ** and so we would have difficulty writing coverage tests for that
24324 ** code.  Better to leave the code out, we think.
24325 **
24326 ** The point of this discussion is as follows:  When creating a new
24327 ** OS layer for an embedded system, if you use this file as an example,
24328 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
24329 ** desktops but not so well in embedded systems.
24330 */
24331
24332 /*
24333 ** Macros used to determine whether or not to use threads.
24334 */
24335 #if defined(SQLCIPHER_THREADSAFE) && SQLCIPHER_THREADSAFE
24336 # define SQLCIPHER_OS2_THREADS 1
24337 #endif
24338
24339 /*
24340 ** Include code that is common to all os_*.c files
24341 */
24342 /************** Include os_common.h in the middle of os_os2.c ****************/
24343 /************** Begin file os_common.h ***************************************/
24344 /*
24345 ** 2004 May 22
24346 **
24347 ** The author disclaims copyright to this source code.  In place of
24348 ** a legal notice, here is a blessing:
24349 **
24350 **    May you do good and not evil.
24351 **    May you find forgiveness for yourself and forgive others.
24352 **    May you share freely, never taking more than you give.
24353 **
24354 ******************************************************************************
24355 **
24356 ** This file contains macros and a little bit of code that is common to
24357 ** all of the platform-specific files (os_*.c) and is #included into those
24358 ** files.
24359 **
24360 ** This file should be #included by the os_*.c files only.  It is not a
24361 ** general purpose header file.
24362 */
24363 #ifndef _OS_COMMON_H_
24364 #define _OS_COMMON_H_
24365
24366 /*
24367 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24368 ** macro to SQLCIPHER_DEBUG and some older makefiles have not yet made the
24369 ** switch.  The following code should catch this problem at compile-time.
24370 */
24371 #ifdef MEMORY_DEBUG
24372 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLCIPHER_DEBUG instead."
24373 #endif
24374
24375 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
24376 # ifndef SQLCIPHER_DEBUG_OS_TRACE
24377 #   define SQLCIPHER_DEBUG_OS_TRACE 0
24378 # endif
24379   int sqlcipher3OSTrace = SQLCIPHER_DEBUG_OS_TRACE;
24380 # define OSTRACE(X)          if( sqlcipher3OSTrace ) sqlcipher3DebugPrintf X
24381 #else
24382 # define OSTRACE(X)
24383 #endif
24384
24385 /*
24386 ** Macros for performance tracing.  Normally turned off.  Only works
24387 ** on i486 hardware.
24388 */
24389 #ifdef SQLCIPHER_PERFORMANCE_TRACE
24390
24391 /* 
24392 ** hwtime.h contains inline assembler code for implementing 
24393 ** high-performance timing routines.
24394 */
24395 /************** Include hwtime.h in the middle of os_common.h ****************/
24396 /************** Begin file hwtime.h ******************************************/
24397 /*
24398 ** 2008 May 27
24399 **
24400 ** The author disclaims copyright to this source code.  In place of
24401 ** a legal notice, here is a blessing:
24402 **
24403 **    May you do good and not evil.
24404 **    May you find forgiveness for yourself and forgive others.
24405 **    May you share freely, never taking more than you give.
24406 **
24407 ******************************************************************************
24408 **
24409 ** This file contains inline asm code for retrieving "high-performance"
24410 ** counters for x86 class CPUs.
24411 */
24412 #ifndef _HWTIME_H_
24413 #define _HWTIME_H_
24414
24415 /*
24416 ** The following routine only works on pentium-class (or newer) processors.
24417 ** It uses the RDTSC opcode to read the cycle count value out of the
24418 ** processor and returns that value.  This can be used for high-res
24419 ** profiling.
24420 */
24421 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24422       (defined(i386) || defined(__i386__) || defined(_M_IX86))
24423
24424   #if defined(__GNUC__)
24425
24426   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
24427      unsigned int lo, hi;
24428      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24429      return (sqlcipher_uint64)hi << 32 | lo;
24430   }
24431
24432   #elif defined(_MSC_VER)
24433
24434   __declspec(naked) __inline sqlcipher_uint64 __cdecl sqlcipher3Hwtime(void){
24435      __asm {
24436         rdtsc
24437         ret       ; return value at EDX:EAX
24438      }
24439   }
24440
24441   #endif
24442
24443 #elif (defined(__GNUC__) && defined(__x86_64__))
24444
24445   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
24446       unsigned long val;
24447       __asm__ __volatile__ ("rdtsc" : "=A" (val));
24448       return val;
24449   }
24450  
24451 #elif (defined(__GNUC__) && defined(__ppc__))
24452
24453   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
24454       unsigned long long retval;
24455       unsigned long junk;
24456       __asm__ __volatile__ ("\n\
24457           1:      mftbu   %1\n\
24458                   mftb    %L0\n\
24459                   mftbu   %0\n\
24460                   cmpw    %0,%1\n\
24461                   bne     1b"
24462                   : "=r" (retval), "=r" (junk));
24463       return retval;
24464   }
24465
24466 #else
24467
24468   #error Need implementation of sqlcipher3Hwtime() for your platform.
24469
24470   /*
24471   ** To compile without implementing sqlcipher3Hwtime() for your platform,
24472   ** you can remove the above #error and use the following
24473   ** stub function.  You will lose timing support for many
24474   ** of the debugging and testing utilities, but it should at
24475   ** least compile and run.
24476   */
24477 SQLCIPHER_PRIVATE   sqlcipher_uint64 sqlcipher3Hwtime(void){ return ((sqlcipher_uint64)0); }
24478
24479 #endif
24480
24481 #endif /* !defined(_HWTIME_H_) */
24482
24483 /************** End of hwtime.h **********************************************/
24484 /************** Continuing where we left off in os_common.h ******************/
24485
24486 static sqlcipher_uint64 g_start;
24487 static sqlcipher_uint64 g_elapsed;
24488 #define TIMER_START       g_start=sqlcipher3Hwtime()
24489 #define TIMER_END         g_elapsed=sqlcipher3Hwtime()-g_start
24490 #define TIMER_ELAPSED     g_elapsed
24491 #else
24492 #define TIMER_START
24493 #define TIMER_END
24494 #define TIMER_ELAPSED     ((sqlcipher_uint64)0)
24495 #endif
24496
24497 /*
24498 ** If we compile with the SQLCIPHER_TEST macro set, then the following block
24499 ** of code will give us the ability to simulate a disk I/O error.  This
24500 ** is used for testing the I/O recovery logic.
24501 */
24502 #ifdef SQLCIPHER_TEST
24503 SQLCIPHER_API int sqlcipher3_io_error_hit = 0;            /* Total number of I/O Errors */
24504 SQLCIPHER_API int sqlcipher3_io_error_hardhit = 0;        /* Number of non-benign errors */
24505 SQLCIPHER_API int sqlcipher3_io_error_pending = 0;        /* Count down to first I/O error */
24506 SQLCIPHER_API int sqlcipher3_io_error_persist = 0;        /* True if I/O errors persist */
24507 SQLCIPHER_API int sqlcipher3_io_error_benign = 0;         /* True if errors are benign */
24508 SQLCIPHER_API int sqlcipher3_diskfull_pending = 0;
24509 SQLCIPHER_API int sqlcipher3_diskfull = 0;
24510 #define SimulateIOErrorBenign(X) sqlcipher3_io_error_benign=(X)
24511 #define SimulateIOError(CODE)  \
24512   if( (sqlcipher3_io_error_persist && sqlcipher3_io_error_hit) \
24513        || sqlcipher3_io_error_pending-- == 1 )  \
24514               { local_ioerr(); CODE; }
24515 static void local_ioerr(){
24516   IOTRACE(("IOERR\n"));
24517   sqlcipher3_io_error_hit++;
24518   if( !sqlcipher3_io_error_benign ) sqlcipher3_io_error_hardhit++;
24519 }
24520 #define SimulateDiskfullError(CODE) \
24521    if( sqlcipher3_diskfull_pending ){ \
24522      if( sqlcipher3_diskfull_pending == 1 ){ \
24523        local_ioerr(); \
24524        sqlcipher3_diskfull = 1; \
24525        sqlcipher3_io_error_hit = 1; \
24526        CODE; \
24527      }else{ \
24528        sqlcipher3_diskfull_pending--; \
24529      } \
24530    }
24531 #else
24532 #define SimulateIOErrorBenign(X)
24533 #define SimulateIOError(A)
24534 #define SimulateDiskfullError(A)
24535 #endif
24536
24537 /*
24538 ** When testing, keep a count of the number of open files.
24539 */
24540 #ifdef SQLCIPHER_TEST
24541 SQLCIPHER_API int sqlcipher3_open_file_count = 0;
24542 #define OpenCounter(X)  sqlcipher3_open_file_count+=(X)
24543 #else
24544 #define OpenCounter(X)
24545 #endif
24546
24547 #endif /* !defined(_OS_COMMON_H_) */
24548
24549 /************** End of os_common.h *******************************************/
24550 /************** Continuing where we left off in os_os2.c *********************/
24551
24552 /* Forward references */
24553 typedef struct os2File os2File;         /* The file structure */
24554 typedef struct os2ShmNode os2ShmNode;   /* A shared descritive memory node */
24555 typedef struct os2ShmLink os2ShmLink;   /* A connection to shared-memory */
24556
24557 /*
24558 ** The os2File structure is subclass of sqlcipher3_file specific for the OS/2
24559 ** protability layer.
24560 */
24561 struct os2File {
24562   const sqlcipher3_io_methods *pMethod;  /* Always the first entry */
24563   HFILE h;                  /* Handle for accessing the file */
24564   int flags;                /* Flags provided to os2Open() */
24565   int locktype;             /* Type of lock currently held on this file */
24566   int szChunk;              /* Chunk size configured by FCNTL_CHUNK_SIZE */
24567   char *zFullPathCp;        /* Full path name of this file */
24568   os2ShmLink *pShmLink;     /* Instance of shared memory on this file */
24569 };
24570
24571 #define LOCK_TIMEOUT 10L /* the default locking timeout */
24572
24573 /*
24574 ** Missing from some versions of the OS/2 toolkit -
24575 ** used to allocate from high memory if possible
24576 */
24577 #ifndef OBJ_ANY
24578 # define OBJ_ANY 0x00000400
24579 #endif
24580
24581 /*****************************************************************************
24582 ** The next group of routines implement the I/O methods specified
24583 ** by the sqlcipher3_io_methods object.
24584 ******************************************************************************/
24585
24586 /*
24587 ** Close a file.
24588 */
24589 static int os2Close( sqlcipher3_file *id ){
24590   APIRET rc;
24591   os2File *pFile = (os2File*)id;
24592
24593   assert( id!=0 );
24594   OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
24595
24596   rc = DosClose( pFile->h );
24597
24598   if( pFile->flags & SQLCIPHER_OPEN_DELETEONCLOSE )
24599     DosForceDelete( (PSZ)pFile->zFullPathCp );
24600
24601   free( pFile->zFullPathCp );
24602   pFile->zFullPathCp = NULL;
24603   pFile->locktype = NO_LOCK;
24604   pFile->h = (HFILE)-1;
24605   pFile->flags = 0;
24606
24607   OpenCounter( -1 );
24608   return rc == NO_ERROR ? SQLCIPHER_OK : SQLCIPHER_IOERR;
24609 }
24610
24611 /*
24612 ** Read data from a file into a buffer.  Return SQLCIPHER_OK if all
24613 ** bytes were read successfully and SQLCIPHER_IOERR if anything goes
24614 ** wrong.
24615 */
24616 static int os2Read(
24617   sqlcipher3_file *id,               /* File to read from */
24618   void *pBuf,                     /* Write content into this buffer */
24619   int amt,                        /* Number of bytes to read */
24620   sqlcipher3_int64 offset            /* Begin reading at this offset */
24621 ){
24622   ULONG fileLocation = 0L;
24623   ULONG got;
24624   os2File *pFile = (os2File*)id;
24625   assert( id!=0 );
24626   SimulateIOError( return SQLCIPHER_IOERR_READ );
24627   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
24628   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
24629     return SQLCIPHER_IOERR;
24630   }
24631   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
24632     return SQLCIPHER_IOERR_READ;
24633   }
24634   if( got == (ULONG)amt )
24635     return SQLCIPHER_OK;
24636   else {
24637     /* Unread portions of the input buffer must be zero-filled */
24638     memset(&((char*)pBuf)[got], 0, amt-got);
24639     return SQLCIPHER_IOERR_SHORT_READ;
24640   }
24641 }
24642
24643 /*
24644 ** Write data from a buffer into a file.  Return SQLCIPHER_OK on success
24645 ** or some other error code on failure.
24646 */
24647 static int os2Write(
24648   sqlcipher3_file *id,               /* File to write into */
24649   const void *pBuf,               /* The bytes to be written */
24650   int amt,                        /* Number of bytes to write */
24651   sqlcipher3_int64 offset            /* Offset into the file to begin writing at */
24652 ){
24653   ULONG fileLocation = 0L;
24654   APIRET rc = NO_ERROR;
24655   ULONG wrote;
24656   os2File *pFile = (os2File*)id;
24657   assert( id!=0 );
24658   SimulateIOError( return SQLCIPHER_IOERR_WRITE );
24659   SimulateDiskfullError( return SQLCIPHER_FULL );
24660   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
24661   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
24662     return SQLCIPHER_IOERR;
24663   }
24664   assert( amt>0 );
24665   while( amt > 0 &&
24666          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
24667          wrote > 0
24668   ){
24669     amt -= wrote;
24670     pBuf = &((char*)pBuf)[wrote];
24671   }
24672
24673   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLCIPHER_FULL : SQLCIPHER_OK;
24674 }
24675
24676 /*
24677 ** Truncate an open file to a specified size
24678 */
24679 static int os2Truncate( sqlcipher3_file *id, i64 nByte ){
24680   APIRET rc;
24681   os2File *pFile = (os2File*)id;
24682   assert( id!=0 );
24683   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
24684   SimulateIOError( return SQLCIPHER_IOERR_TRUNCATE );
24685
24686   /* If the user has configured a chunk-size for this file, truncate the
24687   ** file so that it consists of an integer number of chunks (i.e. the
24688   ** actual file size after the operation may be larger than the requested
24689   ** size).
24690   */
24691   if( pFile->szChunk ){
24692     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
24693   }
24694   
24695   rc = DosSetFileSize( pFile->h, nByte );
24696   return rc == NO_ERROR ? SQLCIPHER_OK : SQLCIPHER_IOERR_TRUNCATE;
24697 }
24698
24699 #ifdef SQLCIPHER_TEST
24700 /*
24701 ** Count the number of fullsyncs and normal syncs.  This is used to test
24702 ** that syncs and fullsyncs are occuring at the right times.
24703 */
24704 SQLCIPHER_API int sqlcipher3_sync_count = 0;
24705 SQLCIPHER_API int sqlcipher3_fullsync_count = 0;
24706 #endif
24707
24708 /*
24709 ** Make sure all writes to a particular file are committed to disk.
24710 */
24711 static int os2Sync( sqlcipher3_file *id, int flags ){
24712   os2File *pFile = (os2File*)id;
24713   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
24714 #ifdef SQLCIPHER_TEST
24715   if( flags & SQLCIPHER_SYNC_FULL){
24716     sqlcipher3_fullsync_count++;
24717   }
24718   sqlcipher3_sync_count++;
24719 #endif
24720   /* If we compiled with the SQLCIPHER_NO_SYNC flag, then syncing is a
24721   ** no-op
24722   */
24723 #ifdef SQLCIPHER_NO_SYNC
24724   UNUSED_PARAMETER(pFile);
24725   return SQLCIPHER_OK;
24726 #else
24727   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLCIPHER_OK : SQLCIPHER_IOERR;
24728 #endif
24729 }
24730
24731 /*
24732 ** Determine the current size of a file in bytes
24733 */
24734 static int os2FileSize( sqlcipher3_file *id, sqlcipher3_int64 *pSize ){
24735   APIRET rc = NO_ERROR;
24736   FILESTATUS3 fsts3FileInfo;
24737   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
24738   assert( id!=0 );
24739   SimulateIOError( return SQLCIPHER_IOERR_FSTAT );
24740   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
24741   if( rc == NO_ERROR ){
24742     *pSize = fsts3FileInfo.cbFile;
24743     return SQLCIPHER_OK;
24744   }else{
24745     return SQLCIPHER_IOERR_FSTAT;
24746   }
24747 }
24748
24749 /*
24750 ** Acquire a reader lock.
24751 */
24752 static int getReadLock( os2File *pFile ){
24753   FILELOCK  LockArea,
24754             UnlockArea;
24755   APIRET res;
24756   memset(&LockArea, 0, sizeof(LockArea));
24757   memset(&UnlockArea, 0, sizeof(UnlockArea));
24758   LockArea.lOffset = SHARED_FIRST;
24759   LockArea.lRange = SHARED_SIZE;
24760   UnlockArea.lOffset = 0L;
24761   UnlockArea.lRange = 0L;
24762   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
24763   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
24764   return res;
24765 }
24766
24767 /*
24768 ** Undo a readlock
24769 */
24770 static int unlockReadLock( os2File *id ){
24771   FILELOCK  LockArea,
24772             UnlockArea;
24773   APIRET res;
24774   memset(&LockArea, 0, sizeof(LockArea));
24775   memset(&UnlockArea, 0, sizeof(UnlockArea));
24776   LockArea.lOffset = 0L;
24777   LockArea.lRange = 0L;
24778   UnlockArea.lOffset = SHARED_FIRST;
24779   UnlockArea.lRange = SHARED_SIZE;
24780   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
24781   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
24782   return res;
24783 }
24784
24785 /*
24786 ** Lock the file with the lock specified by parameter locktype - one
24787 ** of the following:
24788 **
24789 **     (1) SHARED_LOCK
24790 **     (2) RESERVED_LOCK
24791 **     (3) PENDING_LOCK
24792 **     (4) EXCLUSIVE_LOCK
24793 **
24794 ** Sometimes when requesting one lock state, additional lock states
24795 ** are inserted in between.  The locking might fail on one of the later
24796 ** transitions leaving the lock state different from what it started but
24797 ** still short of its goal.  The following chart shows the allowed
24798 ** transitions and the inserted intermediate states:
24799 **
24800 **    UNLOCKED -> SHARED
24801 **    SHARED -> RESERVED
24802 **    SHARED -> (PENDING) -> EXCLUSIVE
24803 **    RESERVED -> (PENDING) -> EXCLUSIVE
24804 **    PENDING -> EXCLUSIVE
24805 **
24806 ** This routine will only increase a lock.  The os2Unlock() routine
24807 ** erases all locks at once and returns us immediately to locking level 0.
24808 ** It is not possible to lower the locking level one step at a time.  You
24809 ** must go straight to locking level 0.
24810 */
24811 static int os2Lock( sqlcipher3_file *id, int locktype ){
24812   int rc = SQLCIPHER_OK;       /* Return code from subroutines */
24813   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
24814   int newLocktype;       /* Set pFile->locktype to this value before exiting */
24815   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
24816   FILELOCK  LockArea,
24817             UnlockArea;
24818   os2File *pFile = (os2File*)id;
24819   memset(&LockArea, 0, sizeof(LockArea));
24820   memset(&UnlockArea, 0, sizeof(UnlockArea));
24821   assert( pFile!=0 );
24822   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
24823
24824   /* If there is already a lock of this type or more restrictive on the
24825   ** os2File, do nothing. Don't use the end_lock: exit path, as
24826   ** sqlcipher3_mutex_enter() hasn't been called yet.
24827   */
24828   if( pFile->locktype>=locktype ){
24829     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
24830     return SQLCIPHER_OK;
24831   }
24832
24833   /* Make sure the locking sequence is correct
24834   */
24835   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
24836   assert( locktype!=PENDING_LOCK );
24837   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
24838
24839   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
24840   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
24841   ** the PENDING_LOCK byte is temporary.
24842   */
24843   newLocktype = pFile->locktype;
24844   if( pFile->locktype==NO_LOCK
24845       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
24846   ){
24847     LockArea.lOffset = PENDING_BYTE;
24848     LockArea.lRange = 1L;
24849     UnlockArea.lOffset = 0L;
24850     UnlockArea.lRange = 0L;
24851
24852     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
24853     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
24854     if( res == NO_ERROR ){
24855       gotPendingLock = 1;
24856       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
24857     }
24858   }
24859
24860   /* Acquire a shared lock
24861   */
24862   if( locktype==SHARED_LOCK && res == NO_ERROR ){
24863     assert( pFile->locktype==NO_LOCK );
24864     res = getReadLock(pFile);
24865     if( res == NO_ERROR ){
24866       newLocktype = SHARED_LOCK;
24867     }
24868     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
24869   }
24870
24871   /* Acquire a RESERVED lock
24872   */
24873   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
24874     assert( pFile->locktype==SHARED_LOCK );
24875     LockArea.lOffset = RESERVED_BYTE;
24876     LockArea.lRange = 1L;
24877     UnlockArea.lOffset = 0L;
24878     UnlockArea.lRange = 0L;
24879     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
24880     if( res == NO_ERROR ){
24881       newLocktype = RESERVED_LOCK;
24882     }
24883     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
24884   }
24885
24886   /* Acquire a PENDING lock
24887   */
24888   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
24889     newLocktype = PENDING_LOCK;
24890     gotPendingLock = 0;
24891     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
24892                pFile->h ));
24893   }
24894
24895   /* Acquire an EXCLUSIVE lock
24896   */
24897   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
24898     assert( pFile->locktype>=SHARED_LOCK );
24899     res = unlockReadLock(pFile);
24900     OSTRACE(( "unreadlock = %d\n", res ));
24901     LockArea.lOffset = SHARED_FIRST;
24902     LockArea.lRange = SHARED_SIZE;
24903     UnlockArea.lOffset = 0L;
24904     UnlockArea.lRange = 0L;
24905     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
24906     if( res == NO_ERROR ){
24907       newLocktype = EXCLUSIVE_LOCK;
24908     }else{
24909       OSTRACE(( "OS/2 error-code = %d\n", res ));
24910       getReadLock(pFile);
24911     }
24912     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
24913   }
24914
24915   /* If we are holding a PENDING lock that ought to be released, then
24916   ** release it now.
24917   */
24918   if( gotPendingLock && locktype==SHARED_LOCK ){
24919     int r;
24920     LockArea.lOffset = 0L;
24921     LockArea.lRange = 0L;
24922     UnlockArea.lOffset = PENDING_BYTE;
24923     UnlockArea.lRange = 1L;
24924     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
24925     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
24926   }
24927
24928   /* Update the state of the lock has held in the file descriptor then
24929   ** return the appropriate result code.
24930   */
24931   if( res == NO_ERROR ){
24932     rc = SQLCIPHER_OK;
24933   }else{
24934     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
24935               locktype, newLocktype ));
24936     rc = SQLCIPHER_BUSY;
24937   }
24938   pFile->locktype = newLocktype;
24939   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
24940   return rc;
24941 }
24942
24943 /*
24944 ** This routine checks if there is a RESERVED lock held on the specified
24945 ** file by this or any other process. If such a lock is held, return
24946 ** non-zero, otherwise zero.
24947 */
24948 static int os2CheckReservedLock( sqlcipher3_file *id, int *pOut ){
24949   int r = 0;
24950   os2File *pFile = (os2File*)id;
24951   assert( pFile!=0 );
24952   if( pFile->locktype>=RESERVED_LOCK ){
24953     r = 1;
24954     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
24955   }else{
24956     FILELOCK  LockArea,
24957               UnlockArea;
24958     APIRET rc = NO_ERROR;
24959     memset(&LockArea, 0, sizeof(LockArea));
24960     memset(&UnlockArea, 0, sizeof(UnlockArea));
24961     LockArea.lOffset = RESERVED_BYTE;
24962     LockArea.lRange = 1L;
24963     UnlockArea.lOffset = 0L;
24964     UnlockArea.lRange = 0L;
24965     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
24966     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
24967     if( rc == NO_ERROR ){
24968       APIRET rcu = NO_ERROR; /* return code for unlocking */
24969       LockArea.lOffset = 0L;
24970       LockArea.lRange = 0L;
24971       UnlockArea.lOffset = RESERVED_BYTE;
24972       UnlockArea.lRange = 1L;
24973       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
24974       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
24975     }
24976     r = !(rc == NO_ERROR);
24977     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
24978   }
24979   *pOut = r;
24980   return SQLCIPHER_OK;
24981 }
24982
24983 /*
24984 ** Lower the locking level on file descriptor id to locktype.  locktype
24985 ** must be either NO_LOCK or SHARED_LOCK.
24986 **
24987 ** If the locking level of the file descriptor is already at or below
24988 ** the requested locking level, this routine is a no-op.
24989 **
24990 ** It is not possible for this routine to fail if the second argument
24991 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
24992 ** might return SQLCIPHER_IOERR;
24993 */
24994 static int os2Unlock( sqlcipher3_file *id, int locktype ){
24995   int type;
24996   os2File *pFile = (os2File*)id;
24997   APIRET rc = SQLCIPHER_OK;
24998   APIRET res = NO_ERROR;
24999   FILELOCK  LockArea,
25000             UnlockArea;
25001   memset(&LockArea, 0, sizeof(LockArea));
25002   memset(&UnlockArea, 0, sizeof(UnlockArea));
25003   assert( pFile!=0 );
25004   assert( locktype<=SHARED_LOCK );
25005   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
25006   type = pFile->locktype;
25007   if( type>=EXCLUSIVE_LOCK ){
25008     LockArea.lOffset = 0L;
25009     LockArea.lRange = 0L;
25010     UnlockArea.lOffset = SHARED_FIRST;
25011     UnlockArea.lRange = SHARED_SIZE;
25012     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
25013     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
25014     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
25015       /* This should never happen.  We should always be able to
25016       ** reacquire the read lock */
25017       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
25018       rc = SQLCIPHER_IOERR_UNLOCK;
25019     }
25020   }
25021   if( type>=RESERVED_LOCK ){
25022     LockArea.lOffset = 0L;
25023     LockArea.lRange = 0L;
25024     UnlockArea.lOffset = RESERVED_BYTE;
25025     UnlockArea.lRange = 1L;
25026     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
25027     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
25028   }
25029   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
25030     res = unlockReadLock(pFile);
25031     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
25032               pFile->h, type, locktype, res ));
25033   }
25034   if( type>=PENDING_LOCK ){
25035     LockArea.lOffset = 0L;
25036     LockArea.lRange = 0L;
25037     UnlockArea.lOffset = PENDING_BYTE;
25038     UnlockArea.lRange = 1L;
25039     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
25040     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
25041   }
25042   pFile->locktype = locktype;
25043   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
25044   return rc;
25045 }
25046
25047 /*
25048 ** Control and query of the open file handle.
25049 */
25050 static int os2FileControl(sqlcipher3_file *id, int op, void *pArg){
25051   switch( op ){
25052     case SQLCIPHER_FCNTL_LOCKSTATE: {
25053       *(int*)pArg = ((os2File*)id)->locktype;
25054       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
25055                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
25056       return SQLCIPHER_OK;
25057     }
25058     case SQLCIPHER_FCNTL_CHUNK_SIZE: {
25059       ((os2File*)id)->szChunk = *(int*)pArg;
25060       return SQLCIPHER_OK;
25061     }
25062     case SQLCIPHER_FCNTL_SIZE_HINT: {
25063       sqlcipher3_int64 sz = *(sqlcipher3_int64*)pArg;
25064       SimulateIOErrorBenign(1);
25065       os2Truncate(id, sz);
25066       SimulateIOErrorBenign(0);
25067       return SQLCIPHER_OK;
25068     }
25069     case SQLCIPHER_FCNTL_SYNC_OMITTED: {
25070       return SQLCIPHER_OK;
25071     }
25072   }
25073   return SQLCIPHER_NOTFOUND;
25074 }
25075
25076 /*
25077 ** Return the sector size in bytes of the underlying block device for
25078 ** the specified file. This is almost always 512 bytes, but may be
25079 ** larger for some devices.
25080 **
25081 ** SQLite code assumes this function cannot fail. It also assumes that
25082 ** if two files are created in the same file-system directory (i.e.
25083 ** a database and its journal file) that the sector size will be the
25084 ** same for both.
25085 */
25086 static int os2SectorSize(sqlcipher3_file *id){
25087   UNUSED_PARAMETER(id);
25088   return SQLCIPHER_DEFAULT_SECTOR_SIZE;
25089 }
25090
25091 /*
25092 ** Return a vector of device characteristics.
25093 */
25094 static int os2DeviceCharacteristics(sqlcipher3_file *id){
25095   UNUSED_PARAMETER(id);
25096   return SQLCIPHER_IOCAP_UNDELETABLE_WHEN_OPEN;
25097 }
25098
25099
25100 /*
25101 ** Character set conversion objects used by conversion routines.
25102 */
25103 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
25104 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
25105
25106 /*
25107 ** Helper function to initialize the conversion objects from and to UTF-8.
25108 */
25109 static void initUconvObjects( void ){
25110   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
25111     ucUtf8 = NULL;
25112   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
25113     uclCp = NULL;
25114 }
25115
25116 /*
25117 ** Helper function to free the conversion objects from and to UTF-8.
25118 */
25119 static void freeUconvObjects( void ){
25120   if ( ucUtf8 )
25121     UniFreeUconvObject( ucUtf8 );
25122   if ( uclCp )
25123     UniFreeUconvObject( uclCp );
25124   ucUtf8 = NULL;
25125   uclCp = NULL;
25126 }
25127
25128 /*
25129 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
25130 ** The two-step process: first convert the incoming UTF-8 string
25131 ** into UCS-2 and then from UCS-2 to the current codepage.
25132 ** The returned char pointer has to be freed.
25133 */
25134 static char *convertUtf8PathToCp( const char *in ){
25135   UniChar tempPath[CCHMAXPATH];
25136   char *out = (char *)calloc( CCHMAXPATH, 1 );
25137
25138   if( !out )
25139     return NULL;
25140
25141   if( !ucUtf8 || !uclCp )
25142     initUconvObjects();
25143
25144   /* determine string for the conversion of UTF-8 which is CP1208 */
25145   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
25146     return out; /* if conversion fails, return the empty string */
25147
25148   /* conversion for current codepage which can be used for paths */
25149   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
25150
25151   return out;
25152 }
25153
25154 /*
25155 ** Helper function to convert filenames from local codepage to UTF-8.
25156 ** The two-step process: first convert the incoming codepage-specific
25157 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
25158 ** The returned char pointer has to be freed.
25159 **
25160 ** This function is non-static to be able to use this in shell.c and
25161 ** similar applications that take command line arguments.
25162 */
25163 char *convertCpPathToUtf8( const char *in ){
25164   UniChar tempPath[CCHMAXPATH];
25165   char *out = (char *)calloc( CCHMAXPATH, 1 );
25166
25167   if( !out )
25168     return NULL;
25169
25170   if( !ucUtf8 || !uclCp )
25171     initUconvObjects();
25172
25173   /* conversion for current codepage which can be used for paths */
25174   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
25175     return out; /* if conversion fails, return the empty string */
25176
25177   /* determine string for the conversion of UTF-8 which is CP1208 */
25178   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
25179
25180   return out;
25181 }
25182
25183
25184 #ifndef SQLCIPHER_OMIT_WAL
25185
25186 /*
25187 ** Use main database file for interprocess locking. If un-defined
25188 ** a separate file is created for this purpose. The file will be
25189 ** used only to set file locks. There will be no data written to it.
25190 */
25191 #define SQLCIPHER_OS2_NO_WAL_LOCK_FILE     
25192
25193 #if 0
25194 static void _ERR_TRACE( const char *fmt, ... ) {
25195   va_list  ap;
25196   va_start(ap, fmt);
25197   vfprintf(stderr, fmt, ap);
25198   fflush(stderr);
25199 }
25200 #define ERR_TRACE(rc, msg)        \
25201         if( (rc) != SQLCIPHER_OK ) _ERR_TRACE msg;
25202 #else
25203 #define ERR_TRACE(rc, msg)
25204 #endif
25205
25206 /*
25207 ** Helper functions to obtain and relinquish the global mutex. The
25208 ** global mutex is used to protect os2ShmNodeList.
25209 **
25210 ** Function os2ShmMutexHeld() is used to assert() that the global mutex 
25211 ** is held when required. This function is only used as part of assert() 
25212 ** statements. e.g.
25213 **
25214 **   os2ShmEnterMutex()
25215 **     assert( os2ShmMutexHeld() );
25216 **   os2ShmLeaveMutex()
25217 */
25218 static void os2ShmEnterMutex(void){
25219   sqlcipher3_mutex_enter(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
25220 }
25221 static void os2ShmLeaveMutex(void){
25222   sqlcipher3_mutex_leave(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
25223 }
25224 #ifdef SQLCIPHER_DEBUG
25225 static int os2ShmMutexHeld(void) {
25226   return sqlcipher3_mutex_held(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
25227 }
25228 int GetCurrentProcessId(void) {
25229   PPIB pib;
25230   DosGetInfoBlocks(NULL, &pib);
25231   return (int)pib->pib_ulpid;
25232 }
25233 #endif
25234
25235 /*
25236 ** Object used to represent a the shared memory area for a single log file.
25237 ** When multiple threads all reference the same log-summary, each thread has
25238 ** its own os2File object, but they all point to a single instance of this 
25239 ** object.  In other words, each log-summary is opened only once per process.
25240 **
25241 ** os2ShmMutexHeld() must be true when creating or destroying
25242 ** this object or while reading or writing the following fields:
25243 **
25244 **      nRef
25245 **      pNext 
25246 **
25247 ** The following fields are read-only after the object is created:
25248 ** 
25249 **      szRegion
25250 **      hLockFile
25251 **      shmBaseName
25252 **
25253 ** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
25254 ** os2ShmMutexHeld() is true when reading or writing any other field
25255 ** in this structure.
25256 **
25257 */
25258 struct os2ShmNode {
25259   sqlcipher3_mutex *mutex;      /* Mutex to access this object */
25260   os2ShmNode *pNext;         /* Next in list of all os2ShmNode objects */
25261
25262   int szRegion;              /* Size of shared-memory regions */
25263
25264   int nRegion;               /* Size of array apRegion */
25265   void **apRegion;           /* Array of pointers to shared-memory regions */
25266
25267   int nRef;                  /* Number of os2ShmLink objects pointing to this */
25268   os2ShmLink *pFirst;        /* First os2ShmLink object pointing to this */
25269
25270   HFILE hLockFile;           /* File used for inter-process memory locking */
25271   char shmBaseName[1];       /* Name of the memory object !!! must last !!! */
25272 };
25273
25274
25275 /*
25276 ** Structure used internally by this VFS to record the state of an
25277 ** open shared memory connection.
25278 **
25279 ** The following fields are initialized when this object is created and
25280 ** are read-only thereafter:
25281 **
25282 **    os2Shm.pShmNode
25283 **    os2Shm.id
25284 **
25285 ** All other fields are read/write.  The os2Shm.pShmNode->mutex must be held
25286 ** while accessing any read/write fields.
25287 */
25288 struct os2ShmLink {
25289   os2ShmNode *pShmNode;      /* The underlying os2ShmNode object */
25290   os2ShmLink *pNext;         /* Next os2Shm with the same os2ShmNode */
25291   u32 sharedMask;            /* Mask of shared locks held */
25292   u32 exclMask;              /* Mask of exclusive locks held */
25293 #ifdef SQLCIPHER_DEBUG
25294   u8 id;                     /* Id of this connection with its os2ShmNode */
25295 #endif
25296 };
25297
25298
25299 /*
25300 ** A global list of all os2ShmNode objects.
25301 **
25302 ** The os2ShmMutexHeld() must be true while reading or writing this list.
25303 */
25304 static os2ShmNode *os2ShmNodeList = NULL;
25305
25306 /*
25307 ** Constants used for locking
25308 */
25309 #ifdef  SQLCIPHER_OS2_NO_WAL_LOCK_FILE
25310 #define OS2_SHM_BASE   (PENDING_BYTE + 0x10000)         /* first lock byte */
25311 #else
25312 #define OS2_SHM_BASE   ((22+SQLCIPHER_SHM_NLOCK)*4)        /* first lock byte */
25313 #endif
25314
25315 #define OS2_SHM_DMS    (OS2_SHM_BASE+SQLCIPHER_SHM_NLOCK)  /* deadman switch */
25316
25317 /*
25318 ** Apply advisory locks for all n bytes beginning at ofst.
25319 */
25320 #define _SHM_UNLCK  1   /* no lock */
25321 #define _SHM_RDLCK  2   /* shared lock, no wait */
25322 #define _SHM_WRLCK  3   /* exlusive lock, no wait */
25323 #define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
25324 static int os2ShmSystemLock(
25325   os2ShmNode *pNode,    /* Apply locks to this open shared-memory segment */
25326   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
25327   int ofst,             /* Offset to first byte to be locked/unlocked */
25328   int nByte             /* Number of bytes to lock or unlock */
25329 ){
25330   APIRET rc;
25331   FILELOCK area;
25332   ULONG mode, timeout;
25333
25334   /* Access to the os2ShmNode object is serialized by the caller */
25335   assert( sqlcipher3_mutex_held(pNode->mutex) || pNode->nRef==0 );
25336
25337   mode = 1;     /* shared lock */
25338   timeout = 0;  /* no wait */
25339   area.lOffset = ofst;
25340   area.lRange = nByte;
25341
25342   switch( lockType ) {
25343     case _SHM_WRLCK_WAIT:
25344       timeout = (ULONG)-1;      /* wait forever */
25345     case _SHM_WRLCK:
25346       mode = 0;                 /* exclusive lock */
25347     case _SHM_RDLCK:
25348       rc = DosSetFileLocks(pNode->hLockFile, 
25349                            NULL, &area, timeout, mode);
25350       break;
25351     /* case _SHM_UNLCK: */
25352     default:
25353       rc = DosSetFileLocks(pNode->hLockFile, 
25354                            &area, NULL, 0, 0);
25355       break;
25356   }
25357                           
25358   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
25359            pNode->hLockFile,
25360            rc==SQLCIPHER_OK ? "ok" : "failed",
25361            lockType==_SHM_UNLCK ? "Unlock" : "Lock",
25362            rc));
25363
25364   ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
25365
25366   return ( rc == 0 ) ?  SQLCIPHER_OK : SQLCIPHER_BUSY;
25367 }
25368
25369 /*
25370 ** Find an os2ShmNode in global list or allocate a new one, if not found.
25371 **
25372 ** This is not a VFS shared-memory method; it is a utility function called
25373 ** by VFS shared-memory methods.
25374 */
25375 static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
25376   os2ShmLink *pLink;
25377   os2ShmNode *pNode;
25378   int cbShmName, rc = SQLCIPHER_OK;
25379   char shmName[CCHMAXPATH + 30];
25380 #ifndef SQLCIPHER_OS2_NO_WAL_LOCK_FILE
25381   ULONG action;
25382 #endif
25383   
25384   /* We need some additional space at the end to append the region number */
25385   cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
25386   if( cbShmName >= CCHMAXPATH-8 )
25387     return SQLCIPHER_IOERR_SHMOPEN; 
25388
25389   /* Replace colon in file name to form a valid shared memory name */
25390   shmName[10+1] = '!';
25391
25392   /* Allocate link object (we free it later in case of failure) */
25393   pLink = sqlcipher3_malloc( sizeof(*pLink) );
25394   if( !pLink )
25395     return SQLCIPHER_NOMEM;
25396
25397   /* Access node list */
25398   os2ShmEnterMutex();
25399
25400   /* Find node by it's shared memory base name */
25401   for( pNode = os2ShmNodeList; 
25402        pNode && stricmp(shmName, pNode->shmBaseName) != 0; 
25403        pNode = pNode->pNext )   ;
25404
25405   /* Not found: allocate a new node */
25406   if( !pNode ) {
25407     pNode = sqlcipher3_malloc( sizeof(*pNode) + cbShmName );
25408     if( pNode ) {
25409       memset(pNode, 0, sizeof(*pNode) );
25410       pNode->szRegion = szRegion;
25411       pNode->hLockFile = (HFILE)-1;      
25412       strcpy(pNode->shmBaseName, shmName);
25413
25414 #ifdef SQLCIPHER_OS2_NO_WAL_LOCK_FILE
25415       if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
25416 #else
25417       sprintf(shmName, "%s-lck", fd->zFullPathCp);
25418       if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL, 
25419                   OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
25420                   OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE | 
25421                   OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
25422                   NULL) != 0 ) {
25423 #endif
25424         sqlcipher3_free(pNode);  
25425         rc = SQLCIPHER_IOERR;
25426       } else {
25427         pNode->mutex = sqlcipher3_mutex_alloc(SQLCIPHER_MUTEX_FAST);
25428         if( !pNode->mutex ) {
25429           sqlcipher3_free(pNode);  
25430           rc = SQLCIPHER_NOMEM;
25431         }
25432       }   
25433     } else {
25434       rc = SQLCIPHER_NOMEM;
25435     }
25436     
25437     if( rc == SQLCIPHER_OK ) {
25438       pNode->pNext = os2ShmNodeList;
25439       os2ShmNodeList = pNode;
25440     } else {
25441       pNode = NULL;
25442     }
25443   } else if( pNode->szRegion != szRegion ) {
25444     rc = SQLCIPHER_IOERR_SHMSIZE;
25445     pNode = NULL;
25446   }
25447
25448   if( pNode ) {
25449     sqlcipher3_mutex_enter(pNode->mutex);
25450
25451     memset(pLink, 0, sizeof(*pLink));
25452
25453     pLink->pShmNode = pNode;
25454     pLink->pNext = pNode->pFirst;
25455     pNode->pFirst = pLink;
25456     pNode->nRef++;
25457
25458     fd->pShmLink = pLink;
25459
25460     sqlcipher3_mutex_leave(pNode->mutex);
25461     
25462   } else {
25463     /* Error occured. Free our link object. */
25464     sqlcipher3_free(pLink);  
25465   }
25466
25467   os2ShmLeaveMutex();
25468
25469   ERR_TRACE(rc, ("os2OpenSharedMemory: %d  %s\n", rc, fd->zFullPathCp))  
25470   
25471   return rc;
25472 }
25473
25474 /*
25475 ** Purge the os2ShmNodeList list of all entries with nRef==0.
25476 **
25477 ** This is not a VFS shared-memory method; it is a utility function called
25478 ** by VFS shared-memory methods.
25479 */
25480 static void os2PurgeShmNodes( int deleteFlag ) {
25481   os2ShmNode *pNode;
25482   os2ShmNode **ppNode;
25483
25484   os2ShmEnterMutex();
25485   
25486   ppNode = &os2ShmNodeList;
25487
25488   while( *ppNode ) {
25489     pNode = *ppNode;
25490
25491     if( pNode->nRef == 0 ) {
25492       *ppNode = pNode->pNext;   
25493      
25494       if( pNode->apRegion ) {
25495         /* Prevent other processes from resizing the shared memory */
25496         os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
25497
25498         while( pNode->nRegion-- ) {
25499 #ifdef SQLCIPHER_DEBUG
25500           int rc = 
25501 #endif          
25502           DosFreeMem(pNode->apRegion[pNode->nRegion]);
25503
25504           OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
25505                   (int)GetCurrentProcessId(), pNode->nRegion,
25506                   rc == 0 ? "ok" : "failed"));
25507         }
25508
25509         /* Allow other processes to resize the shared memory */
25510         os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
25511
25512         sqlcipher3_free(pNode->apRegion);
25513       }  
25514
25515       DosClose(pNode->hLockFile);
25516       
25517 #ifndef SQLCIPHER_OS2_NO_WAL_LOCK_FILE
25518       if( deleteFlag ) {
25519          char fileName[CCHMAXPATH];
25520          /* Skip "\\SHAREMEM\\" */
25521          sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
25522          /* restore colon */
25523          fileName[1] = ':';
25524          
25525          DosForceDelete(fileName); 
25526       }
25527 #endif
25528
25529       sqlcipher3_mutex_free(pNode->mutex);
25530
25531       sqlcipher3_free(pNode);
25532       
25533     } else {
25534       ppNode = &pNode->pNext;
25535     }
25536   } 
25537
25538   os2ShmLeaveMutex();
25539 }
25540
25541 /*
25542 ** This function is called to obtain a pointer to region iRegion of the
25543 ** shared-memory associated with the database file id. Shared-memory regions
25544 ** are numbered starting from zero. Each shared-memory region is szRegion
25545 ** bytes in size.
25546 **
25547 ** If an error occurs, an error code is returned and *pp is set to NULL.
25548 **
25549 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
25550 ** region has not been allocated (by any client, including one running in a
25551 ** separate process), then *pp is set to NULL and SQLCIPHER_OK returned. If
25552 ** bExtend is non-zero and the requested shared-memory region has not yet
25553 ** been allocated, it is allocated by this function.
25554 **
25555 ** If the shared-memory region has already been allocated or is allocated by
25556 ** this call as described above, then it is mapped into this processes
25557 ** address space (if it is not already), *pp is set to point to the mapped
25558 ** memory and SQLCIPHER_OK returned.
25559 */
25560 static int os2ShmMap(
25561   sqlcipher3_file *id,               /* Handle open on database file */
25562   int iRegion,                    /* Region to retrieve */
25563   int szRegion,                   /* Size of regions */
25564   int bExtend,                    /* True to extend block if necessary */
25565   void volatile **pp              /* OUT: Mapped memory */
25566 ){
25567   PVOID pvTemp;
25568   void **apRegion;
25569   os2ShmNode *pNode;
25570   int n, rc = SQLCIPHER_OK;
25571   char shmName[CCHMAXPATH];
25572   os2File *pFile = (os2File*)id;
25573   
25574   *pp = NULL;
25575
25576   if( !pFile->pShmLink )
25577     rc = os2OpenSharedMemory( pFile, szRegion );
25578   
25579   if( rc == SQLCIPHER_OK ) {
25580     pNode = pFile->pShmLink->pShmNode ;
25581     
25582     sqlcipher3_mutex_enter(pNode->mutex);
25583     
25584     assert( szRegion==pNode->szRegion );
25585
25586     /* Unmapped region ? */
25587     if( iRegion >= pNode->nRegion ) {
25588       /* Prevent other processes from resizing the shared memory */
25589       os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
25590
25591       apRegion = sqlcipher3_realloc(
25592         pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
25593
25594       if( apRegion ) {
25595         pNode->apRegion = apRegion;
25596
25597         while( pNode->nRegion <= iRegion ) {
25598           sprintf(shmName, "%s-%u", 
25599                   pNode->shmBaseName, pNode->nRegion);
25600
25601           if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName, 
25602                 PAG_READ | PAG_WRITE) != NO_ERROR ) {
25603             if( !bExtend )
25604               break;
25605
25606             if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
25607                   PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR && 
25608                 DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
25609                   PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) { 
25610               rc = SQLCIPHER_NOMEM;
25611               break;
25612             }
25613           }
25614
25615           apRegion[pNode->nRegion++] = pvTemp;
25616         }
25617
25618         /* zero out remaining entries */ 
25619         for( n = pNode->nRegion; n <= iRegion; n++ )
25620           pNode->apRegion[n] = NULL;
25621
25622         /* Return this region (maybe zero) */
25623         *pp = pNode->apRegion[iRegion];
25624       } else {
25625         rc = SQLCIPHER_NOMEM;
25626       }
25627
25628       /* Allow other processes to resize the shared memory */
25629       os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
25630       
25631     } else {
25632       /* Region has been mapped previously */
25633       *pp = pNode->apRegion[iRegion];
25634     }
25635
25636     sqlcipher3_mutex_leave(pNode->mutex);
25637   } 
25638
25639   ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n", 
25640                  pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
25641           
25642   return rc;
25643 }
25644
25645 /*
25646 ** Close a connection to shared-memory.  Delete the underlying
25647 ** storage if deleteFlag is true.
25648 **
25649 ** If there is no shared memory associated with the connection then this
25650 ** routine is a harmless no-op.
25651 */
25652 static int os2ShmUnmap(
25653   sqlcipher3_file *id,               /* The underlying database file */
25654   int deleteFlag                  /* Delete shared-memory if true */
25655 ){
25656   os2File *pFile = (os2File*)id;
25657   os2ShmLink *pLink = pFile->pShmLink;
25658   
25659   if( pLink ) {
25660     int nRef = -1;
25661     os2ShmLink **ppLink;
25662     os2ShmNode *pNode = pLink->pShmNode;
25663
25664     sqlcipher3_mutex_enter(pNode->mutex);
25665     
25666     for( ppLink = &pNode->pFirst;
25667          *ppLink && *ppLink != pLink;
25668          ppLink = &(*ppLink)->pNext )   ;
25669          
25670     assert(*ppLink);
25671
25672     if( *ppLink ) {
25673       *ppLink = pLink->pNext;
25674       nRef = --pNode->nRef;
25675     } else {
25676       ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n", 
25677                     pNode->shmBaseName))
25678     }
25679     
25680     pFile->pShmLink = NULL;
25681     sqlcipher3_free(pLink);
25682
25683     sqlcipher3_mutex_leave(pNode->mutex);
25684     
25685     if( nRef == 0 )
25686       os2PurgeShmNodes( deleteFlag );
25687   }
25688
25689   return SQLCIPHER_OK;
25690 }
25691
25692 /*
25693 ** Change the lock state for a shared-memory segment.
25694 **
25695 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
25696 ** different here than in posix.  In xShmLock(), one can go from unlocked
25697 ** to shared and back or from unlocked to exclusive and back.  But one may
25698 ** not go from shared to exclusive or from exclusive to shared.
25699 */
25700 static int os2ShmLock(
25701   sqlcipher3_file *id,          /* Database file holding the shared memory */
25702   int ofst,                  /* First lock to acquire or release */
25703   int n,                     /* Number of locks to acquire or release */
25704   int flags                  /* What to do with the lock */
25705 ){
25706   u32 mask;                             /* Mask of locks to take or release */
25707   int rc = SQLCIPHER_OK;                   /* Result code */
25708   os2File *pFile = (os2File*)id;
25709   os2ShmLink *p = pFile->pShmLink;      /* The shared memory being locked */
25710   os2ShmLink *pX;                       /* For looping over all siblings */
25711   os2ShmNode *pShmNode = p->pShmNode;   /* Our node */
25712   
25713   assert( ofst>=0 && ofst+n<=SQLCIPHER_SHM_NLOCK );
25714   assert( n>=1 );
25715   assert( flags==(SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_SHARED)
25716        || flags==(SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_EXCLUSIVE)
25717        || flags==(SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_SHARED)
25718        || flags==(SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_EXCLUSIVE) );
25719   assert( n==1 || (flags & SQLCIPHER_SHM_EXCLUSIVE)!=0 );
25720
25721   mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
25722   assert( n>1 || mask==(1<<ofst) );
25723
25724
25725   sqlcipher3_mutex_enter(pShmNode->mutex);
25726
25727   if( flags & SQLCIPHER_SHM_UNLOCK ){
25728     u32 allMask = 0; /* Mask of locks held by siblings */
25729
25730     /* See if any siblings hold this same lock */
25731     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
25732       if( pX==p ) continue;
25733       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
25734       allMask |= pX->sharedMask;
25735     }
25736
25737     /* Unlock the system-level locks */
25738     if( (mask & allMask)==0 ){
25739       rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
25740     }else{
25741       rc = SQLCIPHER_OK;
25742     }
25743
25744     /* Undo the local locks */
25745     if( rc==SQLCIPHER_OK ){
25746       p->exclMask &= ~mask;
25747       p->sharedMask &= ~mask;
25748     } 
25749   }else if( flags & SQLCIPHER_SHM_SHARED ){
25750     u32 allShared = 0;  /* Union of locks held by connections other than "p" */
25751
25752     /* Find out which shared locks are already held by sibling connections.
25753     ** If any sibling already holds an exclusive lock, go ahead and return
25754     ** SQLCIPHER_BUSY.
25755     */
25756     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
25757       if( (pX->exclMask & mask)!=0 ){
25758         rc = SQLCIPHER_BUSY;
25759         break;
25760       }
25761       allShared |= pX->sharedMask;
25762     }
25763
25764     /* Get shared locks at the system level, if necessary */
25765     if( rc==SQLCIPHER_OK ){
25766       if( (allShared & mask)==0 ){
25767         rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
25768       }else{
25769         rc = SQLCIPHER_OK;
25770       }
25771     }
25772
25773     /* Get the local shared locks */
25774     if( rc==SQLCIPHER_OK ){
25775       p->sharedMask |= mask;
25776     }
25777   }else{
25778     /* Make sure no sibling connections hold locks that will block this
25779     ** lock.  If any do, return SQLCIPHER_BUSY right away.
25780     */
25781     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
25782       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
25783         rc = SQLCIPHER_BUSY;
25784         break;
25785       }
25786     }
25787   
25788     /* Get the exclusive locks at the system level.  Then if successful
25789     ** also mark the local connection as being locked.
25790     */
25791     if( rc==SQLCIPHER_OK ){
25792       rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
25793       if( rc==SQLCIPHER_OK ){
25794         assert( (p->sharedMask & mask)==0 );
25795         p->exclMask |= mask;
25796       }
25797     }
25798   }
25799
25800   sqlcipher3_mutex_leave(pShmNode->mutex);
25801   
25802   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
25803            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
25804            rc ? "failed" : "ok"));
25805
25806   ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n", 
25807                  ofst, n, flags, rc))
25808                   
25809   return rc; 
25810 }
25811
25812 /*
25813 ** Implement a memory barrier or memory fence on shared memory.
25814 **
25815 ** All loads and stores begun before the barrier must complete before
25816 ** any load or store begun after the barrier.
25817 */
25818 static void os2ShmBarrier(
25819   sqlcipher3_file *id                /* Database file holding the shared memory */
25820 ){
25821   UNUSED_PARAMETER(id);
25822   os2ShmEnterMutex();
25823   os2ShmLeaveMutex();
25824 }
25825
25826 #else
25827 # define os2ShmMap     0
25828 # define os2ShmLock    0
25829 # define os2ShmBarrier 0
25830 # define os2ShmUnmap   0
25831 #endif /* #ifndef SQLCIPHER_OMIT_WAL */
25832
25833
25834 /*
25835 ** This vector defines all the methods that can operate on an
25836 ** sqlcipher3_file for os2.
25837 */
25838 static const sqlcipher3_io_methods os2IoMethod = {
25839   2,                              /* iVersion */
25840   os2Close,                       /* xClose */
25841   os2Read,                        /* xRead */
25842   os2Write,                       /* xWrite */
25843   os2Truncate,                    /* xTruncate */
25844   os2Sync,                        /* xSync */
25845   os2FileSize,                    /* xFileSize */
25846   os2Lock,                        /* xLock */
25847   os2Unlock,                      /* xUnlock */
25848   os2CheckReservedLock,           /* xCheckReservedLock */
25849   os2FileControl,                 /* xFileControl */
25850   os2SectorSize,                  /* xSectorSize */
25851   os2DeviceCharacteristics,       /* xDeviceCharacteristics */
25852   os2ShmMap,                      /* xShmMap */
25853   os2ShmLock,                     /* xShmLock */
25854   os2ShmBarrier,                  /* xShmBarrier */
25855   os2ShmUnmap                     /* xShmUnmap */
25856 };
25857
25858
25859 /***************************************************************************
25860 ** Here ends the I/O methods that form the sqlcipher3_io_methods object.
25861 **
25862 ** The next block of code implements the VFS methods.
25863 ****************************************************************************/
25864
25865 /*
25866 ** Create a temporary file name in zBuf.  zBuf must be big enough to
25867 ** hold at pVfs->mxPathname characters.
25868 */
25869 static int getTempname(int nBuf, char *zBuf ){
25870   static const char zChars[] =
25871     "abcdefghijklmnopqrstuvwxyz"
25872     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
25873     "0123456789";
25874   int i, j;
25875   PSZ zTempPathCp;      
25876   char zTempPath[CCHMAXPATH];
25877   ULONG ulDriveNum, ulDriveMap;
25878   
25879   /* It's odd to simulate an io-error here, but really this is just
25880   ** using the io-error infrastructure to test that SQLite handles this
25881   ** function failing. 
25882   */
25883   SimulateIOError( return SQLCIPHER_IOERR );
25884
25885   if( sqlcipher3_temp_directory ) {
25886     sqlcipher3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlcipher3_temp_directory);
25887   } else if( DosScanEnv( (PSZ)"TEMP",   &zTempPathCp ) == NO_ERROR ||
25888              DosScanEnv( (PSZ)"TMP",    &zTempPathCp ) == NO_ERROR ||
25889              DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
25890     char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
25891     sqlcipher3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
25892     free( zTempPathUTF );
25893   } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
25894     zTempPath[0] = (char)('A' + ulDriveNum - 1);
25895     zTempPath[1] = ':'; 
25896     zTempPath[2] = '\0'; 
25897   } else {
25898     zTempPath[0] = '\0'; 
25899   }
25900   
25901   /* Strip off a trailing slashes or backslashes, otherwise we would get *
25902    * multiple (back)slashes which causes DosOpen() to fail.              *
25903    * Trailing spaces are not allowed, either.                            */
25904   j = sqlcipher3Strlen30(zTempPath);
25905   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' || 
25906                     zTempPath[j-1] == ' ' ) ){
25907     j--;
25908   }
25909   zTempPath[j] = '\0';
25910   
25911   /* We use 20 bytes to randomize the name */
25912   sqlcipher3_snprintf(nBuf-22, zBuf,
25913                    "%s\\"SQLCIPHER_TEMP_FILE_PREFIX, zTempPath);
25914   j = sqlcipher3Strlen30(zBuf);
25915   sqlcipher3_randomness( 20, &zBuf[j] );
25916   for( i = 0; i < 20; i++, j++ ){
25917     zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
25918   }
25919   zBuf[j] = 0;
25920
25921   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
25922   return SQLCIPHER_OK;
25923 }
25924
25925
25926 /*
25927 ** Turn a relative pathname into a full pathname.  Write the full
25928 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
25929 ** bytes in size.
25930 */
25931 static int os2FullPathname(
25932   sqlcipher3_vfs *pVfs,          /* Pointer to vfs object */
25933   const char *zRelative,      /* Possibly relative input path */
25934   int nFull,                  /* Size of output buffer in bytes */
25935   char *zFull                 /* Output buffer */
25936 ){
25937   char *zRelativeCp = convertUtf8PathToCp( zRelative );
25938   char zFullCp[CCHMAXPATH] = "\0";
25939   char *zFullUTF;
25940   APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME, 
25941                                 zFullCp, CCHMAXPATH );
25942   free( zRelativeCp );
25943   zFullUTF = convertCpPathToUtf8( zFullCp );
25944   sqlcipher3_snprintf( nFull, zFull, zFullUTF );
25945   free( zFullUTF );
25946   return rc == NO_ERROR ? SQLCIPHER_OK : SQLCIPHER_IOERR;
25947 }
25948
25949
25950 /*
25951 ** Open a file.
25952 */
25953 static int os2Open(
25954   sqlcipher3_vfs *pVfs,            /* Not used */
25955   const char *zName,            /* Name of the file (UTF-8) */
25956   sqlcipher3_file *id,             /* Write the SQLite file handle here */
25957   int flags,                    /* Open mode flags */
25958   int *pOutFlags                /* Status return flags */
25959 ){
25960   HFILE h;
25961   ULONG ulOpenFlags = 0;
25962   ULONG ulOpenMode = 0;
25963   ULONG ulAction = 0;
25964   ULONG rc;
25965   os2File *pFile = (os2File*)id;
25966   const char *zUtf8Name = zName;
25967   char *zNameCp;
25968   char  zTmpname[CCHMAXPATH];
25969
25970   int isExclusive  = (flags & SQLCIPHER_OPEN_EXCLUSIVE);
25971   int isCreate     = (flags & SQLCIPHER_OPEN_CREATE);
25972   int isReadWrite  = (flags & SQLCIPHER_OPEN_READWRITE);
25973 #ifndef NDEBUG
25974   int isDelete     = (flags & SQLCIPHER_OPEN_DELETEONCLOSE);
25975   int isReadonly   = (flags & SQLCIPHER_OPEN_READONLY);
25976   int eType        = (flags & 0xFFFFFF00);
25977   int isOpenJournal = (isCreate && (
25978         eType==SQLCIPHER_OPEN_MASTER_JOURNAL 
25979      || eType==SQLCIPHER_OPEN_MAIN_JOURNAL 
25980      || eType==SQLCIPHER_OPEN_WAL
25981   ));
25982 #endif
25983
25984   UNUSED_PARAMETER(pVfs);
25985   assert( id!=0 );
25986
25987   /* Check the following statements are true: 
25988   **
25989   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
25990   **   (b) if CREATE is set, then READWRITE must also be set, and
25991   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
25992   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
25993   */
25994   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
25995   assert(isCreate==0 || isReadWrite);
25996   assert(isExclusive==0 || isCreate);
25997   assert(isDelete==0 || isCreate);
25998
25999   /* The main DB, main journal, WAL file and master journal are never 
26000   ** automatically deleted. Nor are they ever temporary files.  */
26001   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MAIN_DB );
26002   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MAIN_JOURNAL );
26003   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MASTER_JOURNAL );
26004   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_WAL );
26005
26006   /* Assert that the upper layer has set one of the "file-type" flags. */
26007   assert( eType==SQLCIPHER_OPEN_MAIN_DB      || eType==SQLCIPHER_OPEN_TEMP_DB 
26008        || eType==SQLCIPHER_OPEN_MAIN_JOURNAL || eType==SQLCIPHER_OPEN_TEMP_JOURNAL 
26009        || eType==SQLCIPHER_OPEN_SUBJOURNAL   || eType==SQLCIPHER_OPEN_MASTER_JOURNAL 
26010        || eType==SQLCIPHER_OPEN_TRANSIENT_DB || eType==SQLCIPHER_OPEN_WAL
26011   );
26012
26013   memset( pFile, 0, sizeof(*pFile) );
26014   pFile->h = (HFILE)-1;
26015
26016   /* If the second argument to this function is NULL, generate a 
26017   ** temporary file name to use 
26018   */
26019   if( !zUtf8Name ){
26020     assert(isDelete && !isOpenJournal);
26021     rc = getTempname(CCHMAXPATH, zTmpname);
26022     if( rc!=SQLCIPHER_OK ){
26023       return rc;
26024     }
26025     zUtf8Name = zTmpname;
26026   }
26027
26028   if( isReadWrite ){
26029     ulOpenMode |= OPEN_ACCESS_READWRITE;
26030   }else{
26031     ulOpenMode |= OPEN_ACCESS_READONLY;
26032   }
26033
26034   /* Open in random access mode for possibly better speed.  Allow full
26035   ** sharing because file locks will provide exclusive access when needed.
26036   ** The handle should not be inherited by child processes and we don't 
26037   ** want popups from the critical error handler.
26038   */
26039   ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE | 
26040                 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
26041
26042   /* SQLCIPHER_OPEN_EXCLUSIVE is used to make sure that a new file is 
26043   ** created. SQLite doesn't use it to indicate "exclusive access" 
26044   ** as it is usually understood.
26045   */
26046   if( isExclusive ){
26047     /* Creates a new file, only if it does not already exist. */
26048     /* If the file exists, it fails. */
26049     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
26050   }else if( isCreate ){
26051     /* Open existing file, or create if it doesn't exist */
26052     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
26053   }else{
26054     /* Opens a file, only if it exists. */
26055     ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
26056   }
26057
26058   zNameCp = convertUtf8PathToCp( zUtf8Name );
26059   rc = DosOpen( (PSZ)zNameCp,
26060                 &h,
26061                 &ulAction,
26062                 0L,
26063                 FILE_NORMAL,
26064                 ulOpenFlags,
26065                 ulOpenMode,
26066                 (PEAOP2)NULL );
26067   free( zNameCp );
26068
26069   if( rc != NO_ERROR ){
26070     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
26071               rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
26072
26073     if( isReadWrite ){
26074       return os2Open( pVfs, zName, id,
26075                       ((flags|SQLCIPHER_OPEN_READONLY)&~(SQLCIPHER_OPEN_CREATE|SQLCIPHER_OPEN_READWRITE)),
26076                       pOutFlags );
26077     }else{
26078       return SQLCIPHER_CANTOPEN;
26079     }
26080   }
26081
26082   if( pOutFlags ){
26083     *pOutFlags = isReadWrite ? SQLCIPHER_OPEN_READWRITE : SQLCIPHER_OPEN_READONLY;
26084   }
26085
26086   os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
26087   pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
26088   pFile->pMethod = &os2IoMethod;
26089   pFile->flags = flags;
26090   pFile->h = h;
26091
26092   OpenCounter(+1);
26093   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
26094   return SQLCIPHER_OK;
26095 }
26096
26097 /*
26098 ** Delete the named file.
26099 */
26100 static int os2Delete(
26101   sqlcipher3_vfs *pVfs,                     /* Not used on os2 */
26102   const char *zFilename,                 /* Name of file to delete */
26103   int syncDir                            /* Not used on os2 */
26104 ){
26105   APIRET rc;
26106   char *zFilenameCp;
26107   SimulateIOError( return SQLCIPHER_IOERR_DELETE );
26108   zFilenameCp = convertUtf8PathToCp( zFilename );
26109   rc = DosDelete( (PSZ)zFilenameCp );
26110   free( zFilenameCp );
26111   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
26112   return (rc == NO_ERROR ||
26113           rc == ERROR_FILE_NOT_FOUND ||
26114           rc == ERROR_PATH_NOT_FOUND ) ? SQLCIPHER_OK : SQLCIPHER_IOERR_DELETE;
26115 }
26116
26117 /*
26118 ** Check the existance and status of a file.
26119 */
26120 static int os2Access(
26121   sqlcipher3_vfs *pVfs,        /* Not used on os2 */
26122   const char *zFilename,    /* Name of file to check */
26123   int flags,                /* Type of test to make on this file */
26124   int *pOut                 /* Write results here */
26125 ){
26126   APIRET rc;
26127   FILESTATUS3 fsts3ConfigInfo;
26128   char *zFilenameCp;
26129
26130   UNUSED_PARAMETER(pVfs);
26131   SimulateIOError( return SQLCIPHER_IOERR_ACCESS; );
26132   
26133   zFilenameCp = convertUtf8PathToCp( zFilename );
26134   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
26135                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
26136   free( zFilenameCp );
26137   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
26138             fsts3ConfigInfo.attrFile, flags, rc ));
26139
26140   switch( flags ){
26141     case SQLCIPHER_ACCESS_EXISTS:
26142       /* For an SQLCIPHER_ACCESS_EXISTS query, treat a zero-length file
26143       ** as if it does not exist.
26144       */
26145       if( fsts3ConfigInfo.cbFile == 0 ) 
26146         rc = ERROR_FILE_NOT_FOUND;
26147       break;
26148     case SQLCIPHER_ACCESS_READ:
26149       break;
26150     case SQLCIPHER_ACCESS_READWRITE:
26151       if( fsts3ConfigInfo.attrFile & FILE_READONLY )
26152         rc = ERROR_ACCESS_DENIED;
26153       break;
26154     default:
26155       rc = ERROR_FILE_NOT_FOUND;
26156       assert( !"Invalid flags argument" );
26157   }
26158
26159   *pOut = (rc == NO_ERROR);
26160   OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
26161
26162   return SQLCIPHER_OK;
26163 }
26164
26165
26166 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
26167 /*
26168 ** Interfaces for opening a shared library, finding entry points
26169 ** within the shared library, and closing the shared library.
26170 */
26171 /*
26172 ** Interfaces for opening a shared library, finding entry points
26173 ** within the shared library, and closing the shared library.
26174 */
26175 static void *os2DlOpen(sqlcipher3_vfs *pVfs, const char *zFilename){
26176   HMODULE hmod;
26177   APIRET rc;
26178   char *zFilenameCp = convertUtf8PathToCp(zFilename);
26179   rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
26180   free(zFilenameCp);
26181   return rc != NO_ERROR ? 0 : (void*)hmod;
26182 }
26183 /*
26184 ** A no-op since the error code is returned on the DosLoadModule call.
26185 ** os2Dlopen returns zero if DosLoadModule is not successful.
26186 */
26187 static void os2DlError(sqlcipher3_vfs *pVfs, int nBuf, char *zBufOut){
26188 /* no-op */
26189 }
26190 static void (*os2DlSym(sqlcipher3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
26191   PFN pfn;
26192   APIRET rc;
26193   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
26194   if( rc != NO_ERROR ){
26195     /* if the symbol itself was not found, search again for the same
26196      * symbol with an extra underscore, that might be needed depending
26197      * on the calling convention */
26198     char _zSymbol[256] = "_";
26199     strncat(_zSymbol, zSymbol, 254);
26200     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
26201   }
26202   return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
26203 }
26204 static void os2DlClose(sqlcipher3_vfs *pVfs, void *pHandle){
26205   DosFreeModule((HMODULE)pHandle);
26206 }
26207 #else /* if SQLCIPHER_OMIT_LOAD_EXTENSION is defined: */
26208   #define os2DlOpen 0
26209   #define os2DlError 0
26210   #define os2DlSym 0
26211   #define os2DlClose 0
26212 #endif
26213
26214
26215 /*
26216 ** Write up to nBuf bytes of randomness into zBuf.
26217 */
26218 static int os2Randomness(sqlcipher3_vfs *pVfs, int nBuf, char *zBuf ){
26219   int n = 0;
26220 #if defined(SQLCIPHER_TEST)
26221   n = nBuf;
26222   memset(zBuf, 0, nBuf);
26223 #else
26224   int i;                           
26225   PPIB ppib;
26226   PTIB ptib;
26227   DATETIME dt; 
26228   static unsigned c = 0;
26229   /* Ordered by variation probability */
26230   static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
26231                             QSV_MAXPRMEM, QSV_MAXSHMEM,
26232                             QSV_TOTAVAILMEM, QSV_TOTRESMEM };
26233
26234   /* 8 bytes; timezone and weekday don't increase the randomness much */
26235   if( (int)sizeof(dt)-3 <= nBuf - n ){
26236     c += 0x0100;
26237     DosGetDateTime(&dt);
26238     dt.year = (USHORT)((dt.year - 1900) | c);
26239     memcpy(&zBuf[n], &dt, sizeof(dt)-3);
26240     n += sizeof(dt)-3;
26241   }
26242
26243   /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
26244   if( (int)sizeof(ULONG) <= nBuf - n ){
26245     DosGetInfoBlocks(&ptib, &ppib);
26246     *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
26247                                  ptib->tib_ptib2->tib2_ultid);
26248     n += sizeof(ULONG);
26249   }
26250
26251   /* Up to 6 * 4 bytes; variables depend on the system state */
26252   for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
26253     DosQuerySysInfo(svIdx[i], svIdx[i], 
26254                     (PULONG)&zBuf[n], sizeof(ULONG));
26255     n += sizeof(ULONG);
26256   } 
26257 #endif
26258
26259   return n;
26260 }
26261
26262 /*
26263 ** Sleep for a little while.  Return the amount of time slept.
26264 ** The argument is the number of microseconds we want to sleep.
26265 ** The return value is the number of microseconds of sleep actually
26266 ** requested from the underlying operating system, a number which
26267 ** might be greater than or equal to the argument, but not less
26268 ** than the argument.
26269 */
26270 static int os2Sleep( sqlcipher3_vfs *pVfs, int microsec ){
26271   DosSleep( (microsec/1000) );
26272   return microsec;
26273 }
26274
26275 /*
26276 ** The following variable, if set to a non-zero value, becomes the result
26277 ** returned from sqlcipher3OsCurrentTime().  This is used for testing.
26278 */
26279 #ifdef SQLCIPHER_TEST
26280 SQLCIPHER_API int sqlcipher3_current_time = 0;
26281 #endif
26282
26283 /*
26284 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
26285 ** the current time and date as a Julian Day number times 86_400_000.  In
26286 ** other words, write into *piNow the number of milliseconds since the Julian
26287 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
26288 ** proleptic Gregorian calendar.
26289 **
26290 ** On success, return 0.  Return 1 if the time and date cannot be found.
26291 */
26292 static int os2CurrentTimeInt64(sqlcipher3_vfs *pVfs, sqlcipher3_int64 *piNow){
26293 #ifdef SQLCIPHER_TEST
26294   static const sqlcipher3_int64 unixEpoch = 24405875*(sqlcipher3_int64)8640000;
26295 #endif
26296   int year, month, datepart, timepart;
26297  
26298   DATETIME dt;
26299   DosGetDateTime( &dt );
26300
26301   year = dt.year;
26302   month = dt.month;
26303
26304   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
26305   ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
26306   ** Calculate the Julian days
26307   */
26308   datepart = (int)dt.day - 32076 +
26309     1461*(year + 4800 + (month - 14)/12)/4 +
26310     367*(month - 2 - (month - 14)/12*12)/12 -
26311     3*((year + 4900 + (month - 14)/12)/100)/4;
26312
26313   /* Time in milliseconds, hours to noon added */
26314   timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
26315     ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
26316
26317   *piNow = (sqlcipher3_int64)datepart*86400*1000 + timepart;
26318    
26319 #ifdef SQLCIPHER_TEST
26320   if( sqlcipher3_current_time ){
26321     *piNow = 1000*(sqlcipher3_int64)sqlcipher3_current_time + unixEpoch;
26322   }
26323 #endif
26324
26325   UNUSED_PARAMETER(pVfs);
26326   return 0;
26327 }
26328
26329 /*
26330 ** Find the current time (in Universal Coordinated Time).  Write the
26331 ** current time and date as a Julian Day number into *prNow and
26332 ** return 0.  Return 1 if the time and date cannot be found.
26333 */
26334 static int os2CurrentTime( sqlcipher3_vfs *pVfs, double *prNow ){
26335   int rc;
26336   sqlcipher3_int64 i;
26337   rc = os2CurrentTimeInt64(pVfs, &i);
26338   if( !rc ){
26339     *prNow = i/86400000.0;
26340   }
26341   return rc;
26342 }
26343
26344 /*
26345 ** The idea is that this function works like a combination of
26346 ** GetLastError() and FormatMessage() on windows (or errno and
26347 ** strerror_r() on unix). After an error is returned by an OS
26348 ** function, SQLite calls this function with zBuf pointing to
26349 ** a buffer of nBuf bytes. The OS layer should populate the
26350 ** buffer with a nul-terminated UTF-8 encoded error message
26351 ** describing the last IO error to have occurred within the calling
26352 ** thread.
26353 **
26354 ** If the error message is too large for the supplied buffer,
26355 ** it should be truncated. The return value of xGetLastError
26356 ** is zero if the error message fits in the buffer, or non-zero
26357 ** otherwise (if the message was truncated). If non-zero is returned,
26358 ** then it is not necessary to include the nul-terminator character
26359 ** in the output buffer.
26360 **
26361 ** Not supplying an error message will have no adverse effect
26362 ** on SQLite. It is fine to have an implementation that never
26363 ** returns an error message:
26364 **
26365 **   int xGetLastError(sqlcipher3_vfs *pVfs, int nBuf, char *zBuf){
26366 **     assert(zBuf[0]=='\0');
26367 **     return 0;
26368 **   }
26369 **
26370 ** However if an error message is supplied, it will be incorporated
26371 ** by sqlcipher into the error message available to the user using
26372 ** sqlcipher3_errmsg(), possibly making IO errors easier to debug.
26373 */
26374 static int os2GetLastError(sqlcipher3_vfs *pVfs, int nBuf, char *zBuf){
26375   assert(zBuf[0]=='\0');
26376   return 0;
26377 }
26378
26379 /*
26380 ** Initialize and deinitialize the operating system interface.
26381 */
26382 SQLCIPHER_API int sqlcipher3_os_init(void){
26383   static sqlcipher3_vfs os2Vfs = {
26384     3,                 /* iVersion */
26385     sizeof(os2File),   /* szOsFile */
26386     CCHMAXPATH,        /* mxPathname */
26387     0,                 /* pNext */
26388     "os2",             /* zName */
26389     0,                 /* pAppData */
26390
26391     os2Open,           /* xOpen */
26392     os2Delete,         /* xDelete */
26393     os2Access,         /* xAccess */
26394     os2FullPathname,   /* xFullPathname */
26395     os2DlOpen,         /* xDlOpen */
26396     os2DlError,        /* xDlError */
26397     os2DlSym,          /* xDlSym */
26398     os2DlClose,        /* xDlClose */
26399     os2Randomness,     /* xRandomness */
26400     os2Sleep,          /* xSleep */
26401     os2CurrentTime,    /* xCurrentTime */
26402     os2GetLastError,   /* xGetLastError */
26403     os2CurrentTimeInt64, /* xCurrentTimeInt64 */
26404     0,                 /* xSetSystemCall */
26405     0,                 /* xGetSystemCall */
26406     0                  /* xNextSystemCall */
26407   };
26408   sqlcipher3_vfs_register(&os2Vfs, 1);
26409   initUconvObjects();
26410 /*  sqlcipher3OSTrace = 1; */
26411   return SQLCIPHER_OK;
26412 }
26413 SQLCIPHER_API int sqlcipher3_os_end(void){
26414   freeUconvObjects();
26415   return SQLCIPHER_OK;
26416 }
26417
26418 #endif /* SQLCIPHER_OS_OS2 */
26419
26420 /************** End of os_os2.c **********************************************/
26421 /************** Begin file os_unix.c *****************************************/
26422 /*
26423 ** 2004 May 22
26424 **
26425 ** The author disclaims copyright to this source code.  In place of
26426 ** a legal notice, here is a blessing:
26427 **
26428 **    May you do good and not evil.
26429 **    May you find forgiveness for yourself and forgive others.
26430 **    May you share freely, never taking more than you give.
26431 **
26432 ******************************************************************************
26433 **
26434 ** This file contains the VFS implementation for unix-like operating systems
26435 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
26436 **
26437 ** There are actually several different VFS implementations in this file.
26438 ** The differences are in the way that file locking is done.  The default
26439 ** implementation uses Posix Advisory Locks.  Alternative implementations
26440 ** use flock(), dot-files, various proprietary locking schemas, or simply
26441 ** skip locking all together.
26442 **
26443 ** This source file is organized into divisions where the logic for various
26444 ** subfunctions is contained within the appropriate division.  PLEASE
26445 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
26446 ** in the correct division and should be clearly labeled.
26447 **
26448 ** The layout of divisions is as follows:
26449 **
26450 **   *  General-purpose declarations and utility functions.
26451 **   *  Unique file ID logic used by VxWorks.
26452 **   *  Various locking primitive implementations (all except proxy locking):
26453 **      + for Posix Advisory Locks
26454 **      + for no-op locks
26455 **      + for dot-file locks
26456 **      + for flock() locking
26457 **      + for named semaphore locks (VxWorks only)
26458 **      + for AFP filesystem locks (MacOSX only)
26459 **   *  sqlcipher3_file methods not associated with locking.
26460 **   *  Definitions of sqlcipher3_io_methods objects for all locking
26461 **      methods plus "finder" functions for each locking method.
26462 **   *  sqlcipher3_vfs method implementations.
26463 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
26464 **   *  Definitions of sqlcipher3_vfs objects for all locking methods
26465 **      plus implementations of sqlcipher3_os_init() and sqlcipher3_os_end().
26466 */
26467 #if SQLCIPHER_OS_UNIX              /* This file is used on unix only */
26468
26469 /*
26470 ** There are various methods for file locking used for concurrency
26471 ** control:
26472 **
26473 **   1. POSIX locking (the default),
26474 **   2. No locking,
26475 **   3. Dot-file locking,
26476 **   4. flock() locking,
26477 **   5. AFP locking (OSX only),
26478 **   6. Named POSIX semaphores (VXWorks only),
26479 **   7. proxy locking. (OSX only)
26480 **
26481 ** Styles 4, 5, and 7 are only available of SQLCIPHER_ENABLE_LOCKING_STYLE
26482 ** is defined to 1.  The SQLCIPHER_ENABLE_LOCKING_STYLE also enables automatic
26483 ** selection of the appropriate locking style based on the filesystem
26484 ** where the database is located.  
26485 */
26486 #if !defined(SQLCIPHER_ENABLE_LOCKING_STYLE)
26487 #  if defined(__APPLE__)
26488 #    define SQLCIPHER_ENABLE_LOCKING_STYLE 1
26489 #  else
26490 #    define SQLCIPHER_ENABLE_LOCKING_STYLE 0
26491 #  endif
26492 #endif
26493
26494 /*
26495 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
26496 ** vxworks, or 0 otherwise.
26497 */
26498 #ifndef OS_VXWORKS
26499 #  if defined(__RTP__) || defined(_WRS_KERNEL)
26500 #    define OS_VXWORKS 1
26501 #  else
26502 #    define OS_VXWORKS 0
26503 #  endif
26504 #endif
26505
26506 /*
26507 ** These #defines should enable >2GB file support on Posix if the
26508 ** underlying operating system supports it.  If the OS lacks
26509 ** large file support, these should be no-ops.
26510 **
26511 ** Large file support can be disabled using the -DSQLCIPHER_DISABLE_LFS switch
26512 ** on the compiler command line.  This is necessary if you are compiling
26513 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
26514 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
26515 ** without this option, LFS is enable.  But LFS does not exist in the kernel
26516 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
26517 ** portability you should omit LFS.
26518 **
26519 ** The previous paragraph was written in 2005.  (This paragraph is written
26520 ** on 2008-11-28.) These days, all Linux kernels support large files, so
26521 ** you should probably leave LFS enabled.  But some embedded platforms might
26522 ** lack LFS in which case the SQLCIPHER_DISABLE_LFS macro might still be useful.
26523 */
26524 #ifndef SQLCIPHER_DISABLE_LFS
26525 # define _LARGE_FILE       1
26526 # ifndef _FILE_OFFSET_BITS
26527 #   define _FILE_OFFSET_BITS 64
26528 # endif
26529 # define _LARGEFILE_SOURCE 1
26530 #endif
26531
26532 /*
26533 ** standard include files.
26534 */
26535 #include <sys/types.h>
26536 #include <sys/stat.h>
26537 #include <fcntl.h>
26538 #include <unistd.h>
26539 /* #include <time.h> */
26540 #include <sys/time.h>
26541 #include <errno.h>
26542 #ifndef SQLCIPHER_OMIT_WAL
26543 /* #include <sys/mman.h> */
26544 #endif
26545
26546 #if SQLCIPHER_ENABLE_LOCKING_STYLE
26547 # include <sys/ioctl.h>
26548 # if OS_VXWORKS
26549 #  include <semaphore.h>
26550 #  include <limits.h>
26551 # else
26552 #  include <sys/file.h>
26553 #  include <sys/param.h>
26554 # endif
26555 #endif /* SQLCIPHER_ENABLE_LOCKING_STYLE */
26556
26557 #if defined(__APPLE__) || (SQLCIPHER_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
26558 # include <sys/mount.h>
26559 #endif
26560
26561 #ifdef HAVE_UTIME
26562 # include <utime.h>
26563 #endif
26564
26565 /*
26566 ** Allowed values of unixFile.fsFlags
26567 */
26568 #define SQLCIPHER_FSFLAGS_IS_MSDOS     0x1
26569
26570 /*
26571 ** If we are to be thread-safe, include the pthreads header and define
26572 ** the SQLCIPHER_UNIX_THREADS macro.
26573 */
26574 #if SQLCIPHER_THREADSAFE
26575 /* # include <pthread.h> */
26576 # define SQLCIPHER_UNIX_THREADS 1
26577 #endif
26578
26579 /*
26580 ** Default permissions when creating a new file
26581 */
26582 #ifndef SQLCIPHER_DEFAULT_FILE_PERMISSIONS
26583 # define SQLCIPHER_DEFAULT_FILE_PERMISSIONS 0644
26584 #endif
26585
26586 /*
26587  ** Default permissions when creating auto proxy dir
26588  */
26589 #ifndef SQLCIPHER_DEFAULT_PROXYDIR_PERMISSIONS
26590 # define SQLCIPHER_DEFAULT_PROXYDIR_PERMISSIONS 0755
26591 #endif
26592
26593 /*
26594 ** Maximum supported path-length.
26595 */
26596 #define MAX_PATHNAME 512
26597
26598 /*
26599 ** Only set the lastErrno if the error code is a real error and not 
26600 ** a normal expected return code of SQLCIPHER_BUSY or SQLCIPHER_OK
26601 */
26602 #define IS_LOCK_ERROR(x)  ((x != SQLCIPHER_OK) && (x != SQLCIPHER_BUSY))
26603
26604 /* Forward references */
26605 typedef struct unixShm unixShm;               /* Connection shared memory */
26606 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
26607 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
26608 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
26609
26610 /*
26611 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
26612 ** cannot be closed immediately. In these cases, instances of the following
26613 ** structure are used to store the file descriptor while waiting for an
26614 ** opportunity to either close or reuse it.
26615 */
26616 struct UnixUnusedFd {
26617   int fd;                   /* File descriptor to close */
26618   int flags;                /* Flags this file descriptor was opened with */
26619   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
26620 };
26621
26622 /*
26623 ** The unixFile structure is subclass of sqlcipher3_file specific to the unix
26624 ** VFS implementations.
26625 */
26626 typedef struct unixFile unixFile;
26627 struct unixFile {
26628   sqlcipher3_io_methods const *pMethod;  /* Always the first entry */
26629   unixInodeInfo *pInode;              /* Info about locks on this inode */
26630   int h;                              /* The file descriptor */
26631   unsigned char eFileLock;            /* The type of lock held on this fd */
26632   unsigned char ctrlFlags;            /* Behavioral bits.  UNIXFILE_* flags */
26633   int lastErrno;                      /* The unix errno from last I/O error */
26634   void *lockingContext;               /* Locking style specific state */
26635   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
26636   const char *zPath;                  /* Name of the file */
26637   unixShm *pShm;                      /* Shared memory segment information */
26638   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
26639 #if SQLCIPHER_ENABLE_LOCKING_STYLE
26640   int openFlags;                      /* The flags specified at open() */
26641 #endif
26642 #if SQLCIPHER_ENABLE_LOCKING_STYLE || defined(__APPLE__)
26643   unsigned fsFlags;                   /* cached details from statfs() */
26644 #endif
26645 #if OS_VXWORKS
26646   int isDelete;                       /* Delete on close if true */
26647   struct vxworksFileId *pId;          /* Unique file ID */
26648 #endif
26649 #ifndef NDEBUG
26650   /* The next group of variables are used to track whether or not the
26651   ** transaction counter in bytes 24-27 of database files are updated
26652   ** whenever any part of the database changes.  An assertion fault will
26653   ** occur if a file is updated without also updating the transaction
26654   ** counter.  This test is made to avoid new problems similar to the
26655   ** one described by ticket #3584. 
26656   */
26657   unsigned char transCntrChng;   /* True if the transaction counter changed */
26658   unsigned char dbUpdate;        /* True if any part of database file changed */
26659   unsigned char inNormalWrite;   /* True if in a normal write operation */
26660 #endif
26661 #ifdef SQLCIPHER_TEST
26662   /* In test mode, increase the size of this structure a bit so that 
26663   ** it is larger than the struct CrashFile defined in test6.c.
26664   */
26665   char aPadding[32];
26666 #endif
26667 };
26668
26669 /*
26670 ** Allowed values for the unixFile.ctrlFlags bitmask:
26671 */
26672 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
26673 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
26674 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
26675 #ifndef SQLCIPHER_DISABLE_DIRSYNC
26676 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
26677 #else
26678 # define UNIXFILE_DIRSYNC    0x00
26679 #endif
26680
26681 /*
26682 ** Include code that is common to all os_*.c files
26683 */
26684 /************** Include os_common.h in the middle of os_unix.c ***************/
26685 /************** Begin file os_common.h ***************************************/
26686 /*
26687 ** 2004 May 22
26688 **
26689 ** The author disclaims copyright to this source code.  In place of
26690 ** a legal notice, here is a blessing:
26691 **
26692 **    May you do good and not evil.
26693 **    May you find forgiveness for yourself and forgive others.
26694 **    May you share freely, never taking more than you give.
26695 **
26696 ******************************************************************************
26697 **
26698 ** This file contains macros and a little bit of code that is common to
26699 ** all of the platform-specific files (os_*.c) and is #included into those
26700 ** files.
26701 **
26702 ** This file should be #included by the os_*.c files only.  It is not a
26703 ** general purpose header file.
26704 */
26705 #ifndef _OS_COMMON_H_
26706 #define _OS_COMMON_H_
26707
26708 /*
26709 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
26710 ** macro to SQLCIPHER_DEBUG and some older makefiles have not yet made the
26711 ** switch.  The following code should catch this problem at compile-time.
26712 */
26713 #ifdef MEMORY_DEBUG
26714 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLCIPHER_DEBUG instead."
26715 #endif
26716
26717 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
26718 # ifndef SQLCIPHER_DEBUG_OS_TRACE
26719 #   define SQLCIPHER_DEBUG_OS_TRACE 0
26720 # endif
26721   int sqlcipher3OSTrace = SQLCIPHER_DEBUG_OS_TRACE;
26722 # define OSTRACE(X)          if( sqlcipher3OSTrace ) sqlcipher3DebugPrintf X
26723 #else
26724 # define OSTRACE(X)
26725 #endif
26726
26727 /*
26728 ** Macros for performance tracing.  Normally turned off.  Only works
26729 ** on i486 hardware.
26730 */
26731 #ifdef SQLCIPHER_PERFORMANCE_TRACE
26732
26733 /* 
26734 ** hwtime.h contains inline assembler code for implementing 
26735 ** high-performance timing routines.
26736 */
26737 /************** Include hwtime.h in the middle of os_common.h ****************/
26738 /************** Begin file hwtime.h ******************************************/
26739 /*
26740 ** 2008 May 27
26741 **
26742 ** The author disclaims copyright to this source code.  In place of
26743 ** a legal notice, here is a blessing:
26744 **
26745 **    May you do good and not evil.
26746 **    May you find forgiveness for yourself and forgive others.
26747 **    May you share freely, never taking more than you give.
26748 **
26749 ******************************************************************************
26750 **
26751 ** This file contains inline asm code for retrieving "high-performance"
26752 ** counters for x86 class CPUs.
26753 */
26754 #ifndef _HWTIME_H_
26755 #define _HWTIME_H_
26756
26757 /*
26758 ** The following routine only works on pentium-class (or newer) processors.
26759 ** It uses the RDTSC opcode to read the cycle count value out of the
26760 ** processor and returns that value.  This can be used for high-res
26761 ** profiling.
26762 */
26763 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
26764       (defined(i386) || defined(__i386__) || defined(_M_IX86))
26765
26766   #if defined(__GNUC__)
26767
26768   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
26769      unsigned int lo, hi;
26770      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
26771      return (sqlcipher_uint64)hi << 32 | lo;
26772   }
26773
26774   #elif defined(_MSC_VER)
26775
26776   __declspec(naked) __inline sqlcipher_uint64 __cdecl sqlcipher3Hwtime(void){
26777      __asm {
26778         rdtsc
26779         ret       ; return value at EDX:EAX
26780      }
26781   }
26782
26783   #endif
26784
26785 #elif (defined(__GNUC__) && defined(__x86_64__))
26786
26787   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
26788       unsigned long val;
26789       __asm__ __volatile__ ("rdtsc" : "=A" (val));
26790       return val;
26791   }
26792  
26793 #elif (defined(__GNUC__) && defined(__ppc__))
26794
26795   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
26796       unsigned long long retval;
26797       unsigned long junk;
26798       __asm__ __volatile__ ("\n\
26799           1:      mftbu   %1\n\
26800                   mftb    %L0\n\
26801                   mftbu   %0\n\
26802                   cmpw    %0,%1\n\
26803                   bne     1b"
26804                   : "=r" (retval), "=r" (junk));
26805       return retval;
26806   }
26807
26808 #else
26809
26810   #error Need implementation of sqlcipher3Hwtime() for your platform.
26811
26812   /*
26813   ** To compile without implementing sqlcipher3Hwtime() for your platform,
26814   ** you can remove the above #error and use the following
26815   ** stub function.  You will lose timing support for many
26816   ** of the debugging and testing utilities, but it should at
26817   ** least compile and run.
26818   */
26819 SQLCIPHER_PRIVATE   sqlcipher_uint64 sqlcipher3Hwtime(void){ return ((sqlcipher_uint64)0); }
26820
26821 #endif
26822
26823 #endif /* !defined(_HWTIME_H_) */
26824
26825 /************** End of hwtime.h **********************************************/
26826 /************** Continuing where we left off in os_common.h ******************/
26827
26828 static sqlcipher_uint64 g_start;
26829 static sqlcipher_uint64 g_elapsed;
26830 #define TIMER_START       g_start=sqlcipher3Hwtime()
26831 #define TIMER_END         g_elapsed=sqlcipher3Hwtime()-g_start
26832 #define TIMER_ELAPSED     g_elapsed
26833 #else
26834 #define TIMER_START
26835 #define TIMER_END
26836 #define TIMER_ELAPSED     ((sqlcipher_uint64)0)
26837 #endif
26838
26839 /*
26840 ** If we compile with the SQLCIPHER_TEST macro set, then the following block
26841 ** of code will give us the ability to simulate a disk I/O error.  This
26842 ** is used for testing the I/O recovery logic.
26843 */
26844 #ifdef SQLCIPHER_TEST
26845 SQLCIPHER_API int sqlcipher3_io_error_hit = 0;            /* Total number of I/O Errors */
26846 SQLCIPHER_API int sqlcipher3_io_error_hardhit = 0;        /* Number of non-benign errors */
26847 SQLCIPHER_API int sqlcipher3_io_error_pending = 0;        /* Count down to first I/O error */
26848 SQLCIPHER_API int sqlcipher3_io_error_persist = 0;        /* True if I/O errors persist */
26849 SQLCIPHER_API int sqlcipher3_io_error_benign = 0;         /* True if errors are benign */
26850 SQLCIPHER_API int sqlcipher3_diskfull_pending = 0;
26851 SQLCIPHER_API int sqlcipher3_diskfull = 0;
26852 #define SimulateIOErrorBenign(X) sqlcipher3_io_error_benign=(X)
26853 #define SimulateIOError(CODE)  \
26854   if( (sqlcipher3_io_error_persist && sqlcipher3_io_error_hit) \
26855        || sqlcipher3_io_error_pending-- == 1 )  \
26856               { local_ioerr(); CODE; }
26857 static void local_ioerr(){
26858   IOTRACE(("IOERR\n"));
26859   sqlcipher3_io_error_hit++;
26860   if( !sqlcipher3_io_error_benign ) sqlcipher3_io_error_hardhit++;
26861 }
26862 #define SimulateDiskfullError(CODE) \
26863    if( sqlcipher3_diskfull_pending ){ \
26864      if( sqlcipher3_diskfull_pending == 1 ){ \
26865        local_ioerr(); \
26866        sqlcipher3_diskfull = 1; \
26867        sqlcipher3_io_error_hit = 1; \
26868        CODE; \
26869      }else{ \
26870        sqlcipher3_diskfull_pending--; \
26871      } \
26872    }
26873 #else
26874 #define SimulateIOErrorBenign(X)
26875 #define SimulateIOError(A)
26876 #define SimulateDiskfullError(A)
26877 #endif
26878
26879 /*
26880 ** When testing, keep a count of the number of open files.
26881 */
26882 #ifdef SQLCIPHER_TEST
26883 SQLCIPHER_API int sqlcipher3_open_file_count = 0;
26884 #define OpenCounter(X)  sqlcipher3_open_file_count+=(X)
26885 #else
26886 #define OpenCounter(X)
26887 #endif
26888
26889 #endif /* !defined(_OS_COMMON_H_) */
26890
26891 /************** End of os_common.h *******************************************/
26892 /************** Continuing where we left off in os_unix.c ********************/
26893
26894 /*
26895 ** Define various macros that are missing from some systems.
26896 */
26897 #ifndef O_LARGEFILE
26898 # define O_LARGEFILE 0
26899 #endif
26900 #ifdef SQLCIPHER_DISABLE_LFS
26901 # undef O_LARGEFILE
26902 # define O_LARGEFILE 0
26903 #endif
26904 #ifndef O_NOFOLLOW
26905 # define O_NOFOLLOW 0
26906 #endif
26907 #ifndef O_BINARY
26908 # define O_BINARY 0
26909 #endif
26910
26911 /*
26912 ** The threadid macro resolves to the thread-id or to 0.  Used for
26913 ** testing and debugging only.
26914 */
26915 #if SQLCIPHER_THREADSAFE
26916 #define threadid pthread_self()
26917 #else
26918 #define threadid 0
26919 #endif
26920
26921 /*
26922 ** Different Unix systems declare open() in different ways.  Same use
26923 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
26924 ** The difference is important when using a pointer to the function.
26925 **
26926 ** The safest way to deal with the problem is to always use this wrapper
26927 ** which always has the same well-defined interface.
26928 */
26929 static int posixOpen(const char *zFile, int flags, int mode){
26930   return open(zFile, flags, mode);
26931 }
26932
26933 /* Forward reference */
26934 static int openDirectory(const char*, int*);
26935
26936 /*
26937 ** Many system calls are accessed through pointer-to-functions so that
26938 ** they may be overridden at runtime to facilitate fault injection during
26939 ** testing and sandboxing.  The following array holds the names and pointers
26940 ** to all overrideable system calls.
26941 */
26942 static struct unix_syscall {
26943   const char *zName;            /* Name of the sytem call */
26944   sqlcipher3_syscall_ptr pCurrent; /* Current value of the system call */
26945   sqlcipher3_syscall_ptr pDefault; /* Default value */
26946 } aSyscall[] = {
26947   { "open",         (sqlcipher3_syscall_ptr)posixOpen,  0  },
26948 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
26949
26950   { "close",        (sqlcipher3_syscall_ptr)close,      0  },
26951 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
26952
26953   { "access",       (sqlcipher3_syscall_ptr)access,     0  },
26954 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
26955
26956   { "getcwd",       (sqlcipher3_syscall_ptr)getcwd,     0  },
26957 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
26958
26959   { "stat",         (sqlcipher3_syscall_ptr)stat,       0  },
26960 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
26961
26962 /*
26963 ** The DJGPP compiler environment looks mostly like Unix, but it
26964 ** lacks the fcntl() system call.  So redefine fcntl() to be something
26965 ** that always succeeds.  This means that locking does not occur under
26966 ** DJGPP.  But it is DOS - what did you expect?
26967 */
26968 #ifdef __DJGPP__
26969   { "fstat",        0,                 0  },
26970 #define osFstat(a,b,c)    0
26971 #else     
26972   { "fstat",        (sqlcipher3_syscall_ptr)fstat,      0  },
26973 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
26974 #endif
26975
26976   { "ftruncate",    (sqlcipher3_syscall_ptr)ftruncate,  0  },
26977 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
26978
26979   { "fcntl",        (sqlcipher3_syscall_ptr)fcntl,      0  },
26980 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
26981
26982   { "read",         (sqlcipher3_syscall_ptr)read,       0  },
26983 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
26984
26985 #if defined(USE_PREAD) || SQLCIPHER_ENABLE_LOCKING_STYLE
26986   { "pread",        (sqlcipher3_syscall_ptr)pread,      0  },
26987 #else
26988   { "pread",        (sqlcipher3_syscall_ptr)0,          0  },
26989 #endif
26990 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
26991
26992 #if defined(USE_PREAD64)
26993   { "pread64",      (sqlcipher3_syscall_ptr)pread64,    0  },
26994 #else
26995   { "pread64",      (sqlcipher3_syscall_ptr)0,          0  },
26996 #endif
26997 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
26998
26999   { "write",        (sqlcipher3_syscall_ptr)write,      0  },
27000 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
27001
27002 #if defined(USE_PREAD) || SQLCIPHER_ENABLE_LOCKING_STYLE
27003   { "pwrite",       (sqlcipher3_syscall_ptr)pwrite,     0  },
27004 #else
27005   { "pwrite",       (sqlcipher3_syscall_ptr)0,          0  },
27006 #endif
27007 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
27008                     aSyscall[12].pCurrent)
27009
27010 #if defined(USE_PREAD64)
27011   { "pwrite64",     (sqlcipher3_syscall_ptr)pwrite64,   0  },
27012 #else
27013   { "pwrite64",     (sqlcipher3_syscall_ptr)0,          0  },
27014 #endif
27015 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
27016                     aSyscall[13].pCurrent)
27017
27018 #if SQLCIPHER_ENABLE_LOCKING_STYLE
27019   { "fchmod",       (sqlcipher3_syscall_ptr)fchmod,     0  },
27020 #else
27021   { "fchmod",       (sqlcipher3_syscall_ptr)0,          0  },
27022 #endif
27023 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
27024
27025 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27026   { "fallocate",    (sqlcipher3_syscall_ptr)posix_fallocate,  0 },
27027 #else
27028   { "fallocate",    (sqlcipher3_syscall_ptr)0,                0 },
27029 #endif
27030 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
27031
27032   { "unlink",       (sqlcipher3_syscall_ptr)unlink,           0 },
27033 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
27034
27035   { "openDirectory",    (sqlcipher3_syscall_ptr)openDirectory,      0 },
27036 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
27037
27038 }; /* End of the overrideable system calls */
27039
27040 /*
27041 ** This is the xSetSystemCall() method of sqlcipher3_vfs for all of the
27042 ** "unix" VFSes.  Return SQLCIPHER_OK opon successfully updating the
27043 ** system call pointer, or SQLCIPHER_NOTFOUND if there is no configurable
27044 ** system call named zName.
27045 */
27046 static int unixSetSystemCall(
27047   sqlcipher3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
27048   const char *zName,            /* Name of system call to override */
27049   sqlcipher3_syscall_ptr pNewFunc  /* Pointer to new system call value */
27050 ){
27051   unsigned int i;
27052   int rc = SQLCIPHER_NOTFOUND;
27053
27054   UNUSED_PARAMETER(pNotUsed);
27055   if( zName==0 ){
27056     /* If no zName is given, restore all system calls to their default
27057     ** settings and return NULL
27058     */
27059     rc = SQLCIPHER_OK;
27060     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
27061       if( aSyscall[i].pDefault ){
27062         aSyscall[i].pCurrent = aSyscall[i].pDefault;
27063       }
27064     }
27065   }else{
27066     /* If zName is specified, operate on only the one system call
27067     ** specified.
27068     */
27069     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
27070       if( strcmp(zName, aSyscall[i].zName)==0 ){
27071         if( aSyscall[i].pDefault==0 ){
27072           aSyscall[i].pDefault = aSyscall[i].pCurrent;
27073         }
27074         rc = SQLCIPHER_OK;
27075         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
27076         aSyscall[i].pCurrent = pNewFunc;
27077         break;
27078       }
27079     }
27080   }
27081   return rc;
27082 }
27083
27084 /*
27085 ** Return the value of a system call.  Return NULL if zName is not a
27086 ** recognized system call name.  NULL is also returned if the system call
27087 ** is currently undefined.
27088 */
27089 static sqlcipher3_syscall_ptr unixGetSystemCall(
27090   sqlcipher3_vfs *pNotUsed,
27091   const char *zName
27092 ){
27093   unsigned int i;
27094
27095   UNUSED_PARAMETER(pNotUsed);
27096   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
27097     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
27098   }
27099   return 0;
27100 }
27101
27102 /*
27103 ** Return the name of the first system call after zName.  If zName==NULL
27104 ** then return the name of the first system call.  Return NULL if zName
27105 ** is the last system call or if zName is not the name of a valid
27106 ** system call.
27107 */
27108 static const char *unixNextSystemCall(sqlcipher3_vfs *p, const char *zName){
27109   int i = -1;
27110
27111   UNUSED_PARAMETER(p);
27112   if( zName ){
27113     for(i=0; i<ArraySize(aSyscall)-1; i++){
27114       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
27115     }
27116   }
27117   for(i++; i<ArraySize(aSyscall); i++){
27118     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
27119   }
27120   return 0;
27121 }
27122
27123 /*
27124 ** Retry open() calls that fail due to EINTR
27125 */
27126 static int robust_open(const char *z, int f, int m){
27127   int rc;
27128   do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
27129   return rc;
27130 }
27131
27132 /*
27133 ** Helper functions to obtain and relinquish the global mutex. The
27134 ** global mutex is used to protect the unixInodeInfo and
27135 ** vxworksFileId objects used by this file, all of which may be 
27136 ** shared by multiple threads.
27137 **
27138 ** Function unixMutexHeld() is used to assert() that the global mutex 
27139 ** is held when required. This function is only used as part of assert() 
27140 ** statements. e.g.
27141 **
27142 **   unixEnterMutex()
27143 **     assert( unixMutexHeld() );
27144 **   unixEnterLeave()
27145 */
27146 static void unixEnterMutex(void){
27147   sqlcipher3_mutex_enter(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
27148 }
27149 static void unixLeaveMutex(void){
27150   sqlcipher3_mutex_leave(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
27151 }
27152 #ifdef SQLCIPHER_DEBUG
27153 static int unixMutexHeld(void) {
27154   return sqlcipher3_mutex_held(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
27155 }
27156 #endif
27157
27158
27159 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
27160 /*
27161 ** Helper function for printing out trace information from debugging
27162 ** binaries. This returns the string represetation of the supplied
27163 ** integer lock-type.
27164 */
27165 static const char *azFileLock(int eFileLock){
27166   switch( eFileLock ){
27167     case NO_LOCK: return "NONE";
27168     case SHARED_LOCK: return "SHARED";
27169     case RESERVED_LOCK: return "RESERVED";
27170     case PENDING_LOCK: return "PENDING";
27171     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
27172   }
27173   return "ERROR";
27174 }
27175 #endif
27176
27177 #ifdef SQLCIPHER_LOCK_TRACE
27178 /*
27179 ** Print out information about all locking operations.
27180 **
27181 ** This routine is used for troubleshooting locks on multithreaded
27182 ** platforms.  Enable by compiling with the -DSQLCIPHER_LOCK_TRACE
27183 ** command-line option on the compiler.  This code is normally
27184 ** turned off.
27185 */
27186 static int lockTrace(int fd, int op, struct flock *p){
27187   char *zOpName, *zType;
27188   int s;
27189   int savedErrno;
27190   if( op==F_GETLK ){
27191     zOpName = "GETLK";
27192   }else if( op==F_SETLK ){
27193     zOpName = "SETLK";
27194   }else{
27195     s = osFcntl(fd, op, p);
27196     sqlcipher3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
27197     return s;
27198   }
27199   if( p->l_type==F_RDLCK ){
27200     zType = "RDLCK";
27201   }else if( p->l_type==F_WRLCK ){
27202     zType = "WRLCK";
27203   }else if( p->l_type==F_UNLCK ){
27204     zType = "UNLCK";
27205   }else{
27206     assert( 0 );
27207   }
27208   assert( p->l_whence==SEEK_SET );
27209   s = osFcntl(fd, op, p);
27210   savedErrno = errno;
27211   sqlcipher3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
27212      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
27213      (int)p->l_pid, s);
27214   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
27215     struct flock l2;
27216     l2 = *p;
27217     osFcntl(fd, F_GETLK, &l2);
27218     if( l2.l_type==F_RDLCK ){
27219       zType = "RDLCK";
27220     }else if( l2.l_type==F_WRLCK ){
27221       zType = "WRLCK";
27222     }else if( l2.l_type==F_UNLCK ){
27223       zType = "UNLCK";
27224     }else{
27225       assert( 0 );
27226     }
27227     sqlcipher3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
27228        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
27229   }
27230   errno = savedErrno;
27231   return s;
27232 }
27233 #undef osFcntl
27234 #define osFcntl lockTrace
27235 #endif /* SQLCIPHER_LOCK_TRACE */
27236
27237 /*
27238 ** Retry ftruncate() calls that fail due to EINTR
27239 */
27240 static int robust_ftruncate(int h, sqlcipher3_int64 sz){
27241   int rc;
27242   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
27243   return rc;
27244 }
27245
27246 /*
27247 ** This routine translates a standard POSIX errno code into something
27248 ** useful to the clients of the sqlcipher3 functions.  Specifically, it is
27249 ** intended to translate a variety of "try again" errors into SQLCIPHER_BUSY
27250 ** and a variety of "please close the file descriptor NOW" errors into 
27251 ** SQLCIPHER_IOERR
27252 ** 
27253 ** Errors during initialization of locks, or file system support for locks,
27254 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
27255 */
27256 static int sqlcipherErrorFromPosixError(int posixError, int sqlcipherIOErr) {
27257   switch (posixError) {
27258 #if 0
27259   /* At one point this code was not commented out. In theory, this branch
27260   ** should never be hit, as this function should only be called after
27261   ** a locking-related function (i.e. fcntl()) has returned non-zero with
27262   ** the value of errno as the first argument. Since a system call has failed,
27263   ** errno should be non-zero.
27264   **
27265   ** Despite this, if errno really is zero, we still don't want to return
27266   ** SQLCIPHER_OK. The system call failed, and *some* SQLite error should be
27267   ** propagated back to the caller. Commenting this branch out means errno==0
27268   ** will be handled by the "default:" case below.
27269   */
27270   case 0: 
27271     return SQLCIPHER_OK;
27272 #endif
27273
27274   case EAGAIN:
27275   case ETIMEDOUT:
27276   case EBUSY:
27277   case EINTR:
27278   case ENOLCK:  
27279     /* random NFS retry error, unless during file system support 
27280      * introspection, in which it actually means what it says */
27281     return SQLCIPHER_BUSY;
27282     
27283   case EACCES: 
27284     /* EACCES is like EAGAIN during locking operations, but not any other time*/
27285     if( (sqlcipherIOErr == SQLCIPHER_IOERR_LOCK) || 
27286         (sqlcipherIOErr == SQLCIPHER_IOERR_UNLOCK) || 
27287         (sqlcipherIOErr == SQLCIPHER_IOERR_RDLOCK) ||
27288         (sqlcipherIOErr == SQLCIPHER_IOERR_CHECKRESERVEDLOCK) ){
27289       return SQLCIPHER_BUSY;
27290     }
27291     /* else fall through */
27292   case EPERM: 
27293     return SQLCIPHER_PERM;
27294     
27295   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
27296   ** this module never makes such a call. And the code in SQLite itself 
27297   ** asserts that SQLCIPHER_IOERR_BLOCKED is never returned. For these reasons
27298   ** this case is also commented out. If the system does set errno to EDEADLK,
27299   ** the default SQLCIPHER_IOERR_XXX code will be returned. */
27300 #if 0
27301   case EDEADLK:
27302     return SQLCIPHER_IOERR_BLOCKED;
27303 #endif
27304     
27305 #if EOPNOTSUPP!=ENOTSUP
27306   case EOPNOTSUPP: 
27307     /* something went terribly awry, unless during file system support 
27308      * introspection, in which it actually means what it says */
27309 #endif
27310 #ifdef ENOTSUP
27311   case ENOTSUP: 
27312     /* invalid fd, unless during file system support introspection, in which 
27313      * it actually means what it says */
27314 #endif
27315   case EIO:
27316   case EBADF:
27317   case EINVAL:
27318   case ENOTCONN:
27319   case ENODEV:
27320   case ENXIO:
27321   case ENOENT:
27322 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
27323   case ESTALE:
27324 #endif
27325   case ENOSYS:
27326     /* these should force the client to close the file and reconnect */
27327     
27328   default: 
27329     return sqlcipherIOErr;
27330   }
27331 }
27332
27333
27334
27335 /******************************************************************************
27336 ****************** Begin Unique File ID Utility Used By VxWorks ***************
27337 **
27338 ** On most versions of unix, we can get a unique ID for a file by concatenating
27339 ** the device number and the inode number.  But this does not work on VxWorks.
27340 ** On VxWorks, a unique file id must be based on the canonical filename.
27341 **
27342 ** A pointer to an instance of the following structure can be used as a
27343 ** unique file ID in VxWorks.  Each instance of this structure contains
27344 ** a copy of the canonical filename.  There is also a reference count.  
27345 ** The structure is reclaimed when the number of pointers to it drops to
27346 ** zero.
27347 **
27348 ** There are never very many files open at one time and lookups are not
27349 ** a performance-critical path, so it is sufficient to put these
27350 ** structures on a linked list.
27351 */
27352 struct vxworksFileId {
27353   struct vxworksFileId *pNext;  /* Next in a list of them all */
27354   int nRef;                     /* Number of references to this one */
27355   int nName;                    /* Length of the zCanonicalName[] string */
27356   char *zCanonicalName;         /* Canonical filename */
27357 };
27358
27359 #if OS_VXWORKS
27360 /* 
27361 ** All unique filenames are held on a linked list headed by this
27362 ** variable:
27363 */
27364 static struct vxworksFileId *vxworksFileList = 0;
27365
27366 /*
27367 ** Simplify a filename into its canonical form
27368 ** by making the following changes:
27369 **
27370 **  * removing any trailing and duplicate /
27371 **  * convert /./ into just /
27372 **  * convert /A/../ where A is any simple name into just /
27373 **
27374 ** Changes are made in-place.  Return the new name length.
27375 **
27376 ** The original filename is in z[0..n-1].  Return the number of
27377 ** characters in the simplified name.
27378 */
27379 static int vxworksSimplifyName(char *z, int n){
27380   int i, j;
27381   while( n>1 && z[n-1]=='/' ){ n--; }
27382   for(i=j=0; i<n; i++){
27383     if( z[i]=='/' ){
27384       if( z[i+1]=='/' ) continue;
27385       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
27386         i += 1;
27387         continue;
27388       }
27389       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
27390         while( j>0 && z[j-1]!='/' ){ j--; }
27391         if( j>0 ){ j--; }
27392         i += 2;
27393         continue;
27394       }
27395     }
27396     z[j++] = z[i];
27397   }
27398   z[j] = 0;
27399   return j;
27400 }
27401
27402 /*
27403 ** Find a unique file ID for the given absolute pathname.  Return
27404 ** a pointer to the vxworksFileId object.  This pointer is the unique
27405 ** file ID.
27406 **
27407 ** The nRef field of the vxworksFileId object is incremented before
27408 ** the object is returned.  A new vxworksFileId object is created
27409 ** and added to the global list if necessary.
27410 **
27411 ** If a memory allocation error occurs, return NULL.
27412 */
27413 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
27414   struct vxworksFileId *pNew;         /* search key and new file ID */
27415   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
27416   int n;                              /* Length of zAbsoluteName string */
27417
27418   assert( zAbsoluteName[0]=='/' );
27419   n = (int)strlen(zAbsoluteName);
27420   pNew = sqlcipher3_malloc( sizeof(*pNew) + (n+1) );
27421   if( pNew==0 ) return 0;
27422   pNew->zCanonicalName = (char*)&pNew[1];
27423   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
27424   n = vxworksSimplifyName(pNew->zCanonicalName, n);
27425
27426   /* Search for an existing entry that matching the canonical name.
27427   ** If found, increment the reference count and return a pointer to
27428   ** the existing file ID.
27429   */
27430   unixEnterMutex();
27431   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
27432     if( pCandidate->nName==n 
27433      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
27434     ){
27435        sqlcipher3_free(pNew);
27436        pCandidate->nRef++;
27437        unixLeaveMutex();
27438        return pCandidate;
27439     }
27440   }
27441
27442   /* No match was found.  We will make a new file ID */
27443   pNew->nRef = 1;
27444   pNew->nName = n;
27445   pNew->pNext = vxworksFileList;
27446   vxworksFileList = pNew;
27447   unixLeaveMutex();
27448   return pNew;
27449 }
27450
27451 /*
27452 ** Decrement the reference count on a vxworksFileId object.  Free
27453 ** the object when the reference count reaches zero.
27454 */
27455 static void vxworksReleaseFileId(struct vxworksFileId *pId){
27456   unixEnterMutex();
27457   assert( pId->nRef>0 );
27458   pId->nRef--;
27459   if( pId->nRef==0 ){
27460     struct vxworksFileId **pp;
27461     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
27462     assert( *pp==pId );
27463     *pp = pId->pNext;
27464     sqlcipher3_free(pId);
27465   }
27466   unixLeaveMutex();
27467 }
27468 #endif /* OS_VXWORKS */
27469 /*************** End of Unique File ID Utility Used By VxWorks ****************
27470 ******************************************************************************/
27471
27472
27473 /******************************************************************************
27474 *************************** Posix Advisory Locking ****************************
27475 **
27476 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
27477 ** section 6.5.2.2 lines 483 through 490 specify that when a process
27478 ** sets or clears a lock, that operation overrides any prior locks set
27479 ** by the same process.  It does not explicitly say so, but this implies
27480 ** that it overrides locks set by the same process using a different
27481 ** file descriptor.  Consider this test case:
27482 **
27483 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
27484 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
27485 **
27486 ** Suppose ./file1 and ./file2 are really the same file (because
27487 ** one is a hard or symbolic link to the other) then if you set
27488 ** an exclusive lock on fd1, then try to get an exclusive lock
27489 ** on fd2, it works.  I would have expected the second lock to
27490 ** fail since there was already a lock on the file due to fd1.
27491 ** But not so.  Since both locks came from the same process, the
27492 ** second overrides the first, even though they were on different
27493 ** file descriptors opened on different file names.
27494 **
27495 ** This means that we cannot use POSIX locks to synchronize file access
27496 ** among competing threads of the same process.  POSIX locks will work fine
27497 ** to synchronize access for threads in separate processes, but not
27498 ** threads within the same process.
27499 **
27500 ** To work around the problem, SQLite has to manage file locks internally
27501 ** on its own.  Whenever a new database is opened, we have to find the
27502 ** specific inode of the database file (the inode is determined by the
27503 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
27504 ** and check for locks already existing on that inode.  When locks are
27505 ** created or removed, we have to look at our own internal record of the
27506 ** locks to see if another thread has previously set a lock on that same
27507 ** inode.
27508 **
27509 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
27510 ** For VxWorks, we have to use the alternative unique ID system based on
27511 ** canonical filename and implemented in the previous division.)
27512 **
27513 ** The sqlcipher3_file structure for POSIX is no longer just an integer file
27514 ** descriptor.  It is now a structure that holds the integer file
27515 ** descriptor and a pointer to a structure that describes the internal
27516 ** locks on the corresponding inode.  There is one locking structure
27517 ** per inode, so if the same inode is opened twice, both unixFile structures
27518 ** point to the same locking structure.  The locking structure keeps
27519 ** a reference count (so we will know when to delete it) and a "cnt"
27520 ** field that tells us its internal lock status.  cnt==0 means the
27521 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
27522 ** cnt>0 means there are cnt shared locks on the file.
27523 **
27524 ** Any attempt to lock or unlock a file first checks the locking
27525 ** structure.  The fcntl() system call is only invoked to set a 
27526 ** POSIX lock if the internal lock structure transitions between
27527 ** a locked and an unlocked state.
27528 **
27529 ** But wait:  there are yet more problems with POSIX advisory locks.
27530 **
27531 ** If you close a file descriptor that points to a file that has locks,
27532 ** all locks on that file that are owned by the current process are
27533 ** released.  To work around this problem, each unixInodeInfo object
27534 ** maintains a count of the number of pending locks on tha inode.
27535 ** When an attempt is made to close an unixFile, if there are
27536 ** other unixFile open on the same inode that are holding locks, the call
27537 ** to close() the file descriptor is deferred until all of the locks clear.
27538 ** The unixInodeInfo structure keeps a list of file descriptors that need to
27539 ** be closed and that list is walked (and cleared) when the last lock
27540 ** clears.
27541 **
27542 ** Yet another problem:  LinuxThreads do not play well with posix locks.
27543 **
27544 ** Many older versions of linux use the LinuxThreads library which is
27545 ** not posix compliant.  Under LinuxThreads, a lock created by thread
27546 ** A cannot be modified or overridden by a different thread B.
27547 ** Only thread A can modify the lock.  Locking behavior is correct
27548 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
27549 ** on linux - with NPTL a lock created by thread A can override locks
27550 ** in thread B.  But there is no way to know at compile-time which
27551 ** threading library is being used.  So there is no way to know at
27552 ** compile-time whether or not thread A can override locks on thread B.
27553 ** One has to do a run-time check to discover the behavior of the
27554 ** current process.
27555 **
27556 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
27557 ** was dropped beginning with version 3.7.0.  SQLite will still work with
27558 ** LinuxThreads provided that (1) there is no more than one connection 
27559 ** per database file in the same process and (2) database connections
27560 ** do not move across threads.
27561 */
27562
27563 /*
27564 ** An instance of the following structure serves as the key used
27565 ** to locate a particular unixInodeInfo object.
27566 */
27567 struct unixFileId {
27568   dev_t dev;                  /* Device number */
27569 #if OS_VXWORKS
27570   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
27571 #else
27572   ino_t ino;                  /* Inode number */
27573 #endif
27574 };
27575
27576 /*
27577 ** An instance of the following structure is allocated for each open
27578 ** inode.  Or, on LinuxThreads, there is one of these structures for
27579 ** each inode opened by each thread.
27580 **
27581 ** A single inode can have multiple file descriptors, so each unixFile
27582 ** structure contains a pointer to an instance of this object and this
27583 ** object keeps a count of the number of unixFile pointing to it.
27584 */
27585 struct unixInodeInfo {
27586   struct unixFileId fileId;       /* The lookup key */
27587   int nShared;                    /* Number of SHARED locks held */
27588   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
27589   unsigned char bProcessLock;     /* An exclusive process lock is held */
27590   int nRef;                       /* Number of pointers to this structure */
27591   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
27592   int nLock;                      /* Number of outstanding file locks */
27593   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
27594   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
27595   unixInodeInfo *pPrev;           /*    .... doubly linked */
27596 #if SQLCIPHER_ENABLE_LOCKING_STYLE
27597   unsigned long long sharedByte;  /* for AFP simulated shared lock */
27598 #endif
27599 #if OS_VXWORKS
27600   sem_t *pSem;                    /* Named POSIX semaphore */
27601   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
27602 #endif
27603 };
27604
27605 /*
27606 ** A lists of all unixInodeInfo objects.
27607 */
27608 static unixInodeInfo *inodeList = 0;
27609
27610 /*
27611 **
27612 ** This function - unixLogError_x(), is only ever called via the macro
27613 ** unixLogError().
27614 **
27615 ** It is invoked after an error occurs in an OS function and errno has been
27616 ** set. It logs a message using sqlcipher3_log() containing the current value of
27617 ** errno and, if possible, the human-readable equivalent from strerror() or
27618 ** strerror_r().
27619 **
27620 ** The first argument passed to the macro should be the error code that
27621 ** will be returned to SQLite (e.g. SQLCIPHER_IOERR_DELETE, SQLCIPHER_CANTOPEN). 
27622 ** The two subsequent arguments should be the name of the OS function that
27623 ** failed (e.g. "unlink", "open") and the the associated file-system path,
27624 ** if any.
27625 */
27626 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
27627 static int unixLogErrorAtLine(
27628   int errcode,                    /* SQLite error code */
27629   const char *zFunc,              /* Name of OS function that failed */
27630   const char *zPath,              /* File path associated with error */
27631   int iLine                       /* Source line number where error occurred */
27632 ){
27633   char *zErr;                     /* Message from strerror() or equivalent */
27634   int iErrno = errno;             /* Saved syscall error number */
27635
27636   /* If this is not a threadsafe build (SQLCIPHER_THREADSAFE==0), then use
27637   ** the strerror() function to obtain the human-readable error message
27638   ** equivalent to errno. Otherwise, use strerror_r().
27639   */ 
27640 #if SQLCIPHER_THREADSAFE && defined(HAVE_STRERROR_R)
27641   char aErr[80];
27642   memset(aErr, 0, sizeof(aErr));
27643   zErr = aErr;
27644
27645   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
27646   ** assume that the system provides the the GNU version of strerror_r() that 
27647   ** returns a pointer to a buffer containing the error message. That pointer 
27648   ** may point to aErr[], or it may point to some static storage somewhere. 
27649   ** Otherwise, assume that the system provides the POSIX version of 
27650   ** strerror_r(), which always writes an error message into aErr[].
27651   **
27652   ** If the code incorrectly assumes that it is the POSIX version that is
27653   ** available, the error message will often be an empty string. Not a
27654   ** huge problem. Incorrectly concluding that the GNU version is available 
27655   ** could lead to a segfault though.
27656   */
27657 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
27658   zErr = 
27659 # endif
27660   strerror_r(iErrno, aErr, sizeof(aErr)-1);
27661
27662 #elif SQLCIPHER_THREADSAFE
27663   /* This is a threadsafe build, but strerror_r() is not available. */
27664   zErr = "";
27665 #else
27666   /* Non-threadsafe build, use strerror(). */
27667   zErr = strerror(iErrno);
27668 #endif
27669
27670   assert( errcode!=SQLCIPHER_OK );
27671   if( zPath==0 ) zPath = "";
27672   sqlcipher3_log(errcode,
27673       "os_unix.c:%d: (%d) %s(%s) - %s",
27674       iLine, iErrno, zFunc, zPath, zErr
27675   );
27676
27677   return errcode;
27678 }
27679
27680 /*
27681 ** Close a file descriptor.
27682 **
27683 ** We assume that close() almost always works, since it is only in a
27684 ** very sick application or on a very sick platform that it might fail.
27685 ** If it does fail, simply leak the file descriptor, but do log the
27686 ** error.
27687 **
27688 ** Note that it is not safe to retry close() after EINTR since the
27689 ** file descriptor might have already been reused by another thread.
27690 ** So we don't even try to recover from an EINTR.  Just log the error
27691 ** and move on.
27692 */
27693 static void robust_close(unixFile *pFile, int h, int lineno){
27694   if( osClose(h) ){
27695     unixLogErrorAtLine(SQLCIPHER_IOERR_CLOSE, "close",
27696                        pFile ? pFile->zPath : 0, lineno);
27697   }
27698 }
27699
27700 /*
27701 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
27702 */ 
27703 static void closePendingFds(unixFile *pFile){
27704   unixInodeInfo *pInode = pFile->pInode;
27705   UnixUnusedFd *p;
27706   UnixUnusedFd *pNext;
27707   for(p=pInode->pUnused; p; p=pNext){
27708     pNext = p->pNext;
27709     robust_close(pFile, p->fd, __LINE__);
27710     sqlcipher3_free(p);
27711   }
27712   pInode->pUnused = 0;
27713 }
27714
27715 /*
27716 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
27717 **
27718 ** The mutex entered using the unixEnterMutex() function must be held
27719 ** when this function is called.
27720 */
27721 static void releaseInodeInfo(unixFile *pFile){
27722   unixInodeInfo *pInode = pFile->pInode;
27723   assert( unixMutexHeld() );
27724   if( ALWAYS(pInode) ){
27725     pInode->nRef--;
27726     if( pInode->nRef==0 ){
27727       assert( pInode->pShmNode==0 );
27728       closePendingFds(pFile);
27729       if( pInode->pPrev ){
27730         assert( pInode->pPrev->pNext==pInode );
27731         pInode->pPrev->pNext = pInode->pNext;
27732       }else{
27733         assert( inodeList==pInode );
27734         inodeList = pInode->pNext;
27735       }
27736       if( pInode->pNext ){
27737         assert( pInode->pNext->pPrev==pInode );
27738         pInode->pNext->pPrev = pInode->pPrev;
27739       }
27740       sqlcipher3_free(pInode);
27741     }
27742   }
27743 }
27744
27745 /*
27746 ** Given a file descriptor, locate the unixInodeInfo object that
27747 ** describes that file descriptor.  Create a new one if necessary.  The
27748 ** return value might be uninitialized if an error occurs.
27749 **
27750 ** The mutex entered using the unixEnterMutex() function must be held
27751 ** when this function is called.
27752 **
27753 ** Return an appropriate error code.
27754 */
27755 static int findInodeInfo(
27756   unixFile *pFile,               /* Unix file with file desc used in the key */
27757   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
27758 ){
27759   int rc;                        /* System call return code */
27760   int fd;                        /* The file descriptor for pFile */
27761   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
27762   struct stat statbuf;           /* Low-level file information */
27763   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
27764
27765   assert( unixMutexHeld() );
27766
27767   /* Get low-level information about the file that we can used to
27768   ** create a unique name for the file.
27769   */
27770   fd = pFile->h;
27771   rc = osFstat(fd, &statbuf);
27772   if( rc!=0 ){
27773     pFile->lastErrno = errno;
27774 #ifdef EOVERFLOW
27775     if( pFile->lastErrno==EOVERFLOW ) return SQLCIPHER_NOLFS;
27776 #endif
27777     return SQLCIPHER_IOERR;
27778   }
27779
27780 #ifdef __APPLE__
27781   /* On OS X on an msdos filesystem, the inode number is reported
27782   ** incorrectly for zero-size files.  See ticket #3260.  To work
27783   ** around this problem (we consider it a bug in OS X, not SQLite)
27784   ** we always increase the file size to 1 by writing a single byte
27785   ** prior to accessing the inode number.  The one byte written is
27786   ** an ASCII 'S' character which also happens to be the first byte
27787   ** in the header of every SQLite database.  In this way, if there
27788   ** is a race condition such that another thread has already populated
27789   ** the first page of the database, no damage is done.
27790   */
27791   if( statbuf.st_size==0 && (pFile->fsFlags & SQLCIPHER_FSFLAGS_IS_MSDOS)!=0 ){
27792     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
27793     if( rc!=1 ){
27794       pFile->lastErrno = errno;
27795       return SQLCIPHER_IOERR;
27796     }
27797     rc = osFstat(fd, &statbuf);
27798     if( rc!=0 ){
27799       pFile->lastErrno = errno;
27800       return SQLCIPHER_IOERR;
27801     }
27802   }
27803 #endif
27804
27805   memset(&fileId, 0, sizeof(fileId));
27806   fileId.dev = statbuf.st_dev;
27807 #if OS_VXWORKS
27808   fileId.pId = pFile->pId;
27809 #else
27810   fileId.ino = statbuf.st_ino;
27811 #endif
27812   pInode = inodeList;
27813   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
27814     pInode = pInode->pNext;
27815   }
27816   if( pInode==0 ){
27817     pInode = sqlcipher3_malloc( sizeof(*pInode) );
27818     if( pInode==0 ){
27819       return SQLCIPHER_NOMEM;
27820     }
27821     memset(pInode, 0, sizeof(*pInode));
27822     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
27823     pInode->nRef = 1;
27824     pInode->pNext = inodeList;
27825     pInode->pPrev = 0;
27826     if( inodeList ) inodeList->pPrev = pInode;
27827     inodeList = pInode;
27828   }else{
27829     pInode->nRef++;
27830   }
27831   *ppInode = pInode;
27832   return SQLCIPHER_OK;
27833 }
27834
27835
27836 /*
27837 ** This routine checks if there is a RESERVED lock held on the specified
27838 ** file by this or any other process. If such a lock is held, set *pResOut
27839 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27840 ** is set to SQLCIPHER_OK unless an I/O error occurs during lock checking.
27841 */
27842 static int unixCheckReservedLock(sqlcipher3_file *id, int *pResOut){
27843   int rc = SQLCIPHER_OK;
27844   int reserved = 0;
27845   unixFile *pFile = (unixFile*)id;
27846
27847   SimulateIOError( return SQLCIPHER_IOERR_CHECKRESERVEDLOCK; );
27848
27849   assert( pFile );
27850   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
27851
27852   /* Check if a thread in this process holds such a lock */
27853   if( pFile->pInode->eFileLock>SHARED_LOCK ){
27854     reserved = 1;
27855   }
27856
27857   /* Otherwise see if some other process holds it.
27858   */
27859 #ifndef __DJGPP__
27860   if( !reserved && !pFile->pInode->bProcessLock ){
27861     struct flock lock;
27862     lock.l_whence = SEEK_SET;
27863     lock.l_start = RESERVED_BYTE;
27864     lock.l_len = 1;
27865     lock.l_type = F_WRLCK;
27866     if( osFcntl(pFile->h, F_GETLK, &lock) ){
27867       rc = SQLCIPHER_IOERR_CHECKRESERVEDLOCK;
27868       pFile->lastErrno = errno;
27869     } else if( lock.l_type!=F_UNLCK ){
27870       reserved = 1;
27871     }
27872   }
27873 #endif
27874   
27875   unixLeaveMutex();
27876   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
27877
27878   *pResOut = reserved;
27879   return rc;
27880 }
27881
27882 /*
27883 ** Attempt to set a system-lock on the file pFile.  The lock is 
27884 ** described by pLock.
27885 **
27886 ** If the pFile was opened read/write from unix-excl, then the only lock
27887 ** ever obtained is an exclusive lock, and it is obtained exactly once
27888 ** the first time any lock is attempted.  All subsequent system locking
27889 ** operations become no-ops.  Locking operations still happen internally,
27890 ** in order to coordinate access between separate database connections
27891 ** within this process, but all of that is handled in memory and the
27892 ** operating system does not participate.
27893 **
27894 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
27895 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
27896 ** and is read-only.
27897 **
27898 ** Zero is returned if the call completes successfully, or -1 if a call
27899 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
27900 */
27901 static int unixFileLock(unixFile *pFile, struct flock *pLock){
27902   int rc;
27903   unixInodeInfo *pInode = pFile->pInode;
27904   assert( unixMutexHeld() );
27905   assert( pInode!=0 );
27906   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
27907    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
27908   ){
27909     if( pInode->bProcessLock==0 ){
27910       struct flock lock;
27911       assert( pInode->nLock==0 );
27912       lock.l_whence = SEEK_SET;
27913       lock.l_start = SHARED_FIRST;
27914       lock.l_len = SHARED_SIZE;
27915       lock.l_type = F_WRLCK;
27916       rc = osFcntl(pFile->h, F_SETLK, &lock);
27917       if( rc<0 ) return rc;
27918       pInode->bProcessLock = 1;
27919       pInode->nLock++;
27920     }else{
27921       rc = 0;
27922     }
27923   }else{
27924     rc = osFcntl(pFile->h, F_SETLK, pLock);
27925   }
27926   return rc;
27927 }
27928
27929 /*
27930 ** Lock the file with the lock specified by parameter eFileLock - one
27931 ** of the following:
27932 **
27933 **     (1) SHARED_LOCK
27934 **     (2) RESERVED_LOCK
27935 **     (3) PENDING_LOCK
27936 **     (4) EXCLUSIVE_LOCK
27937 **
27938 ** Sometimes when requesting one lock state, additional lock states
27939 ** are inserted in between.  The locking might fail on one of the later
27940 ** transitions leaving the lock state different from what it started but
27941 ** still short of its goal.  The following chart shows the allowed
27942 ** transitions and the inserted intermediate states:
27943 **
27944 **    UNLOCKED -> SHARED
27945 **    SHARED -> RESERVED
27946 **    SHARED -> (PENDING) -> EXCLUSIVE
27947 **    RESERVED -> (PENDING) -> EXCLUSIVE
27948 **    PENDING -> EXCLUSIVE
27949 **
27950 ** This routine will only increase a lock.  Use the sqlcipher3OsUnlock()
27951 ** routine to lower a locking level.
27952 */
27953 static int unixLock(sqlcipher3_file *id, int eFileLock){
27954   /* The following describes the implementation of the various locks and
27955   ** lock transitions in terms of the POSIX advisory shared and exclusive
27956   ** lock primitives (called read-locks and write-locks below, to avoid
27957   ** confusion with SQLite lock names). The algorithms are complicated
27958   ** slightly in order to be compatible with windows systems simultaneously
27959   ** accessing the same database file, in case that is ever required.
27960   **
27961   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
27962   ** byte', each single bytes at well known offsets, and the 'shared byte
27963   ** range', a range of 510 bytes at a well known offset.
27964   **
27965   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
27966   ** byte'.  If this is successful, a random byte from the 'shared byte
27967   ** range' is read-locked and the lock on the 'pending byte' released.
27968   **
27969   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
27970   ** A RESERVED lock is implemented by grabbing a write-lock on the
27971   ** 'reserved byte'. 
27972   **
27973   ** A process may only obtain a PENDING lock after it has obtained a
27974   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
27975   ** on the 'pending byte'. This ensures that no new SHARED locks can be
27976   ** obtained, but existing SHARED locks are allowed to persist. A process
27977   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
27978   ** This property is used by the algorithm for rolling back a journal file
27979   ** after a crash.
27980   **
27981   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
27982   ** implemented by obtaining a write-lock on the entire 'shared byte
27983   ** range'. Since all other locks require a read-lock on one of the bytes
27984   ** within this range, this ensures that no other locks are held on the
27985   ** database. 
27986   **
27987   ** The reason a single byte cannot be used instead of the 'shared byte
27988   ** range' is that some versions of windows do not support read-locks. By
27989   ** locking a random byte from a range, concurrent SHARED locks may exist
27990   ** even if the locking primitive used is always a write-lock.
27991   */
27992   int rc = SQLCIPHER_OK;
27993   unixFile *pFile = (unixFile*)id;
27994   unixInodeInfo *pInode;
27995   struct flock lock;
27996   int tErrno = 0;
27997
27998   assert( pFile );
27999   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
28000       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
28001       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
28002
28003   /* If there is already a lock of this type or more restrictive on the
28004   ** unixFile, do nothing. Don't use the end_lock: exit path, as
28005   ** unixEnterMutex() hasn't been called yet.
28006   */
28007   if( pFile->eFileLock>=eFileLock ){
28008     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
28009             azFileLock(eFileLock)));
28010     return SQLCIPHER_OK;
28011   }
28012
28013   /* Make sure the locking sequence is correct.
28014   **  (1) We never move from unlocked to anything higher than shared lock.
28015   **  (2) SQLite never explicitly requests a pendig lock.
28016   **  (3) A shared lock is always held when a reserve lock is requested.
28017   */
28018   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
28019   assert( eFileLock!=PENDING_LOCK );
28020   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
28021
28022   /* This mutex is needed because pFile->pInode is shared across threads
28023   */
28024   unixEnterMutex();
28025   pInode = pFile->pInode;
28026
28027   /* If some thread using this PID has a lock via a different unixFile*
28028   ** handle that precludes the requested lock, return BUSY.
28029   */
28030   if( (pFile->eFileLock!=pInode->eFileLock && 
28031           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
28032   ){
28033     rc = SQLCIPHER_BUSY;
28034     goto end_lock;
28035   }
28036
28037   /* If a SHARED lock is requested, and some thread using this PID already
28038   ** has a SHARED or RESERVED lock, then increment reference counts and
28039   ** return SQLCIPHER_OK.
28040   */
28041   if( eFileLock==SHARED_LOCK && 
28042       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
28043     assert( eFileLock==SHARED_LOCK );
28044     assert( pFile->eFileLock==0 );
28045     assert( pInode->nShared>0 );
28046     pFile->eFileLock = SHARED_LOCK;
28047     pInode->nShared++;
28048     pInode->nLock++;
28049     goto end_lock;
28050   }
28051
28052
28053   /* A PENDING lock is needed before acquiring a SHARED lock and before
28054   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
28055   ** be released.
28056   */
28057   lock.l_len = 1L;
28058   lock.l_whence = SEEK_SET;
28059   if( eFileLock==SHARED_LOCK 
28060       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
28061   ){
28062     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
28063     lock.l_start = PENDING_BYTE;
28064     if( unixFileLock(pFile, &lock) ){
28065       tErrno = errno;
28066       rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_LOCK);
28067       if( rc!=SQLCIPHER_BUSY ){
28068         pFile->lastErrno = tErrno;
28069       }
28070       goto end_lock;
28071     }
28072   }
28073
28074
28075   /* If control gets to this point, then actually go ahead and make
28076   ** operating system calls for the specified lock.
28077   */
28078   if( eFileLock==SHARED_LOCK ){
28079     assert( pInode->nShared==0 );
28080     assert( pInode->eFileLock==0 );
28081     assert( rc==SQLCIPHER_OK );
28082
28083     /* Now get the read-lock */
28084     lock.l_start = SHARED_FIRST;
28085     lock.l_len = SHARED_SIZE;
28086     if( unixFileLock(pFile, &lock) ){
28087       tErrno = errno;
28088       rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_LOCK);
28089     }
28090
28091     /* Drop the temporary PENDING lock */
28092     lock.l_start = PENDING_BYTE;
28093     lock.l_len = 1L;
28094     lock.l_type = F_UNLCK;
28095     if( unixFileLock(pFile, &lock) && rc==SQLCIPHER_OK ){
28096       /* This could happen with a network mount */
28097       tErrno = errno;
28098       rc = SQLCIPHER_IOERR_UNLOCK; 
28099     }
28100
28101     if( rc ){
28102       if( rc!=SQLCIPHER_BUSY ){
28103         pFile->lastErrno = tErrno;
28104       }
28105       goto end_lock;
28106     }else{
28107       pFile->eFileLock = SHARED_LOCK;
28108       pInode->nLock++;
28109       pInode->nShared = 1;
28110     }
28111   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
28112     /* We are trying for an exclusive lock but another thread in this
28113     ** same process is still holding a shared lock. */
28114     rc = SQLCIPHER_BUSY;
28115   }else{
28116     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
28117     ** assumed that there is a SHARED or greater lock on the file
28118     ** already.
28119     */
28120     assert( 0!=pFile->eFileLock );
28121     lock.l_type = F_WRLCK;
28122
28123     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
28124     if( eFileLock==RESERVED_LOCK ){
28125       lock.l_start = RESERVED_BYTE;
28126       lock.l_len = 1L;
28127     }else{
28128       lock.l_start = SHARED_FIRST;
28129       lock.l_len = SHARED_SIZE;
28130     }
28131
28132     if( unixFileLock(pFile, &lock) ){
28133       tErrno = errno;
28134       rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_LOCK);
28135       if( rc!=SQLCIPHER_BUSY ){
28136         pFile->lastErrno = tErrno;
28137       }
28138     }
28139   }
28140   
28141
28142 #ifndef NDEBUG
28143   /* Set up the transaction-counter change checking flags when
28144   ** transitioning from a SHARED to a RESERVED lock.  The change
28145   ** from SHARED to RESERVED marks the beginning of a normal
28146   ** write operation (not a hot journal rollback).
28147   */
28148   if( rc==SQLCIPHER_OK
28149    && pFile->eFileLock<=SHARED_LOCK
28150    && eFileLock==RESERVED_LOCK
28151   ){
28152     pFile->transCntrChng = 0;
28153     pFile->dbUpdate = 0;
28154     pFile->inNormalWrite = 1;
28155   }
28156 #endif
28157
28158
28159   if( rc==SQLCIPHER_OK ){
28160     pFile->eFileLock = eFileLock;
28161     pInode->eFileLock = eFileLock;
28162   }else if( eFileLock==EXCLUSIVE_LOCK ){
28163     pFile->eFileLock = PENDING_LOCK;
28164     pInode->eFileLock = PENDING_LOCK;
28165   }
28166
28167 end_lock:
28168   unixLeaveMutex();
28169   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
28170       rc==SQLCIPHER_OK ? "ok" : "failed"));
28171   return rc;
28172 }
28173
28174 /*
28175 ** Add the file descriptor used by file handle pFile to the corresponding
28176 ** pUnused list.
28177 */
28178 static void setPendingFd(unixFile *pFile){
28179   unixInodeInfo *pInode = pFile->pInode;
28180   UnixUnusedFd *p = pFile->pUnused;
28181   p->pNext = pInode->pUnused;
28182   pInode->pUnused = p;
28183   pFile->h = -1;
28184   pFile->pUnused = 0;
28185 }
28186
28187 /*
28188 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28189 ** must be either NO_LOCK or SHARED_LOCK.
28190 **
28191 ** If the locking level of the file descriptor is already at or below
28192 ** the requested locking level, this routine is a no-op.
28193 ** 
28194 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
28195 ** the byte range is divided into 2 parts and the first part is unlocked then
28196 ** set to a read lock, then the other part is simply unlocked.  This works 
28197 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
28198 ** remove the write lock on a region when a read lock is set.
28199 */
28200 static int posixUnlock(sqlcipher3_file *id, int eFileLock, int handleNFSUnlock){
28201   unixFile *pFile = (unixFile*)id;
28202   unixInodeInfo *pInode;
28203   struct flock lock;
28204   int rc = SQLCIPHER_OK;
28205
28206   assert( pFile );
28207   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
28208       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
28209       getpid()));
28210
28211   assert( eFileLock<=SHARED_LOCK );
28212   if( pFile->eFileLock<=eFileLock ){
28213     return SQLCIPHER_OK;
28214   }
28215   unixEnterMutex();
28216   pInode = pFile->pInode;
28217   assert( pInode->nShared!=0 );
28218   if( pFile->eFileLock>SHARED_LOCK ){
28219     assert( pInode->eFileLock==pFile->eFileLock );
28220
28221 #ifndef NDEBUG
28222     /* When reducing a lock such that other processes can start
28223     ** reading the database file again, make sure that the
28224     ** transaction counter was updated if any part of the database
28225     ** file changed.  If the transaction counter is not updated,
28226     ** other connections to the same file might not realize that
28227     ** the file has changed and hence might not know to flush their
28228     ** cache.  The use of a stale cache can lead to database corruption.
28229     */
28230     pFile->inNormalWrite = 0;
28231 #endif
28232
28233     /* downgrading to a shared lock on NFS involves clearing the write lock
28234     ** before establishing the readlock - to avoid a race condition we downgrade
28235     ** the lock in 2 blocks, so that part of the range will be covered by a 
28236     ** write lock until the rest is covered by a read lock:
28237     **  1:   [WWWWW]
28238     **  2:   [....W]
28239     **  3:   [RRRRW]
28240     **  4:   [RRRR.]
28241     */
28242     if( eFileLock==SHARED_LOCK ){
28243
28244 #if !defined(__APPLE__) || !SQLCIPHER_ENABLE_LOCKING_STYLE
28245       (void)handleNFSUnlock;
28246       assert( handleNFSUnlock==0 );
28247 #endif
28248 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
28249       if( handleNFSUnlock ){
28250         int tErrno;               /* Error code from system call errors */
28251         off_t divSize = SHARED_SIZE - 1;
28252         
28253         lock.l_type = F_UNLCK;
28254         lock.l_whence = SEEK_SET;
28255         lock.l_start = SHARED_FIRST;
28256         lock.l_len = divSize;
28257         if( unixFileLock(pFile, &lock)==(-1) ){
28258           tErrno = errno;
28259           rc = SQLCIPHER_IOERR_UNLOCK;
28260           if( IS_LOCK_ERROR(rc) ){
28261             pFile->lastErrno = tErrno;
28262           }
28263           goto end_unlock;
28264         }
28265         lock.l_type = F_RDLCK;
28266         lock.l_whence = SEEK_SET;
28267         lock.l_start = SHARED_FIRST;
28268         lock.l_len = divSize;
28269         if( unixFileLock(pFile, &lock)==(-1) ){
28270           tErrno = errno;
28271           rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_RDLOCK);
28272           if( IS_LOCK_ERROR(rc) ){
28273             pFile->lastErrno = tErrno;
28274           }
28275           goto end_unlock;
28276         }
28277         lock.l_type = F_UNLCK;
28278         lock.l_whence = SEEK_SET;
28279         lock.l_start = SHARED_FIRST+divSize;
28280         lock.l_len = SHARED_SIZE-divSize;
28281         if( unixFileLock(pFile, &lock)==(-1) ){
28282           tErrno = errno;
28283           rc = SQLCIPHER_IOERR_UNLOCK;
28284           if( IS_LOCK_ERROR(rc) ){
28285             pFile->lastErrno = tErrno;
28286           }
28287           goto end_unlock;
28288         }
28289       }else
28290 #endif /* defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE */
28291       {
28292         lock.l_type = F_RDLCK;
28293         lock.l_whence = SEEK_SET;
28294         lock.l_start = SHARED_FIRST;
28295         lock.l_len = SHARED_SIZE;
28296         if( unixFileLock(pFile, &lock) ){
28297           /* In theory, the call to unixFileLock() cannot fail because another
28298           ** process is holding an incompatible lock. If it does, this 
28299           ** indicates that the other process is not following the locking
28300           ** protocol. If this happens, return SQLCIPHER_IOERR_RDLOCK. Returning
28301           ** SQLCIPHER_BUSY would confuse the upper layer (in practice it causes 
28302           ** an assert to fail). */ 
28303           rc = SQLCIPHER_IOERR_RDLOCK;
28304           pFile->lastErrno = errno;
28305           goto end_unlock;
28306         }
28307       }
28308     }
28309     lock.l_type = F_UNLCK;
28310     lock.l_whence = SEEK_SET;
28311     lock.l_start = PENDING_BYTE;
28312     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
28313     if( unixFileLock(pFile, &lock)==0 ){
28314       pInode->eFileLock = SHARED_LOCK;
28315     }else{
28316       rc = SQLCIPHER_IOERR_UNLOCK;
28317       pFile->lastErrno = errno;
28318       goto end_unlock;
28319     }
28320   }
28321   if( eFileLock==NO_LOCK ){
28322     /* Decrement the shared lock counter.  Release the lock using an
28323     ** OS call only when all threads in this same process have released
28324     ** the lock.
28325     */
28326     pInode->nShared--;
28327     if( pInode->nShared==0 ){
28328       lock.l_type = F_UNLCK;
28329       lock.l_whence = SEEK_SET;
28330       lock.l_start = lock.l_len = 0L;
28331       if( unixFileLock(pFile, &lock)==0 ){
28332         pInode->eFileLock = NO_LOCK;
28333       }else{
28334         rc = SQLCIPHER_IOERR_UNLOCK;
28335         pFile->lastErrno = errno;
28336         pInode->eFileLock = NO_LOCK;
28337         pFile->eFileLock = NO_LOCK;
28338       }
28339     }
28340
28341     /* Decrement the count of locks against this same file.  When the
28342     ** count reaches zero, close any other file descriptors whose close
28343     ** was deferred because of outstanding locks.
28344     */
28345     pInode->nLock--;
28346     assert( pInode->nLock>=0 );
28347     if( pInode->nLock==0 ){
28348       closePendingFds(pFile);
28349     }
28350   }
28351         
28352 end_unlock:
28353   unixLeaveMutex();
28354   if( rc==SQLCIPHER_OK ) pFile->eFileLock = eFileLock;
28355   return rc;
28356 }
28357
28358 /*
28359 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28360 ** must be either NO_LOCK or SHARED_LOCK.
28361 **
28362 ** If the locking level of the file descriptor is already at or below
28363 ** the requested locking level, this routine is a no-op.
28364 */
28365 static int unixUnlock(sqlcipher3_file *id, int eFileLock){
28366   return posixUnlock(id, eFileLock, 0);
28367 }
28368
28369 /*
28370 ** This function performs the parts of the "close file" operation 
28371 ** common to all locking schemes. It closes the directory and file
28372 ** handles, if they are valid, and sets all fields of the unixFile
28373 ** structure to 0.
28374 **
28375 ** It is *not* necessary to hold the mutex when this routine is called,
28376 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
28377 ** vxworksReleaseFileId() routine.
28378 */
28379 static int closeUnixFile(sqlcipher3_file *id){
28380   unixFile *pFile = (unixFile*)id;
28381   if( pFile->h>=0 ){
28382     robust_close(pFile, pFile->h, __LINE__);
28383     pFile->h = -1;
28384   }
28385 #if OS_VXWORKS
28386   if( pFile->pId ){
28387     if( pFile->isDelete ){
28388       osUnlink(pFile->pId->zCanonicalName);
28389     }
28390     vxworksReleaseFileId(pFile->pId);
28391     pFile->pId = 0;
28392   }
28393 #endif
28394   OSTRACE(("CLOSE   %-3d\n", pFile->h));
28395   OpenCounter(-1);
28396   sqlcipher3_free(pFile->pUnused);
28397   memset(pFile, 0, sizeof(unixFile));
28398   return SQLCIPHER_OK;
28399 }
28400
28401 /*
28402 ** Close a file.
28403 */
28404 static int unixClose(sqlcipher3_file *id){
28405   int rc = SQLCIPHER_OK;
28406   unixFile *pFile = (unixFile *)id;
28407   unixUnlock(id, NO_LOCK);
28408   unixEnterMutex();
28409
28410   /* unixFile.pInode is always valid here. Otherwise, a different close
28411   ** routine (e.g. nolockClose()) would be called instead.
28412   */
28413   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
28414   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
28415     /* If there are outstanding locks, do not actually close the file just
28416     ** yet because that would clear those locks.  Instead, add the file
28417     ** descriptor to pInode->pUnused list.  It will be automatically closed 
28418     ** when the last lock is cleared.
28419     */
28420     setPendingFd(pFile);
28421   }
28422   releaseInodeInfo(pFile);
28423   rc = closeUnixFile(id);
28424   unixLeaveMutex();
28425   return rc;
28426 }
28427
28428 /************** End of the posix advisory lock implementation *****************
28429 ******************************************************************************/
28430
28431 /******************************************************************************
28432 ****************************** No-op Locking **********************************
28433 **
28434 ** Of the various locking implementations available, this is by far the
28435 ** simplest:  locking is ignored.  No attempt is made to lock the database
28436 ** file for reading or writing.
28437 **
28438 ** This locking mode is appropriate for use on read-only databases
28439 ** (ex: databases that are burned into CD-ROM, for example.)  It can
28440 ** also be used if the application employs some external mechanism to
28441 ** prevent simultaneous access of the same database by two or more
28442 ** database connections.  But there is a serious risk of database
28443 ** corruption if this locking mode is used in situations where multiple
28444 ** database connections are accessing the same database file at the same
28445 ** time and one or more of those connections are writing.
28446 */
28447
28448 static int nolockCheckReservedLock(sqlcipher3_file *NotUsed, int *pResOut){
28449   UNUSED_PARAMETER(NotUsed);
28450   *pResOut = 0;
28451   return SQLCIPHER_OK;
28452 }
28453 static int nolockLock(sqlcipher3_file *NotUsed, int NotUsed2){
28454   UNUSED_PARAMETER2(NotUsed, NotUsed2);
28455   return SQLCIPHER_OK;
28456 }
28457 static int nolockUnlock(sqlcipher3_file *NotUsed, int NotUsed2){
28458   UNUSED_PARAMETER2(NotUsed, NotUsed2);
28459   return SQLCIPHER_OK;
28460 }
28461
28462 /*
28463 ** Close the file.
28464 */
28465 static int nolockClose(sqlcipher3_file *id) {
28466   return closeUnixFile(id);
28467 }
28468
28469 /******************* End of the no-op lock implementation *********************
28470 ******************************************************************************/
28471
28472 /******************************************************************************
28473 ************************* Begin dot-file Locking ******************************
28474 **
28475 ** The dotfile locking implementation uses the existance of separate lock
28476 ** files in order to control access to the database.  This works on just
28477 ** about every filesystem imaginable.  But there are serious downsides:
28478 **
28479 **    (1)  There is zero concurrency.  A single reader blocks all other
28480 **         connections from reading or writing the database.
28481 **
28482 **    (2)  An application crash or power loss can leave stale lock files
28483 **         sitting around that need to be cleared manually.
28484 **
28485 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
28486 ** other locking strategy is available.
28487 **
28488 ** Dotfile locking works by creating a file in the same directory as the
28489 ** database and with the same name but with a ".lock" extension added.
28490 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
28491 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
28492 */
28493
28494 /*
28495 ** The file suffix added to the data base filename in order to create the
28496 ** lock file.
28497 */
28498 #define DOTLOCK_SUFFIX ".lock"
28499
28500 /*
28501 ** This routine checks if there is a RESERVED lock held on the specified
28502 ** file by this or any other process. If such a lock is held, set *pResOut
28503 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
28504 ** is set to SQLCIPHER_OK unless an I/O error occurs during lock checking.
28505 **
28506 ** In dotfile locking, either a lock exists or it does not.  So in this
28507 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
28508 ** is held on the file and false if the file is unlocked.
28509 */
28510 static int dotlockCheckReservedLock(sqlcipher3_file *id, int *pResOut) {
28511   int rc = SQLCIPHER_OK;
28512   int reserved = 0;
28513   unixFile *pFile = (unixFile*)id;
28514
28515   SimulateIOError( return SQLCIPHER_IOERR_CHECKRESERVEDLOCK; );
28516   
28517   assert( pFile );
28518
28519   /* Check if a thread in this process holds such a lock */
28520   if( pFile->eFileLock>SHARED_LOCK ){
28521     /* Either this connection or some other connection in the same process
28522     ** holds a lock on the file.  No need to check further. */
28523     reserved = 1;
28524   }else{
28525     /* The lock is held if and only if the lockfile exists */
28526     const char *zLockFile = (const char*)pFile->lockingContext;
28527     reserved = osAccess(zLockFile, 0)==0;
28528   }
28529   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
28530   *pResOut = reserved;
28531   return rc;
28532 }
28533
28534 /*
28535 ** Lock the file with the lock specified by parameter eFileLock - one
28536 ** of the following:
28537 **
28538 **     (1) SHARED_LOCK
28539 **     (2) RESERVED_LOCK
28540 **     (3) PENDING_LOCK
28541 **     (4) EXCLUSIVE_LOCK
28542 **
28543 ** Sometimes when requesting one lock state, additional lock states
28544 ** are inserted in between.  The locking might fail on one of the later
28545 ** transitions leaving the lock state different from what it started but
28546 ** still short of its goal.  The following chart shows the allowed
28547 ** transitions and the inserted intermediate states:
28548 **
28549 **    UNLOCKED -> SHARED
28550 **    SHARED -> RESERVED
28551 **    SHARED -> (PENDING) -> EXCLUSIVE
28552 **    RESERVED -> (PENDING) -> EXCLUSIVE
28553 **    PENDING -> EXCLUSIVE
28554 **
28555 ** This routine will only increase a lock.  Use the sqlcipher3OsUnlock()
28556 ** routine to lower a locking level.
28557 **
28558 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
28559 ** But we track the other locking levels internally.
28560 */
28561 static int dotlockLock(sqlcipher3_file *id, int eFileLock) {
28562   unixFile *pFile = (unixFile*)id;
28563   int fd;
28564   char *zLockFile = (char *)pFile->lockingContext;
28565   int rc = SQLCIPHER_OK;
28566
28567
28568   /* If we have any lock, then the lock file already exists.  All we have
28569   ** to do is adjust our internal record of the lock level.
28570   */
28571   if( pFile->eFileLock > NO_LOCK ){
28572     pFile->eFileLock = eFileLock;
28573     /* Always update the timestamp on the old file */
28574 #ifdef HAVE_UTIME
28575     utime(zLockFile, NULL);
28576 #else
28577     utimes(zLockFile, NULL);
28578 #endif
28579     return SQLCIPHER_OK;
28580   }
28581   
28582   /* grab an exclusive lock */
28583   fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
28584   if( fd<0 ){
28585     /* failed to open/create the file, someone else may have stolen the lock */
28586     int tErrno = errno;
28587     if( EEXIST == tErrno ){
28588       rc = SQLCIPHER_BUSY;
28589     } else {
28590       rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_LOCK);
28591       if( IS_LOCK_ERROR(rc) ){
28592         pFile->lastErrno = tErrno;
28593       }
28594     }
28595     return rc;
28596   } 
28597   robust_close(pFile, fd, __LINE__);
28598   
28599   /* got it, set the type and return ok */
28600   pFile->eFileLock = eFileLock;
28601   return rc;
28602 }
28603
28604 /*
28605 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28606 ** must be either NO_LOCK or SHARED_LOCK.
28607 **
28608 ** If the locking level of the file descriptor is already at or below
28609 ** the requested locking level, this routine is a no-op.
28610 **
28611 ** When the locking level reaches NO_LOCK, delete the lock file.
28612 */
28613 static int dotlockUnlock(sqlcipher3_file *id, int eFileLock) {
28614   unixFile *pFile = (unixFile*)id;
28615   char *zLockFile = (char *)pFile->lockingContext;
28616
28617   assert( pFile );
28618   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
28619            pFile->eFileLock, getpid()));
28620   assert( eFileLock<=SHARED_LOCK );
28621   
28622   /* no-op if possible */
28623   if( pFile->eFileLock==eFileLock ){
28624     return SQLCIPHER_OK;
28625   }
28626
28627   /* To downgrade to shared, simply update our internal notion of the
28628   ** lock state.  No need to mess with the file on disk.
28629   */
28630   if( eFileLock==SHARED_LOCK ){
28631     pFile->eFileLock = SHARED_LOCK;
28632     return SQLCIPHER_OK;
28633   }
28634   
28635   /* To fully unlock the database, delete the lock file */
28636   assert( eFileLock==NO_LOCK );
28637   if( osUnlink(zLockFile) ){
28638     int rc = 0;
28639     int tErrno = errno;
28640     if( ENOENT != tErrno ){
28641       rc = SQLCIPHER_IOERR_UNLOCK;
28642     }
28643     if( IS_LOCK_ERROR(rc) ){
28644       pFile->lastErrno = tErrno;
28645     }
28646     return rc; 
28647   }
28648   pFile->eFileLock = NO_LOCK;
28649   return SQLCIPHER_OK;
28650 }
28651
28652 /*
28653 ** Close a file.  Make sure the lock has been released before closing.
28654 */
28655 static int dotlockClose(sqlcipher3_file *id) {
28656   int rc;
28657   if( id ){
28658     unixFile *pFile = (unixFile*)id;
28659     dotlockUnlock(id, NO_LOCK);
28660     sqlcipher3_free(pFile->lockingContext);
28661   }
28662   rc = closeUnixFile(id);
28663   return rc;
28664 }
28665 /****************** End of the dot-file lock implementation *******************
28666 ******************************************************************************/
28667
28668 /******************************************************************************
28669 ************************** Begin flock Locking ********************************
28670 **
28671 ** Use the flock() system call to do file locking.
28672 **
28673 ** flock() locking is like dot-file locking in that the various
28674 ** fine-grain locking levels supported by SQLite are collapsed into
28675 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
28676 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
28677 ** still works when you do this, but concurrency is reduced since
28678 ** only a single process can be reading the database at a time.
28679 **
28680 ** Omit this section if SQLCIPHER_ENABLE_LOCKING_STYLE is turned off or if
28681 ** compiling for VXWORKS.
28682 */
28683 #if SQLCIPHER_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28684
28685 /*
28686 ** Retry flock() calls that fail with EINTR
28687 */
28688 #ifdef EINTR
28689 static int robust_flock(int fd, int op){
28690   int rc;
28691   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
28692   return rc;
28693 }
28694 #else
28695 # define robust_flock(a,b) flock(a,b)
28696 #endif
28697      
28698
28699 /*
28700 ** This routine checks if there is a RESERVED lock held on the specified
28701 ** file by this or any other process. If such a lock is held, set *pResOut
28702 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
28703 ** is set to SQLCIPHER_OK unless an I/O error occurs during lock checking.
28704 */
28705 static int flockCheckReservedLock(sqlcipher3_file *id, int *pResOut){
28706   int rc = SQLCIPHER_OK;
28707   int reserved = 0;
28708   unixFile *pFile = (unixFile*)id;
28709   
28710   SimulateIOError( return SQLCIPHER_IOERR_CHECKRESERVEDLOCK; );
28711   
28712   assert( pFile );
28713   
28714   /* Check if a thread in this process holds such a lock */
28715   if( pFile->eFileLock>SHARED_LOCK ){
28716     reserved = 1;
28717   }
28718   
28719   /* Otherwise see if some other process holds it. */
28720   if( !reserved ){
28721     /* attempt to get the lock */
28722     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
28723     if( !lrc ){
28724       /* got the lock, unlock it */
28725       lrc = robust_flock(pFile->h, LOCK_UN);
28726       if ( lrc ) {
28727         int tErrno = errno;
28728         /* unlock failed with an error */
28729         lrc = SQLCIPHER_IOERR_UNLOCK; 
28730         if( IS_LOCK_ERROR(lrc) ){
28731           pFile->lastErrno = tErrno;
28732           rc = lrc;
28733         }
28734       }
28735     } else {
28736       int tErrno = errno;
28737       reserved = 1;
28738       /* someone else might have it reserved */
28739       lrc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_LOCK); 
28740       if( IS_LOCK_ERROR(lrc) ){
28741         pFile->lastErrno = tErrno;
28742         rc = lrc;
28743       }
28744     }
28745   }
28746   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
28747
28748 #ifdef SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS
28749   if( (rc & SQLCIPHER_IOERR) == SQLCIPHER_IOERR ){
28750     rc = SQLCIPHER_OK;
28751     reserved=1;
28752   }
28753 #endif /* SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS */
28754   *pResOut = reserved;
28755   return rc;
28756 }
28757
28758 /*
28759 ** Lock the file with the lock specified by parameter eFileLock - one
28760 ** of the following:
28761 **
28762 **     (1) SHARED_LOCK
28763 **     (2) RESERVED_LOCK
28764 **     (3) PENDING_LOCK
28765 **     (4) EXCLUSIVE_LOCK
28766 **
28767 ** Sometimes when requesting one lock state, additional lock states
28768 ** are inserted in between.  The locking might fail on one of the later
28769 ** transitions leaving the lock state different from what it started but
28770 ** still short of its goal.  The following chart shows the allowed
28771 ** transitions and the inserted intermediate states:
28772 **
28773 **    UNLOCKED -> SHARED
28774 **    SHARED -> RESERVED
28775 **    SHARED -> (PENDING) -> EXCLUSIVE
28776 **    RESERVED -> (PENDING) -> EXCLUSIVE
28777 **    PENDING -> EXCLUSIVE
28778 **
28779 ** flock() only really support EXCLUSIVE locks.  We track intermediate
28780 ** lock states in the sqlcipher3_file structure, but all locks SHARED or
28781 ** above are really EXCLUSIVE locks and exclude all other processes from
28782 ** access the file.
28783 **
28784 ** This routine will only increase a lock.  Use the sqlcipher3OsUnlock()
28785 ** routine to lower a locking level.
28786 */
28787 static int flockLock(sqlcipher3_file *id, int eFileLock) {
28788   int rc = SQLCIPHER_OK;
28789   unixFile *pFile = (unixFile*)id;
28790
28791   assert( pFile );
28792
28793   /* if we already have a lock, it is exclusive.  
28794   ** Just adjust level and punt on outta here. */
28795   if (pFile->eFileLock > NO_LOCK) {
28796     pFile->eFileLock = eFileLock;
28797     return SQLCIPHER_OK;
28798   }
28799   
28800   /* grab an exclusive lock */
28801   
28802   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
28803     int tErrno = errno;
28804     /* didn't get, must be busy */
28805     rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_LOCK);
28806     if( IS_LOCK_ERROR(rc) ){
28807       pFile->lastErrno = tErrno;
28808     }
28809   } else {
28810     /* got it, set the type and return ok */
28811     pFile->eFileLock = eFileLock;
28812   }
28813   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
28814            rc==SQLCIPHER_OK ? "ok" : "failed"));
28815 #ifdef SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS
28816   if( (rc & SQLCIPHER_IOERR) == SQLCIPHER_IOERR ){
28817     rc = SQLCIPHER_BUSY;
28818   }
28819 #endif /* SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS */
28820   return rc;
28821 }
28822
28823
28824 /*
28825 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28826 ** must be either NO_LOCK or SHARED_LOCK.
28827 **
28828 ** If the locking level of the file descriptor is already at or below
28829 ** the requested locking level, this routine is a no-op.
28830 */
28831 static int flockUnlock(sqlcipher3_file *id, int eFileLock) {
28832   unixFile *pFile = (unixFile*)id;
28833   
28834   assert( pFile );
28835   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
28836            pFile->eFileLock, getpid()));
28837   assert( eFileLock<=SHARED_LOCK );
28838   
28839   /* no-op if possible */
28840   if( pFile->eFileLock==eFileLock ){
28841     return SQLCIPHER_OK;
28842   }
28843   
28844   /* shared can just be set because we always have an exclusive */
28845   if (eFileLock==SHARED_LOCK) {
28846     pFile->eFileLock = eFileLock;
28847     return SQLCIPHER_OK;
28848   }
28849   
28850   /* no, really, unlock. */
28851   if( robust_flock(pFile->h, LOCK_UN) ){
28852 #ifdef SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS
28853     return SQLCIPHER_OK;
28854 #endif /* SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS */
28855     return SQLCIPHER_IOERR_UNLOCK;
28856   }else{
28857     pFile->eFileLock = NO_LOCK;
28858     return SQLCIPHER_OK;
28859   }
28860 }
28861
28862 /*
28863 ** Close a file.
28864 */
28865 static int flockClose(sqlcipher3_file *id) {
28866   if( id ){
28867     flockUnlock(id, NO_LOCK);
28868   }
28869   return closeUnixFile(id);
28870 }
28871
28872 #endif /* SQLCIPHER_ENABLE_LOCKING_STYLE && !OS_VXWORK */
28873
28874 /******************* End of the flock lock implementation *********************
28875 ******************************************************************************/
28876
28877 /******************************************************************************
28878 ************************ Begin Named Semaphore Locking ************************
28879 **
28880 ** Named semaphore locking is only supported on VxWorks.
28881 **
28882 ** Semaphore locking is like dot-lock and flock in that it really only
28883 ** supports EXCLUSIVE locking.  Only a single process can read or write
28884 ** the database file at a time.  This reduces potential concurrency, but
28885 ** makes the lock implementation much easier.
28886 */
28887 #if OS_VXWORKS
28888
28889 /*
28890 ** This routine checks if there is a RESERVED lock held on the specified
28891 ** file by this or any other process. If such a lock is held, set *pResOut
28892 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
28893 ** is set to SQLCIPHER_OK unless an I/O error occurs during lock checking.
28894 */
28895 static int semCheckReservedLock(sqlcipher3_file *id, int *pResOut) {
28896   int rc = SQLCIPHER_OK;
28897   int reserved = 0;
28898   unixFile *pFile = (unixFile*)id;
28899
28900   SimulateIOError( return SQLCIPHER_IOERR_CHECKRESERVEDLOCK; );
28901   
28902   assert( pFile );
28903
28904   /* Check if a thread in this process holds such a lock */
28905   if( pFile->eFileLock>SHARED_LOCK ){
28906     reserved = 1;
28907   }
28908   
28909   /* Otherwise see if some other process holds it. */
28910   if( !reserved ){
28911     sem_t *pSem = pFile->pInode->pSem;
28912     struct stat statBuf;
28913
28914     if( sem_trywait(pSem)==-1 ){
28915       int tErrno = errno;
28916       if( EAGAIN != tErrno ){
28917         rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_CHECKRESERVEDLOCK);
28918         pFile->lastErrno = tErrno;
28919       } else {
28920         /* someone else has the lock when we are in NO_LOCK */
28921         reserved = (pFile->eFileLock < SHARED_LOCK);
28922       }
28923     }else{
28924       /* we could have it if we want it */
28925       sem_post(pSem);
28926     }
28927   }
28928   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
28929
28930   *pResOut = reserved;
28931   return rc;
28932 }
28933
28934 /*
28935 ** Lock the file with the lock specified by parameter eFileLock - one
28936 ** of the following:
28937 **
28938 **     (1) SHARED_LOCK
28939 **     (2) RESERVED_LOCK
28940 **     (3) PENDING_LOCK
28941 **     (4) EXCLUSIVE_LOCK
28942 **
28943 ** Sometimes when requesting one lock state, additional lock states
28944 ** are inserted in between.  The locking might fail on one of the later
28945 ** transitions leaving the lock state different from what it started but
28946 ** still short of its goal.  The following chart shows the allowed
28947 ** transitions and the inserted intermediate states:
28948 **
28949 **    UNLOCKED -> SHARED
28950 **    SHARED -> RESERVED
28951 **    SHARED -> (PENDING) -> EXCLUSIVE
28952 **    RESERVED -> (PENDING) -> EXCLUSIVE
28953 **    PENDING -> EXCLUSIVE
28954 **
28955 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
28956 ** lock states in the sqlcipher3_file structure, but all locks SHARED or
28957 ** above are really EXCLUSIVE locks and exclude all other processes from
28958 ** access the file.
28959 **
28960 ** This routine will only increase a lock.  Use the sqlcipher3OsUnlock()
28961 ** routine to lower a locking level.
28962 */
28963 static int semLock(sqlcipher3_file *id, int eFileLock) {
28964   unixFile *pFile = (unixFile*)id;
28965   int fd;
28966   sem_t *pSem = pFile->pInode->pSem;
28967   int rc = SQLCIPHER_OK;
28968
28969   /* if we already have a lock, it is exclusive.  
28970   ** Just adjust level and punt on outta here. */
28971   if (pFile->eFileLock > NO_LOCK) {
28972     pFile->eFileLock = eFileLock;
28973     rc = SQLCIPHER_OK;
28974     goto sem_end_lock;
28975   }
28976   
28977   /* lock semaphore now but bail out when already locked. */
28978   if( sem_trywait(pSem)==-1 ){
28979     rc = SQLCIPHER_BUSY;
28980     goto sem_end_lock;
28981   }
28982
28983   /* got it, set the type and return ok */
28984   pFile->eFileLock = eFileLock;
28985
28986  sem_end_lock:
28987   return rc;
28988 }
28989
28990 /*
28991 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28992 ** must be either NO_LOCK or SHARED_LOCK.
28993 **
28994 ** If the locking level of the file descriptor is already at or below
28995 ** the requested locking level, this routine is a no-op.
28996 */
28997 static int semUnlock(sqlcipher3_file *id, int eFileLock) {
28998   unixFile *pFile = (unixFile*)id;
28999   sem_t *pSem = pFile->pInode->pSem;
29000
29001   assert( pFile );
29002   assert( pSem );
29003   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
29004            pFile->eFileLock, getpid()));
29005   assert( eFileLock<=SHARED_LOCK );
29006   
29007   /* no-op if possible */
29008   if( pFile->eFileLock==eFileLock ){
29009     return SQLCIPHER_OK;
29010   }
29011   
29012   /* shared can just be set because we always have an exclusive */
29013   if (eFileLock==SHARED_LOCK) {
29014     pFile->eFileLock = eFileLock;
29015     return SQLCIPHER_OK;
29016   }
29017   
29018   /* no, really unlock. */
29019   if ( sem_post(pSem)==-1 ) {
29020     int rc, tErrno = errno;
29021     rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_UNLOCK);
29022     if( IS_LOCK_ERROR(rc) ){
29023       pFile->lastErrno = tErrno;
29024     }
29025     return rc; 
29026   }
29027   pFile->eFileLock = NO_LOCK;
29028   return SQLCIPHER_OK;
29029 }
29030
29031 /*
29032  ** Close a file.
29033  */
29034 static int semClose(sqlcipher3_file *id) {
29035   if( id ){
29036     unixFile *pFile = (unixFile*)id;
29037     semUnlock(id, NO_LOCK);
29038     assert( pFile );
29039     unixEnterMutex();
29040     releaseInodeInfo(pFile);
29041     unixLeaveMutex();
29042     closeUnixFile(id);
29043   }
29044   return SQLCIPHER_OK;
29045 }
29046
29047 #endif /* OS_VXWORKS */
29048 /*
29049 ** Named semaphore locking is only available on VxWorks.
29050 **
29051 *************** End of the named semaphore lock implementation ****************
29052 ******************************************************************************/
29053
29054
29055 /******************************************************************************
29056 *************************** Begin AFP Locking *********************************
29057 **
29058 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
29059 ** on Apple Macintosh computers - both OS9 and OSX.
29060 **
29061 ** Third-party implementations of AFP are available.  But this code here
29062 ** only works on OSX.
29063 */
29064
29065 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
29066 /*
29067 ** The afpLockingContext structure contains all afp lock specific state
29068 */
29069 typedef struct afpLockingContext afpLockingContext;
29070 struct afpLockingContext {
29071   int reserved;
29072   const char *dbPath;             /* Name of the open file */
29073 };
29074
29075 struct ByteRangeLockPB2
29076 {
29077   unsigned long long offset;        /* offset to first byte to lock */
29078   unsigned long long length;        /* nbr of bytes to lock */
29079   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
29080   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
29081   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
29082   int fd;                           /* file desc to assoc this lock with */
29083 };
29084
29085 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
29086
29087 /*
29088 ** This is a utility for setting or clearing a bit-range lock on an
29089 ** AFP filesystem.
29090 ** 
29091 ** Return SQLCIPHER_OK on success, SQLCIPHER_BUSY on failure.
29092 */
29093 static int afpSetLock(
29094   const char *path,              /* Name of the file to be locked or unlocked */
29095   unixFile *pFile,               /* Open file descriptor on path */
29096   unsigned long long offset,     /* First byte to be locked */
29097   unsigned long long length,     /* Number of bytes to lock */
29098   int setLockFlag                /* True to set lock.  False to clear lock */
29099 ){
29100   struct ByteRangeLockPB2 pb;
29101   int err;
29102   
29103   pb.unLockFlag = setLockFlag ? 0 : 1;
29104   pb.startEndFlag = 0;
29105   pb.offset = offset;
29106   pb.length = length; 
29107   pb.fd = pFile->h;
29108   
29109   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
29110     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
29111     offset, length));
29112   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
29113   if ( err==-1 ) {
29114     int rc;
29115     int tErrno = errno;
29116     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
29117              path, tErrno, strerror(tErrno)));
29118 #ifdef SQLCIPHER_IGNORE_AFP_LOCK_ERRORS
29119     rc = SQLCIPHER_BUSY;
29120 #else
29121     rc = sqlcipherErrorFromPosixError(tErrno,
29122                     setLockFlag ? SQLCIPHER_IOERR_LOCK : SQLCIPHER_IOERR_UNLOCK);
29123 #endif /* SQLCIPHER_IGNORE_AFP_LOCK_ERRORS */
29124     if( IS_LOCK_ERROR(rc) ){
29125       pFile->lastErrno = tErrno;
29126     }
29127     return rc;
29128   } else {
29129     return SQLCIPHER_OK;
29130   }
29131 }
29132
29133 /*
29134 ** This routine checks if there is a RESERVED lock held on the specified
29135 ** file by this or any other process. If such a lock is held, set *pResOut
29136 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
29137 ** is set to SQLCIPHER_OK unless an I/O error occurs during lock checking.
29138 */
29139 static int afpCheckReservedLock(sqlcipher3_file *id, int *pResOut){
29140   int rc = SQLCIPHER_OK;
29141   int reserved = 0;
29142   unixFile *pFile = (unixFile*)id;
29143   afpLockingContext *context;
29144   
29145   SimulateIOError( return SQLCIPHER_IOERR_CHECKRESERVEDLOCK; );
29146   
29147   assert( pFile );
29148   context = (afpLockingContext *) pFile->lockingContext;
29149   if( context->reserved ){
29150     *pResOut = 1;
29151     return SQLCIPHER_OK;
29152   }
29153   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
29154   
29155   /* Check if a thread in this process holds such a lock */
29156   if( pFile->pInode->eFileLock>SHARED_LOCK ){
29157     reserved = 1;
29158   }
29159   
29160   /* Otherwise see if some other process holds it.
29161    */
29162   if( !reserved ){
29163     /* lock the RESERVED byte */
29164     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
29165     if( SQLCIPHER_OK==lrc ){
29166       /* if we succeeded in taking the reserved lock, unlock it to restore
29167       ** the original state */
29168       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
29169     } else {
29170       /* if we failed to get the lock then someone else must have it */
29171       reserved = 1;
29172     }
29173     if( IS_LOCK_ERROR(lrc) ){
29174       rc=lrc;
29175     }
29176   }
29177   
29178   unixLeaveMutex();
29179   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
29180   
29181   *pResOut = reserved;
29182   return rc;
29183 }
29184
29185 /*
29186 ** Lock the file with the lock specified by parameter eFileLock - one
29187 ** of the following:
29188 **
29189 **     (1) SHARED_LOCK
29190 **     (2) RESERVED_LOCK
29191 **     (3) PENDING_LOCK
29192 **     (4) EXCLUSIVE_LOCK
29193 **
29194 ** Sometimes when requesting one lock state, additional lock states
29195 ** are inserted in between.  The locking might fail on one of the later
29196 ** transitions leaving the lock state different from what it started but
29197 ** still short of its goal.  The following chart shows the allowed
29198 ** transitions and the inserted intermediate states:
29199 **
29200 **    UNLOCKED -> SHARED
29201 **    SHARED -> RESERVED
29202 **    SHARED -> (PENDING) -> EXCLUSIVE
29203 **    RESERVED -> (PENDING) -> EXCLUSIVE
29204 **    PENDING -> EXCLUSIVE
29205 **
29206 ** This routine will only increase a lock.  Use the sqlcipher3OsUnlock()
29207 ** routine to lower a locking level.
29208 */
29209 static int afpLock(sqlcipher3_file *id, int eFileLock){
29210   int rc = SQLCIPHER_OK;
29211   unixFile *pFile = (unixFile*)id;
29212   unixInodeInfo *pInode = pFile->pInode;
29213   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
29214   
29215   assert( pFile );
29216   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
29217            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
29218            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
29219
29220   /* If there is already a lock of this type or more restrictive on the
29221   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
29222   ** unixEnterMutex() hasn't been called yet.
29223   */
29224   if( pFile->eFileLock>=eFileLock ){
29225     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
29226            azFileLock(eFileLock)));
29227     return SQLCIPHER_OK;
29228   }
29229
29230   /* Make sure the locking sequence is correct
29231   **  (1) We never move from unlocked to anything higher than shared lock.
29232   **  (2) SQLite never explicitly requests a pendig lock.
29233   **  (3) A shared lock is always held when a reserve lock is requested.
29234   */
29235   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
29236   assert( eFileLock!=PENDING_LOCK );
29237   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
29238   
29239   /* This mutex is needed because pFile->pInode is shared across threads
29240   */
29241   unixEnterMutex();
29242   pInode = pFile->pInode;
29243
29244   /* If some thread using this PID has a lock via a different unixFile*
29245   ** handle that precludes the requested lock, return BUSY.
29246   */
29247   if( (pFile->eFileLock!=pInode->eFileLock && 
29248        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
29249      ){
29250     rc = SQLCIPHER_BUSY;
29251     goto afp_end_lock;
29252   }
29253   
29254   /* If a SHARED lock is requested, and some thread using this PID already
29255   ** has a SHARED or RESERVED lock, then increment reference counts and
29256   ** return SQLCIPHER_OK.
29257   */
29258   if( eFileLock==SHARED_LOCK && 
29259      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
29260     assert( eFileLock==SHARED_LOCK );
29261     assert( pFile->eFileLock==0 );
29262     assert( pInode->nShared>0 );
29263     pFile->eFileLock = SHARED_LOCK;
29264     pInode->nShared++;
29265     pInode->nLock++;
29266     goto afp_end_lock;
29267   }
29268     
29269   /* A PENDING lock is needed before acquiring a SHARED lock and before
29270   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
29271   ** be released.
29272   */
29273   if( eFileLock==SHARED_LOCK 
29274       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
29275   ){
29276     int failed;
29277     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
29278     if (failed) {
29279       rc = failed;
29280       goto afp_end_lock;
29281     }
29282   }
29283   
29284   /* If control gets to this point, then actually go ahead and make
29285   ** operating system calls for the specified lock.
29286   */
29287   if( eFileLock==SHARED_LOCK ){
29288     int lrc1, lrc2, lrc1Errno = 0;
29289     long lk, mask;
29290     
29291     assert( pInode->nShared==0 );
29292     assert( pInode->eFileLock==0 );
29293         
29294     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
29295     /* Now get the read-lock SHARED_LOCK */
29296     /* note that the quality of the randomness doesn't matter that much */
29297     lk = random(); 
29298     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
29299     lrc1 = afpSetLock(context->dbPath, pFile, 
29300           SHARED_FIRST+pInode->sharedByte, 1, 1);
29301     if( IS_LOCK_ERROR(lrc1) ){
29302       lrc1Errno = pFile->lastErrno;
29303     }
29304     /* Drop the temporary PENDING lock */
29305     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
29306     
29307     if( IS_LOCK_ERROR(lrc1) ) {
29308       pFile->lastErrno = lrc1Errno;
29309       rc = lrc1;
29310       goto afp_end_lock;
29311     } else if( IS_LOCK_ERROR(lrc2) ){
29312       rc = lrc2;
29313       goto afp_end_lock;
29314     } else if( lrc1 != SQLCIPHER_OK ) {
29315       rc = lrc1;
29316     } else {
29317       pFile->eFileLock = SHARED_LOCK;
29318       pInode->nLock++;
29319       pInode->nShared = 1;
29320     }
29321   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
29322     /* We are trying for an exclusive lock but another thread in this
29323      ** same process is still holding a shared lock. */
29324     rc = SQLCIPHER_BUSY;
29325   }else{
29326     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
29327     ** assumed that there is a SHARED or greater lock on the file
29328     ** already.
29329     */
29330     int failed = 0;
29331     assert( 0!=pFile->eFileLock );
29332     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
29333         /* Acquire a RESERVED lock */
29334         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
29335       if( !failed ){
29336         context->reserved = 1;
29337       }
29338     }
29339     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
29340       /* Acquire an EXCLUSIVE lock */
29341         
29342       /* Remove the shared lock before trying the range.  we'll need to 
29343       ** reestablish the shared lock if we can't get the  afpUnlock
29344       */
29345       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
29346                          pInode->sharedByte, 1, 0)) ){
29347         int failed2 = SQLCIPHER_OK;
29348         /* now attemmpt to get the exclusive lock range */
29349         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
29350                                SHARED_SIZE, 1);
29351         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
29352                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
29353           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
29354           ** a critical I/O error
29355           */
29356           rc = ((failed & SQLCIPHER_IOERR) == SQLCIPHER_IOERR) ? failed2 : 
29357                SQLCIPHER_IOERR_LOCK;
29358           goto afp_end_lock;
29359         } 
29360       }else{
29361         rc = failed; 
29362       }
29363     }
29364     if( failed ){
29365       rc = failed;
29366     }
29367   }
29368   
29369   if( rc==SQLCIPHER_OK ){
29370     pFile->eFileLock = eFileLock;
29371     pInode->eFileLock = eFileLock;
29372   }else if( eFileLock==EXCLUSIVE_LOCK ){
29373     pFile->eFileLock = PENDING_LOCK;
29374     pInode->eFileLock = PENDING_LOCK;
29375   }
29376   
29377 afp_end_lock:
29378   unixLeaveMutex();
29379   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
29380          rc==SQLCIPHER_OK ? "ok" : "failed"));
29381   return rc;
29382 }
29383
29384 /*
29385 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29386 ** must be either NO_LOCK or SHARED_LOCK.
29387 **
29388 ** If the locking level of the file descriptor is already at or below
29389 ** the requested locking level, this routine is a no-op.
29390 */
29391 static int afpUnlock(sqlcipher3_file *id, int eFileLock) {
29392   int rc = SQLCIPHER_OK;
29393   unixFile *pFile = (unixFile*)id;
29394   unixInodeInfo *pInode;
29395   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
29396   int skipShared = 0;
29397 #ifdef SQLCIPHER_TEST
29398   int h = pFile->h;
29399 #endif
29400
29401   assert( pFile );
29402   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
29403            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
29404            getpid()));
29405
29406   assert( eFileLock<=SHARED_LOCK );
29407   if( pFile->eFileLock<=eFileLock ){
29408     return SQLCIPHER_OK;
29409   }
29410   unixEnterMutex();
29411   pInode = pFile->pInode;
29412   assert( pInode->nShared!=0 );
29413   if( pFile->eFileLock>SHARED_LOCK ){
29414     assert( pInode->eFileLock==pFile->eFileLock );
29415     SimulateIOErrorBenign(1);
29416     SimulateIOError( h=(-1) )
29417     SimulateIOErrorBenign(0);
29418     
29419 #ifndef NDEBUG
29420     /* When reducing a lock such that other processes can start
29421     ** reading the database file again, make sure that the
29422     ** transaction counter was updated if any part of the database
29423     ** file changed.  If the transaction counter is not updated,
29424     ** other connections to the same file might not realize that
29425     ** the file has changed and hence might not know to flush their
29426     ** cache.  The use of a stale cache can lead to database corruption.
29427     */
29428     assert( pFile->inNormalWrite==0
29429            || pFile->dbUpdate==0
29430            || pFile->transCntrChng==1 );
29431     pFile->inNormalWrite = 0;
29432 #endif
29433     
29434     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
29435       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
29436       if( rc==SQLCIPHER_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
29437         /* only re-establish the shared lock if necessary */
29438         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
29439         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
29440       } else {
29441         skipShared = 1;
29442       }
29443     }
29444     if( rc==SQLCIPHER_OK && pFile->eFileLock>=PENDING_LOCK ){
29445       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
29446     } 
29447     if( rc==SQLCIPHER_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
29448       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
29449       if( !rc ){ 
29450         context->reserved = 0; 
29451       }
29452     }
29453     if( rc==SQLCIPHER_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
29454       pInode->eFileLock = SHARED_LOCK;
29455     }
29456   }
29457   if( rc==SQLCIPHER_OK && eFileLock==NO_LOCK ){
29458
29459     /* Decrement the shared lock counter.  Release the lock using an
29460     ** OS call only when all threads in this same process have released
29461     ** the lock.
29462     */
29463     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
29464     pInode->nShared--;
29465     if( pInode->nShared==0 ){
29466       SimulateIOErrorBenign(1);
29467       SimulateIOError( h=(-1) )
29468       SimulateIOErrorBenign(0);
29469       if( !skipShared ){
29470         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
29471       }
29472       if( !rc ){
29473         pInode->eFileLock = NO_LOCK;
29474         pFile->eFileLock = NO_LOCK;
29475       }
29476     }
29477     if( rc==SQLCIPHER_OK ){
29478       pInode->nLock--;
29479       assert( pInode->nLock>=0 );
29480       if( pInode->nLock==0 ){
29481         closePendingFds(pFile);
29482       }
29483     }
29484   }
29485   
29486   unixLeaveMutex();
29487   if( rc==SQLCIPHER_OK ) pFile->eFileLock = eFileLock;
29488   return rc;
29489 }
29490
29491 /*
29492 ** Close a file & cleanup AFP specific locking context 
29493 */
29494 static int afpClose(sqlcipher3_file *id) {
29495   int rc = SQLCIPHER_OK;
29496   if( id ){
29497     unixFile *pFile = (unixFile*)id;
29498     afpUnlock(id, NO_LOCK);
29499     unixEnterMutex();
29500     if( pFile->pInode && pFile->pInode->nLock ){
29501       /* If there are outstanding locks, do not actually close the file just
29502       ** yet because that would clear those locks.  Instead, add the file
29503       ** descriptor to pInode->aPending.  It will be automatically closed when
29504       ** the last lock is cleared.
29505       */
29506       setPendingFd(pFile);
29507     }
29508     releaseInodeInfo(pFile);
29509     sqlcipher3_free(pFile->lockingContext);
29510     rc = closeUnixFile(id);
29511     unixLeaveMutex();
29512   }
29513   return rc;
29514 }
29515
29516 #endif /* defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE */
29517 /*
29518 ** The code above is the AFP lock implementation.  The code is specific
29519 ** to MacOSX and does not work on other unix platforms.  No alternative
29520 ** is available.  If you don't compile for a mac, then the "unix-afp"
29521 ** VFS is not available.
29522 **
29523 ********************* End of the AFP lock implementation **********************
29524 ******************************************************************************/
29525
29526 /******************************************************************************
29527 *************************** Begin NFS Locking ********************************/
29528
29529 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
29530 /*
29531  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29532  ** must be either NO_LOCK or SHARED_LOCK.
29533  **
29534  ** If the locking level of the file descriptor is already at or below
29535  ** the requested locking level, this routine is a no-op.
29536  */
29537 static int nfsUnlock(sqlcipher3_file *id, int eFileLock){
29538   return posixUnlock(id, eFileLock, 1);
29539 }
29540
29541 #endif /* defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE */
29542 /*
29543 ** The code above is the NFS lock implementation.  The code is specific
29544 ** to MacOSX and does not work on other unix platforms.  No alternative
29545 ** is available.  
29546 **
29547 ********************* End of the NFS lock implementation **********************
29548 ******************************************************************************/
29549
29550 /******************************************************************************
29551 **************** Non-locking sqlcipher3_file methods *****************************
29552 **
29553 ** The next division contains implementations for all methods of the 
29554 ** sqlcipher3_file object other than the locking methods.  The locking
29555 ** methods were defined in divisions above (one locking method per
29556 ** division).  Those methods that are common to all locking modes
29557 ** are gather together into this division.
29558 */
29559
29560 /*
29561 ** Seek to the offset passed as the second argument, then read cnt 
29562 ** bytes into pBuf. Return the number of bytes actually read.
29563 **
29564 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
29565 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
29566 ** one system to another.  Since SQLite does not define USE_PREAD
29567 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
29568 ** See tickets #2741 and #2681.
29569 **
29570 ** To avoid stomping the errno value on a failed read the lastErrno value
29571 ** is set before returning.
29572 */
29573 static int seekAndRead(unixFile *id, sqlcipher3_int64 offset, void *pBuf, int cnt){
29574   int got;
29575 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
29576   i64 newOffset;
29577 #endif
29578   TIMER_START;
29579 #if defined(USE_PREAD)
29580   do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
29581   SimulateIOError( got = -1 );
29582 #elif defined(USE_PREAD64)
29583   do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
29584   SimulateIOError( got = -1 );
29585 #else
29586   newOffset = lseek(id->h, offset, SEEK_SET);
29587   SimulateIOError( newOffset-- );
29588   if( newOffset!=offset ){
29589     if( newOffset == -1 ){
29590       ((unixFile*)id)->lastErrno = errno;
29591     }else{
29592       ((unixFile*)id)->lastErrno = 0;                   
29593     }
29594     return -1;
29595   }
29596   do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
29597 #endif
29598   TIMER_END;
29599   if( got<0 ){
29600     ((unixFile*)id)->lastErrno = errno;
29601   }
29602   OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
29603   return got;
29604 }
29605
29606 /*
29607 ** Read data from a file into a buffer.  Return SQLCIPHER_OK if all
29608 ** bytes were read successfully and SQLCIPHER_IOERR if anything goes
29609 ** wrong.
29610 */
29611 static int unixRead(
29612   sqlcipher3_file *id, 
29613   void *pBuf, 
29614   int amt,
29615   sqlcipher3_int64 offset
29616 ){
29617   unixFile *pFile = (unixFile *)id;
29618   int got;
29619   assert( id );
29620
29621   /* If this is a database file (not a journal, master-journal or temp
29622   ** file), the bytes in the locking range should never be read or written. */
29623 #if 0
29624   assert( pFile->pUnused==0
29625        || offset>=PENDING_BYTE+512
29626        || offset+amt<=PENDING_BYTE 
29627   );
29628 #endif
29629
29630   got = seekAndRead(pFile, offset, pBuf, amt);
29631   if( got==amt ){
29632     return SQLCIPHER_OK;
29633   }else if( got<0 ){
29634     /* lastErrno set by seekAndRead */
29635     return SQLCIPHER_IOERR_READ;
29636   }else{
29637     pFile->lastErrno = 0; /* not a system error */
29638     /* Unread parts of the buffer must be zero-filled */
29639     memset(&((char*)pBuf)[got], 0, amt-got);
29640     return SQLCIPHER_IOERR_SHORT_READ;
29641   }
29642 }
29643
29644 /*
29645 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
29646 ** Return the number of bytes actually read.  Update the offset.
29647 **
29648 ** To avoid stomping the errno value on a failed write the lastErrno value
29649 ** is set before returning.
29650 */
29651 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
29652   int got;
29653 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
29654   i64 newOffset;
29655 #endif
29656   TIMER_START;
29657 #if defined(USE_PREAD)
29658   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
29659 #elif defined(USE_PREAD64)
29660   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
29661 #else
29662   do{
29663     newOffset = lseek(id->h, offset, SEEK_SET);
29664     SimulateIOError( newOffset-- );
29665     if( newOffset!=offset ){
29666       if( newOffset == -1 ){
29667         ((unixFile*)id)->lastErrno = errno;
29668       }else{
29669         ((unixFile*)id)->lastErrno = 0;                 
29670       }
29671       return -1;
29672     }
29673     got = osWrite(id->h, pBuf, cnt);
29674   }while( got<0 && errno==EINTR );
29675 #endif
29676   TIMER_END;
29677   if( got<0 ){
29678     ((unixFile*)id)->lastErrno = errno;
29679   }
29680
29681   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
29682   return got;
29683 }
29684
29685
29686 /*
29687 ** Write data from a buffer into a file.  Return SQLCIPHER_OK on success
29688 ** or some other error code on failure.
29689 */
29690 static int unixWrite(
29691   sqlcipher3_file *id, 
29692   const void *pBuf, 
29693   int amt,
29694   sqlcipher3_int64 offset 
29695 ){
29696   unixFile *pFile = (unixFile*)id;
29697   int wrote = 0;
29698   assert( id );
29699   assert( amt>0 );
29700
29701   /* If this is a database file (not a journal, master-journal or temp
29702   ** file), the bytes in the locking range should never be read or written. */
29703 #if 0
29704   assert( pFile->pUnused==0
29705        || offset>=PENDING_BYTE+512
29706        || offset+amt<=PENDING_BYTE 
29707   );
29708 #endif
29709
29710 #ifndef NDEBUG
29711   /* If we are doing a normal write to a database file (as opposed to
29712   ** doing a hot-journal rollback or a write to some file other than a
29713   ** normal database file) then record the fact that the database
29714   ** has changed.  If the transaction counter is modified, record that
29715   ** fact too.
29716   */
29717   if( pFile->inNormalWrite ){
29718     pFile->dbUpdate = 1;  /* The database has been modified */
29719     if( offset<=24 && offset+amt>=27 ){
29720       int rc;
29721       char oldCntr[4];
29722       SimulateIOErrorBenign(1);
29723       rc = seekAndRead(pFile, 24, oldCntr, 4);
29724       SimulateIOErrorBenign(0);
29725       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
29726         pFile->transCntrChng = 1;  /* The transaction counter has changed */
29727       }
29728     }
29729   }
29730 #endif
29731
29732   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
29733     amt -= wrote;
29734     offset += wrote;
29735     pBuf = &((char*)pBuf)[wrote];
29736   }
29737   SimulateIOError(( wrote=(-1), amt=1 ));
29738   SimulateDiskfullError(( wrote=0, amt=1 ));
29739
29740   if( amt>0 ){
29741     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
29742       /* lastErrno set by seekAndWrite */
29743       return SQLCIPHER_IOERR_WRITE;
29744     }else{
29745       pFile->lastErrno = 0; /* not a system error */
29746       return SQLCIPHER_FULL;
29747     }
29748   }
29749
29750   return SQLCIPHER_OK;
29751 }
29752
29753 #ifdef SQLCIPHER_TEST
29754 /*
29755 ** Count the number of fullsyncs and normal syncs.  This is used to test
29756 ** that syncs and fullsyncs are occurring at the right times.
29757 */
29758 SQLCIPHER_API int sqlcipher3_sync_count = 0;
29759 SQLCIPHER_API int sqlcipher3_fullsync_count = 0;
29760 #endif
29761
29762 /*
29763 ** We do not trust systems to provide a working fdatasync().  Some do.
29764 ** Others do no.  To be safe, we will stick with the (slightly slower)
29765 ** fsync(). If you know that your system does support fdatasync() correctly,
29766 ** then simply compile with -Dfdatasync=fdatasync
29767 */
29768 #if !defined(fdatasync)
29769 # define fdatasync fsync
29770 #endif
29771
29772 /*
29773 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
29774 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
29775 ** only available on Mac OS X.  But that could change.
29776 */
29777 #ifdef F_FULLFSYNC
29778 # define HAVE_FULLFSYNC 1
29779 #else
29780 # define HAVE_FULLFSYNC 0
29781 #endif
29782
29783
29784 /*
29785 ** The fsync() system call does not work as advertised on many
29786 ** unix systems.  The following procedure is an attempt to make
29787 ** it work better.
29788 **
29789 ** The SQLCIPHER_NO_SYNC macro disables all fsync()s.  This is useful
29790 ** for testing when we want to run through the test suite quickly.
29791 ** You are strongly advised *not* to deploy with SQLCIPHER_NO_SYNC
29792 ** enabled, however, since with SQLCIPHER_NO_SYNC enabled, an OS crash
29793 ** or power failure will likely corrupt the database file.
29794 **
29795 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
29796 ** The idea behind dataOnly is that it should only write the file content
29797 ** to disk, not the inode.  We only set dataOnly if the file size is 
29798 ** unchanged since the file size is part of the inode.  However, 
29799 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
29800 ** file size has changed.  The only real difference between fdatasync()
29801 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
29802 ** inode if the mtime or owner or other inode attributes have changed.
29803 ** We only care about the file size, not the other file attributes, so
29804 ** as far as SQLite is concerned, an fdatasync() is always adequate.
29805 ** So, we always use fdatasync() if it is available, regardless of
29806 ** the value of the dataOnly flag.
29807 */
29808 static int full_fsync(int fd, int fullSync, int dataOnly){
29809   int rc;
29810
29811   /* The following "ifdef/elif/else/" block has the same structure as
29812   ** the one below. It is replicated here solely to avoid cluttering 
29813   ** up the real code with the UNUSED_PARAMETER() macros.
29814   */
29815 #ifdef SQLCIPHER_NO_SYNC
29816   UNUSED_PARAMETER(fd);
29817   UNUSED_PARAMETER(fullSync);
29818   UNUSED_PARAMETER(dataOnly);
29819 #elif HAVE_FULLFSYNC
29820   UNUSED_PARAMETER(dataOnly);
29821 #else
29822   UNUSED_PARAMETER(fullSync);
29823   UNUSED_PARAMETER(dataOnly);
29824 #endif
29825
29826   /* Record the number of times that we do a normal fsync() and 
29827   ** FULLSYNC.  This is used during testing to verify that this procedure
29828   ** gets called with the correct arguments.
29829   */
29830 #ifdef SQLCIPHER_TEST
29831   if( fullSync ) sqlcipher3_fullsync_count++;
29832   sqlcipher3_sync_count++;
29833 #endif
29834
29835   /* If we compiled with the SQLCIPHER_NO_SYNC flag, then syncing is a
29836   ** no-op
29837   */
29838 #ifdef SQLCIPHER_NO_SYNC
29839   rc = SQLCIPHER_OK;
29840 #elif HAVE_FULLFSYNC
29841   if( fullSync ){
29842     rc = osFcntl(fd, F_FULLFSYNC, 0);
29843   }else{
29844     rc = 1;
29845   }
29846   /* If the FULLFSYNC failed, fall back to attempting an fsync().
29847   ** It shouldn't be possible for fullfsync to fail on the local 
29848   ** file system (on OSX), so failure indicates that FULLFSYNC
29849   ** isn't supported for this file system. So, attempt an fsync 
29850   ** and (for now) ignore the overhead of a superfluous fcntl call.  
29851   ** It'd be better to detect fullfsync support once and avoid 
29852   ** the fcntl call every time sync is called.
29853   */
29854   if( rc ) rc = fsync(fd);
29855
29856 #elif defined(__APPLE__)
29857   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
29858   ** so currently we default to the macro that redefines fdatasync to fsync
29859   */
29860   rc = fsync(fd);
29861 #else 
29862   rc = fdatasync(fd);
29863 #if OS_VXWORKS
29864   if( rc==-1 && errno==ENOTSUP ){
29865     rc = fsync(fd);
29866   }
29867 #endif /* OS_VXWORKS */
29868 #endif /* ifdef SQLCIPHER_NO_SYNC elif HAVE_FULLFSYNC */
29869
29870   if( OS_VXWORKS && rc!= -1 ){
29871     rc = 0;
29872   }
29873   return rc;
29874 }
29875
29876 /*
29877 ** Open a file descriptor to the directory containing file zFilename.
29878 ** If successful, *pFd is set to the opened file descriptor and
29879 ** SQLCIPHER_OK is returned. If an error occurs, either SQLCIPHER_NOMEM
29880 ** or SQLCIPHER_CANTOPEN is returned and *pFd is set to an undefined
29881 ** value.
29882 **
29883 ** The directory file descriptor is used for only one thing - to
29884 ** fsync() a directory to make sure file creation and deletion events
29885 ** are flushed to disk.  Such fsyncs are not needed on newer
29886 ** journaling filesystems, but are required on older filesystems.
29887 **
29888 ** This routine can be overridden using the xSetSysCall interface.
29889 ** The ability to override this routine was added in support of the
29890 ** chromium sandbox.  Opening a directory is a security risk (we are
29891 ** told) so making it overrideable allows the chromium sandbox to
29892 ** replace this routine with a harmless no-op.  To make this routine
29893 ** a no-op, replace it with a stub that returns SQLCIPHER_OK but leaves
29894 ** *pFd set to a negative number.
29895 **
29896 ** If SQLCIPHER_OK is returned, the caller is responsible for closing
29897 ** the file descriptor *pFd using close().
29898 */
29899 static int openDirectory(const char *zFilename, int *pFd){
29900   int ii;
29901   int fd = -1;
29902   char zDirname[MAX_PATHNAME+1];
29903
29904   sqlcipher3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
29905   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
29906   if( ii>0 ){
29907     zDirname[ii] = '\0';
29908     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
29909     if( fd>=0 ){
29910 #ifdef FD_CLOEXEC
29911       osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29912 #endif
29913       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
29914     }
29915   }
29916   *pFd = fd;
29917   return (fd>=0?SQLCIPHER_OK:unixLogError(SQLCIPHER_CANTOPEN_BKPT, "open", zDirname));
29918 }
29919
29920 /*
29921 ** Make sure all writes to a particular file are committed to disk.
29922 **
29923 ** If dataOnly==0 then both the file itself and its metadata (file
29924 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
29925 ** file data is synced.
29926 **
29927 ** Under Unix, also make sure that the directory entry for the file
29928 ** has been created by fsync-ing the directory that contains the file.
29929 ** If we do not do this and we encounter a power failure, the directory
29930 ** entry for the journal might not exist after we reboot.  The next
29931 ** SQLite to access the file will not know that the journal exists (because
29932 ** the directory entry for the journal was never created) and the transaction
29933 ** will not roll back - possibly leading to database corruption.
29934 */
29935 static int unixSync(sqlcipher3_file *id, int flags){
29936   int rc;
29937   unixFile *pFile = (unixFile*)id;
29938
29939   int isDataOnly = (flags&SQLCIPHER_SYNC_DATAONLY);
29940   int isFullsync = (flags&0x0F)==SQLCIPHER_SYNC_FULL;
29941
29942   /* Check that one of SQLCIPHER_SYNC_NORMAL or FULL was passed */
29943   assert((flags&0x0F)==SQLCIPHER_SYNC_NORMAL
29944       || (flags&0x0F)==SQLCIPHER_SYNC_FULL
29945   );
29946
29947   /* Unix cannot, but some systems may return SQLCIPHER_FULL from here. This
29948   ** line is to test that doing so does not cause any problems.
29949   */
29950   SimulateDiskfullError( return SQLCIPHER_FULL );
29951
29952   assert( pFile );
29953   OSTRACE(("SYNC    %-3d\n", pFile->h));
29954   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
29955   SimulateIOError( rc=1 );
29956   if( rc ){
29957     pFile->lastErrno = errno;
29958     return unixLogError(SQLCIPHER_IOERR_FSYNC, "full_fsync", pFile->zPath);
29959   }
29960
29961   /* Also fsync the directory containing the file if the DIRSYNC flag
29962   ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)
29963   ** are unable to fsync a directory, so ignore errors on the fsync.
29964   */
29965   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
29966     int dirfd;
29967     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
29968             HAVE_FULLFSYNC, isFullsync));
29969     rc = osOpenDirectory(pFile->zPath, &dirfd);
29970     if( rc==SQLCIPHER_OK && dirfd>=0 ){
29971       full_fsync(dirfd, 0, 0);
29972       robust_close(pFile, dirfd, __LINE__);
29973     }else if( rc==SQLCIPHER_CANTOPEN ){
29974       rc = SQLCIPHER_OK;
29975     }
29976     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
29977   }
29978   return rc;
29979 }
29980
29981 /*
29982 ** Truncate an open file to a specified size
29983 */
29984 static int unixTruncate(sqlcipher3_file *id, i64 nByte){
29985   unixFile *pFile = (unixFile *)id;
29986   int rc;
29987   assert( pFile );
29988   SimulateIOError( return SQLCIPHER_IOERR_TRUNCATE );
29989
29990   /* If the user has configured a chunk-size for this file, truncate the
29991   ** file so that it consists of an integer number of chunks (i.e. the
29992   ** actual file size after the operation may be larger than the requested
29993   ** size).
29994   */
29995   if( pFile->szChunk ){
29996     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
29997   }
29998
29999   rc = robust_ftruncate(pFile->h, (off_t)nByte);
30000   if( rc ){
30001     pFile->lastErrno = errno;
30002     return unixLogError(SQLCIPHER_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
30003   }else{
30004 #ifndef NDEBUG
30005     /* If we are doing a normal write to a database file (as opposed to
30006     ** doing a hot-journal rollback or a write to some file other than a
30007     ** normal database file) and we truncate the file to zero length,
30008     ** that effectively updates the change counter.  This might happen
30009     ** when restoring a database using the backup API from a zero-length
30010     ** source.
30011     */
30012     if( pFile->inNormalWrite && nByte==0 ){
30013       pFile->transCntrChng = 1;
30014     }
30015 #endif
30016
30017     return SQLCIPHER_OK;
30018   }
30019 }
30020
30021 /*
30022 ** Determine the current size of a file in bytes
30023 */
30024 static int unixFileSize(sqlcipher3_file *id, i64 *pSize){
30025   int rc;
30026   struct stat buf;
30027   assert( id );
30028   rc = osFstat(((unixFile*)id)->h, &buf);
30029   SimulateIOError( rc=1 );
30030   if( rc!=0 ){
30031     ((unixFile*)id)->lastErrno = errno;
30032     return SQLCIPHER_IOERR_FSTAT;
30033   }
30034   *pSize = buf.st_size;
30035
30036   /* When opening a zero-size database, the findInodeInfo() procedure
30037   ** writes a single byte into that file in order to work around a bug
30038   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
30039   ** layers, we need to report this file size as zero even though it is
30040   ** really 1.   Ticket #3260.
30041   */
30042   if( *pSize==1 ) *pSize = 0;
30043
30044
30045   return SQLCIPHER_OK;
30046 }
30047
30048 #if SQLCIPHER_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30049 /*
30050 ** Handler for proxy-locking file-control verbs.  Defined below in the
30051 ** proxying locking division.
30052 */
30053 static int proxyFileControl(sqlcipher3_file*,int,void*);
30054 #endif
30055
30056 /* 
30057 ** This function is called to handle the SQLCIPHER_FCNTL_SIZE_HINT 
30058 ** file-control operation.  Enlarge the database to nBytes in size
30059 ** (rounded up to the next chunk-size).  If the database is already
30060 ** nBytes or larger, this routine is a no-op.
30061 */
30062 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
30063   if( pFile->szChunk>0 ){
30064     i64 nSize;                    /* Required file size */
30065     struct stat buf;              /* Used to hold return values of fstat() */
30066    
30067     if( osFstat(pFile->h, &buf) ) return SQLCIPHER_IOERR_FSTAT;
30068
30069     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
30070     if( nSize>(i64)buf.st_size ){
30071
30072 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
30073       /* The code below is handling the return value of osFallocate() 
30074       ** correctly. posix_fallocate() is defined to "returns zero on success, 
30075       ** or an error number on  failure". See the manpage for details. */
30076       int err;
30077       do{
30078         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
30079       }while( err==EINTR );
30080       if( err ) return SQLCIPHER_IOERR_WRITE;
30081 #else
30082       /* If the OS does not have posix_fallocate(), fake it. First use
30083       ** ftruncate() to set the file size, then write a single byte to
30084       ** the last byte in each block within the extended region. This
30085       ** is the same technique used by glibc to implement posix_fallocate()
30086       ** on systems that do not have a real fallocate() system call.
30087       */
30088       int nBlk = buf.st_blksize;  /* File-system block size */
30089       i64 iWrite;                 /* Next offset to write to */
30090
30091       if( robust_ftruncate(pFile->h, nSize) ){
30092         pFile->lastErrno = errno;
30093         return unixLogError(SQLCIPHER_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
30094       }
30095       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
30096       while( iWrite<nSize ){
30097         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
30098         if( nWrite!=1 ) return SQLCIPHER_IOERR_WRITE;
30099         iWrite += nBlk;
30100       }
30101 #endif
30102     }
30103   }
30104
30105   return SQLCIPHER_OK;
30106 }
30107
30108 /*
30109 ** Information and control of an open file handle.
30110 */
30111 static int unixFileControl(sqlcipher3_file *id, int op, void *pArg){
30112   unixFile *pFile = (unixFile*)id;
30113   switch( op ){
30114     case SQLCIPHER_FCNTL_LOCKSTATE: {
30115       *(int*)pArg = pFile->eFileLock;
30116       return SQLCIPHER_OK;
30117     }
30118     case SQLCIPHER_LAST_ERRNO: {
30119       *(int*)pArg = pFile->lastErrno;
30120       return SQLCIPHER_OK;
30121     }
30122     case SQLCIPHER_FCNTL_CHUNK_SIZE: {
30123       pFile->szChunk = *(int *)pArg;
30124       return SQLCIPHER_OK;
30125     }
30126     case SQLCIPHER_FCNTL_SIZE_HINT: {
30127       int rc;
30128       SimulateIOErrorBenign(1);
30129       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
30130       SimulateIOErrorBenign(0);
30131       return rc;
30132     }
30133     case SQLCIPHER_FCNTL_PERSIST_WAL: {
30134       int bPersist = *(int*)pArg;
30135       if( bPersist<0 ){
30136         *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
30137       }else if( bPersist==0 ){
30138         pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
30139       }else{
30140         pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
30141       }
30142       return SQLCIPHER_OK;
30143     }
30144 #ifndef NDEBUG
30145     /* The pager calls this method to signal that it has done
30146     ** a rollback and that the database is therefore unchanged and
30147     ** it hence it is OK for the transaction change counter to be
30148     ** unchanged.
30149     */
30150     case SQLCIPHER_FCNTL_DB_UNCHANGED: {
30151       ((unixFile*)id)->dbUpdate = 0;
30152       return SQLCIPHER_OK;
30153     }
30154 #endif
30155 #if SQLCIPHER_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30156     case SQLCIPHER_SET_LOCKPROXYFILE:
30157     case SQLCIPHER_GET_LOCKPROXYFILE: {
30158       return proxyFileControl(id,op,pArg);
30159     }
30160 #endif /* SQLCIPHER_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
30161     case SQLCIPHER_FCNTL_SYNC_OMITTED: {
30162       return SQLCIPHER_OK;  /* A no-op */
30163     }
30164   }
30165   return SQLCIPHER_NOTFOUND;
30166 }
30167
30168 /*
30169 ** Return the sector size in bytes of the underlying block device for
30170 ** the specified file. This is almost always 512 bytes, but may be
30171 ** larger for some devices.
30172 **
30173 ** SQLite code assumes this function cannot fail. It also assumes that
30174 ** if two files are created in the same file-system directory (i.e.
30175 ** a database and its journal file) that the sector size will be the
30176 ** same for both.
30177 */
30178 static int unixSectorSize(sqlcipher3_file *NotUsed){
30179   UNUSED_PARAMETER(NotUsed);
30180   return SQLCIPHER_DEFAULT_SECTOR_SIZE;
30181 }
30182
30183 /*
30184 ** Return the device characteristics for the file. This is always 0 for unix.
30185 */
30186 static int unixDeviceCharacteristics(sqlcipher3_file *NotUsed){
30187   UNUSED_PARAMETER(NotUsed);
30188   return 0;
30189 }
30190
30191 #ifndef SQLCIPHER_OMIT_WAL
30192
30193
30194 /*
30195 ** Object used to represent an shared memory buffer.  
30196 **
30197 ** When multiple threads all reference the same wal-index, each thread
30198 ** has its own unixShm object, but they all point to a single instance
30199 ** of this unixShmNode object.  In other words, each wal-index is opened
30200 ** only once per process.
30201 **
30202 ** Each unixShmNode object is connected to a single unixInodeInfo object.
30203 ** We could coalesce this object into unixInodeInfo, but that would mean
30204 ** every open file that does not use shared memory (in other words, most
30205 ** open files) would have to carry around this extra information.  So
30206 ** the unixInodeInfo object contains a pointer to this unixShmNode object
30207 ** and the unixShmNode object is created only when needed.
30208 **
30209 ** unixMutexHeld() must be true when creating or destroying
30210 ** this object or while reading or writing the following fields:
30211 **
30212 **      nRef
30213 **
30214 ** The following fields are read-only after the object is created:
30215 ** 
30216 **      fid
30217 **      zFilename
30218 **
30219 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
30220 ** unixMutexHeld() is true when reading or writing any other field
30221 ** in this structure.
30222 */
30223 struct unixShmNode {
30224   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
30225   sqlcipher3_mutex *mutex;      /* Mutex to access this object */
30226   char *zFilename;           /* Name of the mmapped file */
30227   int h;                     /* Open file descriptor */
30228   int szRegion;              /* Size of shared-memory regions */
30229   u16 nRegion;               /* Size of array apRegion */
30230   u8 isReadonly;             /* True if read-only */
30231   char **apRegion;           /* Array of mapped shared-memory regions */
30232   int nRef;                  /* Number of unixShm objects pointing to this */
30233   unixShm *pFirst;           /* All unixShm objects pointing to this */
30234 #ifdef SQLCIPHER_DEBUG
30235   u8 exclMask;               /* Mask of exclusive locks held */
30236   u8 sharedMask;             /* Mask of shared locks held */
30237   u8 nextShmId;              /* Next available unixShm.id value */
30238 #endif
30239 };
30240
30241 /*
30242 ** Structure used internally by this VFS to record the state of an
30243 ** open shared memory connection.
30244 **
30245 ** The following fields are initialized when this object is created and
30246 ** are read-only thereafter:
30247 **
30248 **    unixShm.pFile
30249 **    unixShm.id
30250 **
30251 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
30252 ** while accessing any read/write fields.
30253 */
30254 struct unixShm {
30255   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
30256   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
30257   u8 hasMutex;               /* True if holding the unixShmNode mutex */
30258   u8 id;                     /* Id of this connection within its unixShmNode */
30259   u16 sharedMask;            /* Mask of shared locks held */
30260   u16 exclMask;              /* Mask of exclusive locks held */
30261 };
30262
30263 /*
30264 ** Constants used for locking
30265 */
30266 #define UNIX_SHM_BASE   ((22+SQLCIPHER_SHM_NLOCK)*4)         /* first lock byte */
30267 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLCIPHER_SHM_NLOCK)  /* deadman switch */
30268
30269 /*
30270 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
30271 **
30272 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
30273 ** otherwise.
30274 */
30275 static int unixShmSystemLock(
30276   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
30277   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
30278   int ofst,              /* First byte of the locking range */
30279   int n                  /* Number of bytes to lock */
30280 ){
30281   struct flock f;       /* The posix advisory locking structure */
30282   int rc = SQLCIPHER_OK;   /* Result code form fcntl() */
30283
30284   /* Access to the unixShmNode object is serialized by the caller */
30285   assert( sqlcipher3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
30286
30287   /* Shared locks never span more than one byte */
30288   assert( n==1 || lockType!=F_RDLCK );
30289
30290   /* Locks are within range */
30291   assert( n>=1 && n<SQLCIPHER_SHM_NLOCK );
30292
30293   if( pShmNode->h>=0 ){
30294     /* Initialize the locking parameters */
30295     memset(&f, 0, sizeof(f));
30296     f.l_type = lockType;
30297     f.l_whence = SEEK_SET;
30298     f.l_start = ofst;
30299     f.l_len = n;
30300
30301     rc = osFcntl(pShmNode->h, F_SETLK, &f);
30302     rc = (rc!=(-1)) ? SQLCIPHER_OK : SQLCIPHER_BUSY;
30303   }
30304
30305   /* Update the global lock state and do debug tracing */
30306 #ifdef SQLCIPHER_DEBUG
30307   { u16 mask;
30308   OSTRACE(("SHM-LOCK "));
30309   mask = (1<<(ofst+n)) - (1<<ofst);
30310   if( rc==SQLCIPHER_OK ){
30311     if( lockType==F_UNLCK ){
30312       OSTRACE(("unlock %d ok", ofst));
30313       pShmNode->exclMask &= ~mask;
30314       pShmNode->sharedMask &= ~mask;
30315     }else if( lockType==F_RDLCK ){
30316       OSTRACE(("read-lock %d ok", ofst));
30317       pShmNode->exclMask &= ~mask;
30318       pShmNode->sharedMask |= mask;
30319     }else{
30320       assert( lockType==F_WRLCK );
30321       OSTRACE(("write-lock %d ok", ofst));
30322       pShmNode->exclMask |= mask;
30323       pShmNode->sharedMask &= ~mask;
30324     }
30325   }else{
30326     if( lockType==F_UNLCK ){
30327       OSTRACE(("unlock %d failed", ofst));
30328     }else if( lockType==F_RDLCK ){
30329       OSTRACE(("read-lock failed"));
30330     }else{
30331       assert( lockType==F_WRLCK );
30332       OSTRACE(("write-lock %d failed", ofst));
30333     }
30334   }
30335   OSTRACE((" - afterwards %03x,%03x\n",
30336            pShmNode->sharedMask, pShmNode->exclMask));
30337   }
30338 #endif
30339
30340   return rc;        
30341 }
30342
30343
30344 /*
30345 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
30346 **
30347 ** This is not a VFS shared-memory method; it is a utility function called
30348 ** by VFS shared-memory methods.
30349 */
30350 static void unixShmPurge(unixFile *pFd){
30351   unixShmNode *p = pFd->pInode->pShmNode;
30352   assert( unixMutexHeld() );
30353   if( p && p->nRef==0 ){
30354     int i;
30355     assert( p->pInode==pFd->pInode );
30356     sqlcipher3_mutex_free(p->mutex);
30357     for(i=0; i<p->nRegion; i++){
30358       if( p->h>=0 ){
30359         munmap(p->apRegion[i], p->szRegion);
30360       }else{
30361         sqlcipher3_free(p->apRegion[i]);
30362       }
30363     }
30364     sqlcipher3_free(p->apRegion);
30365     if( p->h>=0 ){
30366       robust_close(pFd, p->h, __LINE__);
30367       p->h = -1;
30368     }
30369     p->pInode->pShmNode = 0;
30370     sqlcipher3_free(p);
30371   }
30372 }
30373
30374 /*
30375 ** Open a shared-memory area associated with open database file pDbFd.  
30376 ** This particular implementation uses mmapped files.
30377 **
30378 ** The file used to implement shared-memory is in the same directory
30379 ** as the open database file and has the same name as the open database
30380 ** file with the "-shm" suffix added.  For example, if the database file
30381 ** is "/home/user1/config.db" then the file that is created and mmapped
30382 ** for shared memory will be called "/home/user1/config.db-shm".  
30383 **
30384 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
30385 ** some other tmpfs mount. But if a file in a different directory
30386 ** from the database file is used, then differing access permissions
30387 ** or a chroot() might cause two different processes on the same
30388 ** database to end up using different files for shared memory - 
30389 ** meaning that their memory would not really be shared - resulting
30390 ** in database corruption.  Nevertheless, this tmpfs file usage
30391 ** can be enabled at compile-time using -DSQLCIPHER_SHM_DIRECTORY="/dev/shm"
30392 ** or the equivalent.  The use of the SQLCIPHER_SHM_DIRECTORY compile-time
30393 ** option results in an incompatible build of SQLite;  builds of SQLite
30394 ** that with differing SQLCIPHER_SHM_DIRECTORY settings attempt to use the
30395 ** same database file at the same time, database corruption will likely
30396 ** result. The SQLCIPHER_SHM_DIRECTORY compile-time option is considered
30397 ** "unsupported" and may go away in a future SQLite release.
30398 **
30399 ** When opening a new shared-memory file, if no other instances of that
30400 ** file are currently open, in this process or in other processes, then
30401 ** the file must be truncated to zero length or have its header cleared.
30402 **
30403 ** If the original database file (pDbFd) is using the "unix-excl" VFS
30404 ** that means that an exclusive lock is held on the database file and
30405 ** that no other processes are able to read or write the database.  In
30406 ** that case, we do not really need shared memory.  No shared memory
30407 ** file is created.  The shared memory will be simulated with heap memory.
30408 */
30409 static int unixOpenSharedMemory(unixFile *pDbFd){
30410   struct unixShm *p = 0;          /* The connection to be opened */
30411   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
30412   int rc;                         /* Result code */
30413   unixInodeInfo *pInode;          /* The inode of fd */
30414   char *zShmFilename;             /* Name of the file used for SHM */
30415   int nShmFilename;               /* Size of the SHM filename in bytes */
30416
30417   /* Allocate space for the new unixShm object. */
30418   p = sqlcipher3_malloc( sizeof(*p) );
30419   if( p==0 ) return SQLCIPHER_NOMEM;
30420   memset(p, 0, sizeof(*p));
30421   assert( pDbFd->pShm==0 );
30422
30423   /* Check to see if a unixShmNode object already exists. Reuse an existing
30424   ** one if present. Create a new one if necessary.
30425   */
30426   unixEnterMutex();
30427   pInode = pDbFd->pInode;
30428   pShmNode = pInode->pShmNode;
30429   if( pShmNode==0 ){
30430     struct stat sStat;                 /* fstat() info for database file */
30431
30432     /* Call fstat() to figure out the permissions on the database file. If
30433     ** a new *-shm file is created, an attempt will be made to create it
30434     ** with the same permissions. The actual permissions the file is created
30435     ** with are subject to the current umask setting.
30436     */
30437     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
30438       rc = SQLCIPHER_IOERR_FSTAT;
30439       goto shm_open_err;
30440     }
30441
30442 #ifdef SQLCIPHER_SHM_DIRECTORY
30443     nShmFilename = sizeof(SQLCIPHER_SHM_DIRECTORY) + 30;
30444 #else
30445     nShmFilename = 5 + (int)strlen(pDbFd->zPath);
30446 #endif
30447     pShmNode = sqlcipher3_malloc( sizeof(*pShmNode) + nShmFilename );
30448     if( pShmNode==0 ){
30449       rc = SQLCIPHER_NOMEM;
30450       goto shm_open_err;
30451     }
30452     memset(pShmNode, 0, sizeof(*pShmNode));
30453     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
30454 #ifdef SQLCIPHER_SHM_DIRECTORY
30455     sqlcipher3_snprintf(nShmFilename, zShmFilename, 
30456                      SQLCIPHER_SHM_DIRECTORY "/sqlcipher-shm-%x-%x",
30457                      (u32)sStat.st_ino, (u32)sStat.st_dev);
30458 #else
30459     sqlcipher3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
30460     sqlcipher3FileSuffix3(pDbFd->zPath, zShmFilename);
30461 #endif
30462     pShmNode->h = -1;
30463     pDbFd->pInode->pShmNode = pShmNode;
30464     pShmNode->pInode = pDbFd->pInode;
30465     pShmNode->mutex = sqlcipher3_mutex_alloc(SQLCIPHER_MUTEX_FAST);
30466     if( pShmNode->mutex==0 ){
30467       rc = SQLCIPHER_NOMEM;
30468       goto shm_open_err;
30469     }
30470
30471     if( pInode->bProcessLock==0 ){
30472       const char *zRO;
30473       int openFlags = O_RDWR | O_CREAT;
30474       zRO = sqlcipher3_uri_parameter(pDbFd->zPath, "readonly_shm");
30475       if( zRO && sqlcipher3GetBoolean(zRO) ){
30476         openFlags = O_RDONLY;
30477         pShmNode->isReadonly = 1;
30478       }
30479       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
30480       if( pShmNode->h<0 ){
30481         if( pShmNode->h<0 ){
30482           rc = unixLogError(SQLCIPHER_CANTOPEN_BKPT, "open", zShmFilename);
30483           goto shm_open_err;
30484         }
30485       }
30486   
30487       /* Check to see if another process is holding the dead-man switch.
30488       ** If not, truncate the file to zero length. 
30489       */
30490       rc = SQLCIPHER_OK;
30491       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLCIPHER_OK ){
30492         if( robust_ftruncate(pShmNode->h, 0) ){
30493           rc = unixLogError(SQLCIPHER_IOERR_SHMOPEN, "ftruncate", zShmFilename);
30494         }
30495       }
30496       if( rc==SQLCIPHER_OK ){
30497         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
30498       }
30499       if( rc ) goto shm_open_err;
30500     }
30501   }
30502
30503   /* Make the new connection a child of the unixShmNode */
30504   p->pShmNode = pShmNode;
30505 #ifdef SQLCIPHER_DEBUG
30506   p->id = pShmNode->nextShmId++;
30507 #endif
30508   pShmNode->nRef++;
30509   pDbFd->pShm = p;
30510   unixLeaveMutex();
30511
30512   /* The reference count on pShmNode has already been incremented under
30513   ** the cover of the unixEnterMutex() mutex and the pointer from the
30514   ** new (struct unixShm) object to the pShmNode has been set. All that is
30515   ** left to do is to link the new object into the linked list starting
30516   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
30517   ** mutex.
30518   */
30519   sqlcipher3_mutex_enter(pShmNode->mutex);
30520   p->pNext = pShmNode->pFirst;
30521   pShmNode->pFirst = p;
30522   sqlcipher3_mutex_leave(pShmNode->mutex);
30523   return SQLCIPHER_OK;
30524
30525   /* Jump here on any error */
30526 shm_open_err:
30527   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
30528   sqlcipher3_free(p);
30529   unixLeaveMutex();
30530   return rc;
30531 }
30532
30533 /*
30534 ** This function is called to obtain a pointer to region iRegion of the 
30535 ** shared-memory associated with the database file fd. Shared-memory regions 
30536 ** are numbered starting from zero. Each shared-memory region is szRegion 
30537 ** bytes in size.
30538 **
30539 ** If an error occurs, an error code is returned and *pp is set to NULL.
30540 **
30541 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
30542 ** region has not been allocated (by any client, including one running in a
30543 ** separate process), then *pp is set to NULL and SQLCIPHER_OK returned. If 
30544 ** bExtend is non-zero and the requested shared-memory region has not yet 
30545 ** been allocated, it is allocated by this function.
30546 **
30547 ** If the shared-memory region has already been allocated or is allocated by
30548 ** this call as described above, then it is mapped into this processes 
30549 ** address space (if it is not already), *pp is set to point to the mapped 
30550 ** memory and SQLCIPHER_OK returned.
30551 */
30552 static int unixShmMap(
30553   sqlcipher3_file *fd,               /* Handle open on database file */
30554   int iRegion,                    /* Region to retrieve */
30555   int szRegion,                   /* Size of regions */
30556   int bExtend,                    /* True to extend file if necessary */
30557   void volatile **pp              /* OUT: Mapped memory */
30558 ){
30559   unixFile *pDbFd = (unixFile*)fd;
30560   unixShm *p;
30561   unixShmNode *pShmNode;
30562   int rc = SQLCIPHER_OK;
30563
30564   /* If the shared-memory file has not yet been opened, open it now. */
30565   if( pDbFd->pShm==0 ){
30566     rc = unixOpenSharedMemory(pDbFd);
30567     if( rc!=SQLCIPHER_OK ) return rc;
30568   }
30569
30570   p = pDbFd->pShm;
30571   pShmNode = p->pShmNode;
30572   sqlcipher3_mutex_enter(pShmNode->mutex);
30573   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
30574   assert( pShmNode->pInode==pDbFd->pInode );
30575   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
30576   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
30577
30578   if( pShmNode->nRegion<=iRegion ){
30579     char **apNew;                      /* New apRegion[] array */
30580     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
30581     struct stat sStat;                 /* Used by fstat() */
30582
30583     pShmNode->szRegion = szRegion;
30584
30585     if( pShmNode->h>=0 ){
30586       /* The requested region is not mapped into this processes address space.
30587       ** Check to see if it has been allocated (i.e. if the wal-index file is
30588       ** large enough to contain the requested region).
30589       */
30590       if( osFstat(pShmNode->h, &sStat) ){
30591         rc = SQLCIPHER_IOERR_SHMSIZE;
30592         goto shmpage_out;
30593       }
30594   
30595       if( sStat.st_size<nByte ){
30596         /* The requested memory region does not exist. If bExtend is set to
30597         ** false, exit early. *pp will be set to NULL and SQLCIPHER_OK returned.
30598         **
30599         ** Alternatively, if bExtend is true, use ftruncate() to allocate
30600         ** the requested memory region.
30601         */
30602         if( !bExtend ) goto shmpage_out;
30603         if( robust_ftruncate(pShmNode->h, nByte) ){
30604           rc = unixLogError(SQLCIPHER_IOERR_SHMSIZE, "ftruncate",
30605                             pShmNode->zFilename);
30606           goto shmpage_out;
30607         }
30608       }
30609     }
30610
30611     /* Map the requested memory region into this processes address space. */
30612     apNew = (char **)sqlcipher3_realloc(
30613         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
30614     );
30615     if( !apNew ){
30616       rc = SQLCIPHER_IOERR_NOMEM;
30617       goto shmpage_out;
30618     }
30619     pShmNode->apRegion = apNew;
30620     while(pShmNode->nRegion<=iRegion){
30621       void *pMem;
30622       if( pShmNode->h>=0 ){
30623         pMem = mmap(0, szRegion,
30624             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
30625             MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
30626         );
30627         if( pMem==MAP_FAILED ){
30628           rc = unixLogError(SQLCIPHER_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
30629           goto shmpage_out;
30630         }
30631       }else{
30632         pMem = sqlcipher3_malloc(szRegion);
30633         if( pMem==0 ){
30634           rc = SQLCIPHER_NOMEM;
30635           goto shmpage_out;
30636         }
30637         memset(pMem, 0, szRegion);
30638       }
30639       pShmNode->apRegion[pShmNode->nRegion] = pMem;
30640       pShmNode->nRegion++;
30641     }
30642   }
30643
30644 shmpage_out:
30645   if( pShmNode->nRegion>iRegion ){
30646     *pp = pShmNode->apRegion[iRegion];
30647   }else{
30648     *pp = 0;
30649   }
30650   if( pShmNode->isReadonly && rc==SQLCIPHER_OK ) rc = SQLCIPHER_READONLY;
30651   sqlcipher3_mutex_leave(pShmNode->mutex);
30652   return rc;
30653 }
30654
30655 /*
30656 ** Change the lock state for a shared-memory segment.
30657 **
30658 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
30659 ** different here than in posix.  In xShmLock(), one can go from unlocked
30660 ** to shared and back or from unlocked to exclusive and back.  But one may
30661 ** not go from shared to exclusive or from exclusive to shared.
30662 */
30663 static int unixShmLock(
30664   sqlcipher3_file *fd,          /* Database file holding the shared memory */
30665   int ofst,                  /* First lock to acquire or release */
30666   int n,                     /* Number of locks to acquire or release */
30667   int flags                  /* What to do with the lock */
30668 ){
30669   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
30670   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
30671   unixShm *pX;                          /* For looping over all siblings */
30672   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
30673   int rc = SQLCIPHER_OK;                   /* Result code */
30674   u16 mask;                             /* Mask of locks to take or release */
30675
30676   assert( pShmNode==pDbFd->pInode->pShmNode );
30677   assert( pShmNode->pInode==pDbFd->pInode );
30678   assert( ofst>=0 && ofst+n<=SQLCIPHER_SHM_NLOCK );
30679   assert( n>=1 );
30680   assert( flags==(SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_SHARED)
30681        || flags==(SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_EXCLUSIVE)
30682        || flags==(SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_SHARED)
30683        || flags==(SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_EXCLUSIVE) );
30684   assert( n==1 || (flags & SQLCIPHER_SHM_EXCLUSIVE)!=0 );
30685   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
30686   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
30687
30688   mask = (1<<(ofst+n)) - (1<<ofst);
30689   assert( n>1 || mask==(1<<ofst) );
30690   sqlcipher3_mutex_enter(pShmNode->mutex);
30691   if( flags & SQLCIPHER_SHM_UNLOCK ){
30692     u16 allMask = 0; /* Mask of locks held by siblings */
30693
30694     /* See if any siblings hold this same lock */
30695     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30696       if( pX==p ) continue;
30697       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
30698       allMask |= pX->sharedMask;
30699     }
30700
30701     /* Unlock the system-level locks */
30702     if( (mask & allMask)==0 ){
30703       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
30704     }else{
30705       rc = SQLCIPHER_OK;
30706     }
30707
30708     /* Undo the local locks */
30709     if( rc==SQLCIPHER_OK ){
30710       p->exclMask &= ~mask;
30711       p->sharedMask &= ~mask;
30712     } 
30713   }else if( flags & SQLCIPHER_SHM_SHARED ){
30714     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
30715
30716     /* Find out which shared locks are already held by sibling connections.
30717     ** If any sibling already holds an exclusive lock, go ahead and return
30718     ** SQLCIPHER_BUSY.
30719     */
30720     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30721       if( (pX->exclMask & mask)!=0 ){
30722         rc = SQLCIPHER_BUSY;
30723         break;
30724       }
30725       allShared |= pX->sharedMask;
30726     }
30727
30728     /* Get shared locks at the system level, if necessary */
30729     if( rc==SQLCIPHER_OK ){
30730       if( (allShared & mask)==0 ){
30731         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
30732       }else{
30733         rc = SQLCIPHER_OK;
30734       }
30735     }
30736
30737     /* Get the local shared locks */
30738     if( rc==SQLCIPHER_OK ){
30739       p->sharedMask |= mask;
30740     }
30741   }else{
30742     /* Make sure no sibling connections hold locks that will block this
30743     ** lock.  If any do, return SQLCIPHER_BUSY right away.
30744     */
30745     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30746       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
30747         rc = SQLCIPHER_BUSY;
30748         break;
30749       }
30750     }
30751   
30752     /* Get the exclusive locks at the system level.  Then if successful
30753     ** also mark the local connection as being locked.
30754     */
30755     if( rc==SQLCIPHER_OK ){
30756       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
30757       if( rc==SQLCIPHER_OK ){
30758         assert( (p->sharedMask & mask)==0 );
30759         p->exclMask |= mask;
30760       }
30761     }
30762   }
30763   sqlcipher3_mutex_leave(pShmNode->mutex);
30764   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
30765            p->id, getpid(), p->sharedMask, p->exclMask));
30766   return rc;
30767 }
30768
30769 /*
30770 ** Implement a memory barrier or memory fence on shared memory.  
30771 **
30772 ** All loads and stores begun before the barrier must complete before
30773 ** any load or store begun after the barrier.
30774 */
30775 static void unixShmBarrier(
30776   sqlcipher3_file *fd                /* Database file holding the shared memory */
30777 ){
30778   UNUSED_PARAMETER(fd);
30779   unixEnterMutex();
30780   unixLeaveMutex();
30781 }
30782
30783 /*
30784 ** Close a connection to shared-memory.  Delete the underlying 
30785 ** storage if deleteFlag is true.
30786 **
30787 ** If there is no shared memory associated with the connection then this
30788 ** routine is a harmless no-op.
30789 */
30790 static int unixShmUnmap(
30791   sqlcipher3_file *fd,               /* The underlying database file */
30792   int deleteFlag                  /* Delete shared-memory if true */
30793 ){
30794   unixShm *p;                     /* The connection to be closed */
30795   unixShmNode *pShmNode;          /* The underlying shared-memory file */
30796   unixShm **pp;                   /* For looping over sibling connections */
30797   unixFile *pDbFd;                /* The underlying database file */
30798
30799   pDbFd = (unixFile*)fd;
30800   p = pDbFd->pShm;
30801   if( p==0 ) return SQLCIPHER_OK;
30802   pShmNode = p->pShmNode;
30803
30804   assert( pShmNode==pDbFd->pInode->pShmNode );
30805   assert( pShmNode->pInode==pDbFd->pInode );
30806
30807   /* Remove connection p from the set of connections associated
30808   ** with pShmNode */
30809   sqlcipher3_mutex_enter(pShmNode->mutex);
30810   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
30811   *pp = p->pNext;
30812
30813   /* Free the connection p */
30814   sqlcipher3_free(p);
30815   pDbFd->pShm = 0;
30816   sqlcipher3_mutex_leave(pShmNode->mutex);
30817
30818   /* If pShmNode->nRef has reached 0, then close the underlying
30819   ** shared-memory file, too */
30820   unixEnterMutex();
30821   assert( pShmNode->nRef>0 );
30822   pShmNode->nRef--;
30823   if( pShmNode->nRef==0 ){
30824     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
30825     unixShmPurge(pDbFd);
30826   }
30827   unixLeaveMutex();
30828
30829   return SQLCIPHER_OK;
30830 }
30831
30832
30833 #else
30834 # define unixShmMap     0
30835 # define unixShmLock    0
30836 # define unixShmBarrier 0
30837 # define unixShmUnmap   0
30838 #endif /* #ifndef SQLCIPHER_OMIT_WAL */
30839
30840 /*
30841 ** Here ends the implementation of all sqlcipher3_file methods.
30842 **
30843 ********************** End sqlcipher3_file Methods *******************************
30844 ******************************************************************************/
30845
30846 /*
30847 ** This division contains definitions of sqlcipher3_io_methods objects that
30848 ** implement various file locking strategies.  It also contains definitions
30849 ** of "finder" functions.  A finder-function is used to locate the appropriate
30850 ** sqlcipher3_io_methods object for a particular database file.  The pAppData
30851 ** field of the sqlcipher3_vfs VFS objects are initialized to be pointers to
30852 ** the correct finder-function for that VFS.
30853 **
30854 ** Most finder functions return a pointer to a fixed sqlcipher3_io_methods
30855 ** object.  The only interesting finder-function is autolockIoFinder, which
30856 ** looks at the filesystem type and tries to guess the best locking
30857 ** strategy from that.
30858 **
30859 ** For finder-funtion F, two objects are created:
30860 **
30861 **    (1) The real finder-function named "FImpt()".
30862 **
30863 **    (2) A constant pointer to this function named just "F".
30864 **
30865 **
30866 ** A pointer to the F pointer is used as the pAppData value for VFS
30867 ** objects.  We have to do this instead of letting pAppData point
30868 ** directly at the finder-function since C90 rules prevent a void*
30869 ** from be cast into a function pointer.
30870 **
30871 **
30872 ** Each instance of this macro generates two objects:
30873 **
30874 **   *  A constant sqlcipher3_io_methods object call METHOD that has locking
30875 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
30876 **
30877 **   *  An I/O method finder function called FINDER that returns a pointer
30878 **      to the METHOD object in the previous bullet.
30879 */
30880 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
30881 static const sqlcipher3_io_methods METHOD = {                                   \
30882    VERSION,                    /* iVersion */                                \
30883    CLOSE,                      /* xClose */                                  \
30884    unixRead,                   /* xRead */                                   \
30885    unixWrite,                  /* xWrite */                                  \
30886    unixTruncate,               /* xTruncate */                               \
30887    unixSync,                   /* xSync */                                   \
30888    unixFileSize,               /* xFileSize */                               \
30889    LOCK,                       /* xLock */                                   \
30890    UNLOCK,                     /* xUnlock */                                 \
30891    CKLOCK,                     /* xCheckReservedLock */                      \
30892    unixFileControl,            /* xFileControl */                            \
30893    unixSectorSize,             /* xSectorSize */                             \
30894    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
30895    unixShmMap,                 /* xShmMap */                                 \
30896    unixShmLock,                /* xShmLock */                                \
30897    unixShmBarrier,             /* xShmBarrier */                             \
30898    unixShmUnmap                /* xShmUnmap */                               \
30899 };                                                                           \
30900 static const sqlcipher3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
30901   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
30902   return &METHOD;                                                            \
30903 }                                                                            \
30904 static const sqlcipher3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
30905     = FINDER##Impl;
30906
30907 /*
30908 ** Here are all of the sqlcipher3_io_methods objects for each of the
30909 ** locking strategies.  Functions that return pointers to these methods
30910 ** are also created.
30911 */
30912 IOMETHODS(
30913   posixIoFinder,            /* Finder function name */
30914   posixIoMethods,           /* sqlcipher3_io_methods object name */
30915   2,                        /* shared memory is enabled */
30916   unixClose,                /* xClose method */
30917   unixLock,                 /* xLock method */
30918   unixUnlock,               /* xUnlock method */
30919   unixCheckReservedLock     /* xCheckReservedLock method */
30920 )
30921 IOMETHODS(
30922   nolockIoFinder,           /* Finder function name */
30923   nolockIoMethods,          /* sqlcipher3_io_methods object name */
30924   1,                        /* shared memory is disabled */
30925   nolockClose,              /* xClose method */
30926   nolockLock,               /* xLock method */
30927   nolockUnlock,             /* xUnlock method */
30928   nolockCheckReservedLock   /* xCheckReservedLock method */
30929 )
30930 IOMETHODS(
30931   dotlockIoFinder,          /* Finder function name */
30932   dotlockIoMethods,         /* sqlcipher3_io_methods object name */
30933   1,                        /* shared memory is disabled */
30934   dotlockClose,             /* xClose method */
30935   dotlockLock,              /* xLock method */
30936   dotlockUnlock,            /* xUnlock method */
30937   dotlockCheckReservedLock  /* xCheckReservedLock method */
30938 )
30939
30940 #if SQLCIPHER_ENABLE_LOCKING_STYLE && !OS_VXWORKS
30941 IOMETHODS(
30942   flockIoFinder,            /* Finder function name */
30943   flockIoMethods,           /* sqlcipher3_io_methods object name */
30944   1,                        /* shared memory is disabled */
30945   flockClose,               /* xClose method */
30946   flockLock,                /* xLock method */
30947   flockUnlock,              /* xUnlock method */
30948   flockCheckReservedLock    /* xCheckReservedLock method */
30949 )
30950 #endif
30951
30952 #if OS_VXWORKS
30953 IOMETHODS(
30954   semIoFinder,              /* Finder function name */
30955   semIoMethods,             /* sqlcipher3_io_methods object name */
30956   1,                        /* shared memory is disabled */
30957   semClose,                 /* xClose method */
30958   semLock,                  /* xLock method */
30959   semUnlock,                /* xUnlock method */
30960   semCheckReservedLock      /* xCheckReservedLock method */
30961 )
30962 #endif
30963
30964 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
30965 IOMETHODS(
30966   afpIoFinder,              /* Finder function name */
30967   afpIoMethods,             /* sqlcipher3_io_methods object name */
30968   1,                        /* shared memory is disabled */
30969   afpClose,                 /* xClose method */
30970   afpLock,                  /* xLock method */
30971   afpUnlock,                /* xUnlock method */
30972   afpCheckReservedLock      /* xCheckReservedLock method */
30973 )
30974 #endif
30975
30976 /*
30977 ** The proxy locking method is a "super-method" in the sense that it
30978 ** opens secondary file descriptors for the conch and lock files and
30979 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
30980 ** secondary files.  For this reason, the division that implements
30981 ** proxy locking is located much further down in the file.  But we need
30982 ** to go ahead and define the sqlcipher3_io_methods and finder function
30983 ** for proxy locking here.  So we forward declare the I/O methods.
30984 */
30985 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
30986 static int proxyClose(sqlcipher3_file*);
30987 static int proxyLock(sqlcipher3_file*, int);
30988 static int proxyUnlock(sqlcipher3_file*, int);
30989 static int proxyCheckReservedLock(sqlcipher3_file*, int*);
30990 IOMETHODS(
30991   proxyIoFinder,            /* Finder function name */
30992   proxyIoMethods,           /* sqlcipher3_io_methods object name */
30993   1,                        /* shared memory is disabled */
30994   proxyClose,               /* xClose method */
30995   proxyLock,                /* xLock method */
30996   proxyUnlock,              /* xUnlock method */
30997   proxyCheckReservedLock    /* xCheckReservedLock method */
30998 )
30999 #endif
31000
31001 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
31002 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
31003 IOMETHODS(
31004   nfsIoFinder,               /* Finder function name */
31005   nfsIoMethods,              /* sqlcipher3_io_methods object name */
31006   1,                         /* shared memory is disabled */
31007   unixClose,                 /* xClose method */
31008   unixLock,                  /* xLock method */
31009   nfsUnlock,                 /* xUnlock method */
31010   unixCheckReservedLock      /* xCheckReservedLock method */
31011 )
31012 #endif
31013
31014 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
31015 /* 
31016 ** This "finder" function attempts to determine the best locking strategy 
31017 ** for the database file "filePath".  It then returns the sqlcipher3_io_methods
31018 ** object that implements that strategy.
31019 **
31020 ** This is for MacOSX only.
31021 */
31022 static const sqlcipher3_io_methods *autolockIoFinderImpl(
31023   const char *filePath,    /* name of the database file */
31024   unixFile *pNew           /* open file object for the database file */
31025 ){
31026   static const struct Mapping {
31027     const char *zFilesystem;              /* Filesystem type name */
31028     const sqlcipher3_io_methods *pMethods;   /* Appropriate locking method */
31029   } aMap[] = {
31030     { "hfs",    &posixIoMethods },
31031     { "ufs",    &posixIoMethods },
31032     { "afpfs",  &afpIoMethods },
31033     { "smbfs",  &afpIoMethods },
31034     { "webdav", &nolockIoMethods },
31035     { 0, 0 }
31036   };
31037   int i;
31038   struct statfs fsInfo;
31039   struct flock lockInfo;
31040
31041   if( !filePath ){
31042     /* If filePath==NULL that means we are dealing with a transient file
31043     ** that does not need to be locked. */
31044     return &nolockIoMethods;
31045   }
31046   if( statfs(filePath, &fsInfo) != -1 ){
31047     if( fsInfo.f_flags & MNT_RDONLY ){
31048       return &nolockIoMethods;
31049     }
31050     for(i=0; aMap[i].zFilesystem; i++){
31051       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
31052         return aMap[i].pMethods;
31053       }
31054     }
31055   }
31056
31057   /* Default case. Handles, amongst others, "nfs".
31058   ** Test byte-range lock using fcntl(). If the call succeeds, 
31059   ** assume that the file-system supports POSIX style locks. 
31060   */
31061   lockInfo.l_len = 1;
31062   lockInfo.l_start = 0;
31063   lockInfo.l_whence = SEEK_SET;
31064   lockInfo.l_type = F_RDLCK;
31065   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
31066     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
31067       return &nfsIoMethods;
31068     } else {
31069       return &posixIoMethods;
31070     }
31071   }else{
31072     return &dotlockIoMethods;
31073   }
31074 }
31075 static const sqlcipher3_io_methods 
31076   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
31077
31078 #endif /* defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE */
31079
31080 #if OS_VXWORKS && SQLCIPHER_ENABLE_LOCKING_STYLE
31081 /* 
31082 ** This "finder" function attempts to determine the best locking strategy 
31083 ** for the database file "filePath".  It then returns the sqlcipher3_io_methods
31084 ** object that implements that strategy.
31085 **
31086 ** This is for VXWorks only.
31087 */
31088 static const sqlcipher3_io_methods *autolockIoFinderImpl(
31089   const char *filePath,    /* name of the database file */
31090   unixFile *pNew           /* the open file object */
31091 ){
31092   struct flock lockInfo;
31093
31094   if( !filePath ){
31095     /* If filePath==NULL that means we are dealing with a transient file
31096     ** that does not need to be locked. */
31097     return &nolockIoMethods;
31098   }
31099
31100   /* Test if fcntl() is supported and use POSIX style locks.
31101   ** Otherwise fall back to the named semaphore method.
31102   */
31103   lockInfo.l_len = 1;
31104   lockInfo.l_start = 0;
31105   lockInfo.l_whence = SEEK_SET;
31106   lockInfo.l_type = F_RDLCK;
31107   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
31108     return &posixIoMethods;
31109   }else{
31110     return &semIoMethods;
31111   }
31112 }
31113 static const sqlcipher3_io_methods 
31114   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
31115
31116 #endif /* OS_VXWORKS && SQLCIPHER_ENABLE_LOCKING_STYLE */
31117
31118 /*
31119 ** An abstract type for a pointer to a IO method finder function:
31120 */
31121 typedef const sqlcipher3_io_methods *(*finder_type)(const char*,unixFile*);
31122
31123
31124 /****************************************************************************
31125 **************************** sqlcipher3_vfs methods ****************************
31126 **
31127 ** This division contains the implementation of methods on the
31128 ** sqlcipher3_vfs object.
31129 */
31130
31131 /*
31132 ** Initialize the contents of the unixFile structure pointed to by pId.
31133 */
31134 static int fillInUnixFile(
31135   sqlcipher3_vfs *pVfs,      /* Pointer to vfs object */
31136   int h,                  /* Open file descriptor of file being opened */
31137   int syncDir,            /* True to sync directory on first sync */
31138   sqlcipher3_file *pId,      /* Write to the unixFile structure here */
31139   const char *zFilename,  /* Name of the file being opened */
31140   int noLock,             /* Omit locking if true */
31141   int isDelete,           /* Delete on close if true */
31142   int isReadOnly          /* True if the file is opened read-only */
31143 ){
31144   const sqlcipher3_io_methods *pLockingStyle;
31145   unixFile *pNew = (unixFile *)pId;
31146   int rc = SQLCIPHER_OK;
31147
31148   assert( pNew->pInode==NULL );
31149
31150   /* Parameter isDelete is only used on vxworks. Express this explicitly 
31151   ** here to prevent compiler warnings about unused parameters.
31152   */
31153   UNUSED_PARAMETER(isDelete);
31154
31155   /* Usually the path zFilename should not be a relative pathname. The
31156   ** exception is when opening the proxy "conch" file in builds that
31157   ** include the special Apple locking styles.
31158   */
31159 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
31160   assert( zFilename==0 || zFilename[0]=='/' 
31161     || pVfs->pAppData==(void*)&autolockIoFinder );
31162 #else
31163   assert( zFilename==0 || zFilename[0]=='/' );
31164 #endif
31165
31166   /* No locking occurs in temporary files */
31167   assert( zFilename!=0 || noLock );
31168
31169   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
31170   pNew->h = h;
31171   pNew->zPath = zFilename;
31172   if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
31173     pNew->ctrlFlags = UNIXFILE_EXCL;
31174   }else{
31175     pNew->ctrlFlags = 0;
31176   }
31177   if( isReadOnly ){
31178     pNew->ctrlFlags |= UNIXFILE_RDONLY;
31179   }
31180   if( syncDir ){
31181     pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
31182   }
31183
31184 #if OS_VXWORKS
31185   pNew->pId = vxworksFindFileId(zFilename);
31186   if( pNew->pId==0 ){
31187     noLock = 1;
31188     rc = SQLCIPHER_NOMEM;
31189   }
31190 #endif
31191
31192   if( noLock ){
31193     pLockingStyle = &nolockIoMethods;
31194   }else{
31195     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
31196 #if SQLCIPHER_ENABLE_LOCKING_STYLE
31197     /* Cache zFilename in the locking context (AFP and dotlock override) for
31198     ** proxyLock activation is possible (remote proxy is based on db name)
31199     ** zFilename remains valid until file is closed, to support */
31200     pNew->lockingContext = (void*)zFilename;
31201 #endif
31202   }
31203
31204   if( pLockingStyle == &posixIoMethods
31205 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
31206     || pLockingStyle == &nfsIoMethods
31207 #endif
31208   ){
31209     unixEnterMutex();
31210     rc = findInodeInfo(pNew, &pNew->pInode);
31211     if( rc!=SQLCIPHER_OK ){
31212       /* If an error occured in findInodeInfo(), close the file descriptor
31213       ** immediately, before releasing the mutex. findInodeInfo() may fail
31214       ** in two scenarios:
31215       **
31216       **   (a) A call to fstat() failed.
31217       **   (b) A malloc failed.
31218       **
31219       ** Scenario (b) may only occur if the process is holding no other
31220       ** file descriptors open on the same file. If there were other file
31221       ** descriptors on this file, then no malloc would be required by
31222       ** findInodeInfo(). If this is the case, it is quite safe to close
31223       ** handle h - as it is guaranteed that no posix locks will be released
31224       ** by doing so.
31225       **
31226       ** If scenario (a) caused the error then things are not so safe. The
31227       ** implicit assumption here is that if fstat() fails, things are in
31228       ** such bad shape that dropping a lock or two doesn't matter much.
31229       */
31230       robust_close(pNew, h, __LINE__);
31231       h = -1;
31232     }
31233     unixLeaveMutex();
31234   }
31235
31236 #if SQLCIPHER_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31237   else if( pLockingStyle == &afpIoMethods ){
31238     /* AFP locking uses the file path so it needs to be included in
31239     ** the afpLockingContext.
31240     */
31241     afpLockingContext *pCtx;
31242     pNew->lockingContext = pCtx = sqlcipher3_malloc( sizeof(*pCtx) );
31243     if( pCtx==0 ){
31244       rc = SQLCIPHER_NOMEM;
31245     }else{
31246       /* NB: zFilename exists and remains valid until the file is closed
31247       ** according to requirement F11141.  So we do not need to make a
31248       ** copy of the filename. */
31249       pCtx->dbPath = zFilename;
31250       pCtx->reserved = 0;
31251       srandomdev();
31252       unixEnterMutex();
31253       rc = findInodeInfo(pNew, &pNew->pInode);
31254       if( rc!=SQLCIPHER_OK ){
31255         sqlcipher3_free(pNew->lockingContext);
31256         robust_close(pNew, h, __LINE__);
31257         h = -1;
31258       }
31259       unixLeaveMutex();        
31260     }
31261   }
31262 #endif
31263
31264   else if( pLockingStyle == &dotlockIoMethods ){
31265     /* Dotfile locking uses the file path so it needs to be included in
31266     ** the dotlockLockingContext 
31267     */
31268     char *zLockFile;
31269     int nFilename;
31270     assert( zFilename!=0 );
31271     nFilename = (int)strlen(zFilename) + 6;
31272     zLockFile = (char *)sqlcipher3_malloc(nFilename);
31273     if( zLockFile==0 ){
31274       rc = SQLCIPHER_NOMEM;
31275     }else{
31276       sqlcipher3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
31277     }
31278     pNew->lockingContext = zLockFile;
31279   }
31280
31281 #if OS_VXWORKS
31282   else if( pLockingStyle == &semIoMethods ){
31283     /* Named semaphore locking uses the file path so it needs to be
31284     ** included in the semLockingContext
31285     */
31286     unixEnterMutex();
31287     rc = findInodeInfo(pNew, &pNew->pInode);
31288     if( (rc==SQLCIPHER_OK) && (pNew->pInode->pSem==NULL) ){
31289       char *zSemName = pNew->pInode->aSemName;
31290       int n;
31291       sqlcipher3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
31292                        pNew->pId->zCanonicalName);
31293       for( n=1; zSemName[n]; n++ )
31294         if( zSemName[n]=='/' ) zSemName[n] = '_';
31295       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
31296       if( pNew->pInode->pSem == SEM_FAILED ){
31297         rc = SQLCIPHER_NOMEM;
31298         pNew->pInode->aSemName[0] = '\0';
31299       }
31300     }
31301     unixLeaveMutex();
31302   }
31303 #endif
31304   
31305   pNew->lastErrno = 0;
31306 #if OS_VXWORKS
31307   if( rc!=SQLCIPHER_OK ){
31308     if( h>=0 ) robust_close(pNew, h, __LINE__);
31309     h = -1;
31310     osUnlink(zFilename);
31311     isDelete = 0;
31312   }
31313   pNew->isDelete = isDelete;
31314 #endif
31315   if( rc!=SQLCIPHER_OK ){
31316     if( h>=0 ) robust_close(pNew, h, __LINE__);
31317   }else{
31318     pNew->pMethod = pLockingStyle;
31319     OpenCounter(+1);
31320   }
31321   return rc;
31322 }
31323
31324 /*
31325 ** Return the name of a directory in which to put temporary files.
31326 ** If no suitable temporary file directory can be found, return NULL.
31327 */
31328 static const char *unixTempFileDir(void){
31329   static const char *azDirs[] = {
31330      0,
31331      0,
31332      "/var/tmp",
31333      "/usr/tmp",
31334      "/tmp",
31335      0        /* List terminator */
31336   };
31337   unsigned int i;
31338   struct stat buf;
31339   const char *zDir = 0;
31340
31341   azDirs[0] = sqlcipher3_temp_directory;
31342   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
31343   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
31344     if( zDir==0 ) continue;
31345     if( osStat(zDir, &buf) ) continue;
31346     if( !S_ISDIR(buf.st_mode) ) continue;
31347     if( osAccess(zDir, 07) ) continue;
31348     break;
31349   }
31350   return zDir;
31351 }
31352
31353 /*
31354 ** Create a temporary file name in zBuf.  zBuf must be allocated
31355 ** by the calling process and must be big enough to hold at least
31356 ** pVfs->mxPathname bytes.
31357 */
31358 static int unixGetTempname(int nBuf, char *zBuf){
31359   static const unsigned char zChars[] =
31360     "abcdefghijklmnopqrstuvwxyz"
31361     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
31362     "0123456789";
31363   unsigned int i, j;
31364   const char *zDir;
31365
31366   /* It's odd to simulate an io-error here, but really this is just
31367   ** using the io-error infrastructure to test that SQLite handles this
31368   ** function failing. 
31369   */
31370   SimulateIOError( return SQLCIPHER_IOERR );
31371
31372   zDir = unixTempFileDir();
31373   if( zDir==0 ) zDir = ".";
31374
31375   /* Check that the output buffer is large enough for the temporary file 
31376   ** name. If it is not, return SQLCIPHER_ERROR.
31377   */
31378   if( (strlen(zDir) + strlen(SQLCIPHER_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
31379     return SQLCIPHER_ERROR;
31380   }
31381
31382   do{
31383     sqlcipher3_snprintf(nBuf-17, zBuf, "%s/"SQLCIPHER_TEMP_FILE_PREFIX, zDir);
31384     j = (int)strlen(zBuf);
31385     sqlcipher3_randomness(15, &zBuf[j]);
31386     for(i=0; i<15; i++, j++){
31387       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
31388     }
31389     zBuf[j] = 0;
31390   }while( osAccess(zBuf,0)==0 );
31391   return SQLCIPHER_OK;
31392 }
31393
31394 #if SQLCIPHER_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31395 /*
31396 ** Routine to transform a unixFile into a proxy-locking unixFile.
31397 ** Implementation in the proxy-lock division, but used by unixOpen()
31398 ** if SQLCIPHER_PREFER_PROXY_LOCKING is defined.
31399 */
31400 static int proxyTransformUnixFile(unixFile*, const char*);
31401 #endif
31402
31403 /*
31404 ** Search for an unused file descriptor that was opened on the database 
31405 ** file (not a journal or master-journal file) identified by pathname
31406 ** zPath with SQLCIPHER_OPEN_XXX flags matching those passed as the second
31407 ** argument to this function.
31408 **
31409 ** Such a file descriptor may exist if a database connection was closed
31410 ** but the associated file descriptor could not be closed because some
31411 ** other file descriptor open on the same file is holding a file-lock.
31412 ** Refer to comments in the unixClose() function and the lengthy comment
31413 ** describing "Posix Advisory Locking" at the start of this file for 
31414 ** further details. Also, ticket #4018.
31415 **
31416 ** If a suitable file descriptor is found, then it is returned. If no
31417 ** such file descriptor is located, -1 is returned.
31418 */
31419 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
31420   UnixUnusedFd *pUnused = 0;
31421
31422   /* Do not search for an unused file descriptor on vxworks. Not because
31423   ** vxworks would not benefit from the change (it might, we're not sure),
31424   ** but because no way to test it is currently available. It is better 
31425   ** not to risk breaking vxworks support for the sake of such an obscure 
31426   ** feature.  */
31427 #if !OS_VXWORKS
31428   struct stat sStat;                   /* Results of stat() call */
31429
31430   /* A stat() call may fail for various reasons. If this happens, it is
31431   ** almost certain that an open() call on the same path will also fail.
31432   ** For this reason, if an error occurs in the stat() call here, it is
31433   ** ignored and -1 is returned. The caller will try to open a new file
31434   ** descriptor on the same path, fail, and return an error to SQLite.
31435   **
31436   ** Even if a subsequent open() call does succeed, the consequences of
31437   ** not searching for a resusable file descriptor are not dire.  */
31438   if( 0==osStat(zPath, &sStat) ){
31439     unixInodeInfo *pInode;
31440
31441     unixEnterMutex();
31442     pInode = inodeList;
31443     while( pInode && (pInode->fileId.dev!=sStat.st_dev
31444                      || pInode->fileId.ino!=sStat.st_ino) ){
31445        pInode = pInode->pNext;
31446     }
31447     if( pInode ){
31448       UnixUnusedFd **pp;
31449       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
31450       pUnused = *pp;
31451       if( pUnused ){
31452         *pp = pUnused->pNext;
31453       }
31454     }
31455     unixLeaveMutex();
31456   }
31457 #endif    /* if !OS_VXWORKS */
31458   return pUnused;
31459 }
31460
31461 /*
31462 ** This function is called by unixOpen() to determine the unix permissions
31463 ** to create new files with. If no error occurs, then SQLCIPHER_OK is returned
31464 ** and a value suitable for passing as the third argument to open(2) is
31465 ** written to *pMode. If an IO error occurs, an SQLite error code is 
31466 ** returned and the value of *pMode is not modified.
31467 **
31468 ** If the file being opened is a temporary file, it is always created with
31469 ** the octal permissions 0600 (read/writable by owner only). If the file
31470 ** is a database or master journal file, it is created with the permissions 
31471 ** mask SQLCIPHER_DEFAULT_FILE_PERMISSIONS.
31472 **
31473 ** Finally, if the file being opened is a WAL or regular journal file, then 
31474 ** this function queries the file-system for the permissions on the 
31475 ** corresponding database file and sets *pMode to this value. Whenever 
31476 ** possible, WAL and journal files are created using the same permissions 
31477 ** as the associated database file.
31478 **
31479 ** If the SQLCIPHER_ENABLE_8_3_NAMES option is enabled, then the
31480 ** original filename is unavailable.  But 8_3_NAMES is only used for
31481 ** FAT filesystems and permissions do not matter there, so just use
31482 ** the default permissions.
31483 */
31484 static int findCreateFileMode(
31485   const char *zPath,              /* Path of file (possibly) being created */
31486   int flags,                      /* Flags passed as 4th argument to xOpen() */
31487   mode_t *pMode                   /* OUT: Permissions to open file with */
31488 ){
31489   int rc = SQLCIPHER_OK;             /* Return Code */
31490   *pMode = SQLCIPHER_DEFAULT_FILE_PERMISSIONS;
31491   if( flags & (SQLCIPHER_OPEN_WAL|SQLCIPHER_OPEN_MAIN_JOURNAL) ){
31492     char zDb[MAX_PATHNAME+1];     /* Database file path */
31493     int nDb;                      /* Number of valid bytes in zDb */
31494     struct stat sStat;            /* Output of stat() on database file */
31495
31496     /* zPath is a path to a WAL or journal file. The following block derives
31497     ** the path to the associated database file from zPath. This block handles
31498     ** the following naming conventions:
31499     **
31500     **   "<path to db>-journal"
31501     **   "<path to db>-wal"
31502     **   "<path to db>-journalNN"
31503     **   "<path to db>-walNN"
31504     **
31505     ** where NN is a decimal number. The NN naming schemes are 
31506     ** used by the test_multiplex.c module.
31507     */
31508     nDb = sqlcipher3Strlen30(zPath) - 1; 
31509 #ifdef SQLCIPHER_ENABLE_8_3_NAMES
31510     while( nDb>0 && !sqlcipher3Isalnum(zPath[nDb]) ) nDb--;
31511     if( nDb==0 || zPath[nDb]!='-' ) return SQLCIPHER_OK;
31512 #else
31513     while( zPath[nDb]!='-' ){
31514       assert( nDb>0 );
31515       assert( zPath[nDb]!='\n' );
31516       nDb--;
31517     }
31518 #endif
31519     memcpy(zDb, zPath, nDb);
31520     zDb[nDb] = '\0';
31521
31522     if( 0==osStat(zDb, &sStat) ){
31523       *pMode = sStat.st_mode & 0777;
31524     }else{
31525       rc = SQLCIPHER_IOERR_FSTAT;
31526     }
31527   }else if( flags & SQLCIPHER_OPEN_DELETEONCLOSE ){
31528     *pMode = 0600;
31529   }
31530   return rc;
31531 }
31532
31533 /*
31534 ** Open the file zPath.
31535 ** 
31536 ** Previously, the SQLite OS layer used three functions in place of this
31537 ** one:
31538 **
31539 **     sqlcipher3OsOpenReadWrite();
31540 **     sqlcipher3OsOpenReadOnly();
31541 **     sqlcipher3OsOpenExclusive();
31542 **
31543 ** These calls correspond to the following combinations of flags:
31544 **
31545 **     ReadWrite() ->     (READWRITE | CREATE)
31546 **     ReadOnly()  ->     (READONLY) 
31547 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
31548 **
31549 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
31550 ** true, the file was configured to be automatically deleted when the
31551 ** file handle closed. To achieve the same effect using this new 
31552 ** interface, add the DELETEONCLOSE flag to those specified above for 
31553 ** OpenExclusive().
31554 */
31555 static int unixOpen(
31556   sqlcipher3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
31557   const char *zPath,           /* Pathname of file to be opened */
31558   sqlcipher3_file *pFile,         /* The file descriptor to be filled in */
31559   int flags,                   /* Input flags to control the opening */
31560   int *pOutFlags               /* Output flags returned to SQLite core */
31561 ){
31562   unixFile *p = (unixFile *)pFile;
31563   int fd = -1;                   /* File descriptor returned by open() */
31564   int openFlags = 0;             /* Flags to pass to open() */
31565   int eType = flags&0xFFFFFF00;  /* Type of file to open */
31566   int noLock;                    /* True to omit locking primitives */
31567   int rc = SQLCIPHER_OK;            /* Function Return Code */
31568
31569   int isExclusive  = (flags & SQLCIPHER_OPEN_EXCLUSIVE);
31570   int isDelete     = (flags & SQLCIPHER_OPEN_DELETEONCLOSE);
31571   int isCreate     = (flags & SQLCIPHER_OPEN_CREATE);
31572   int isReadonly   = (flags & SQLCIPHER_OPEN_READONLY);
31573   int isReadWrite  = (flags & SQLCIPHER_OPEN_READWRITE);
31574 #if SQLCIPHER_ENABLE_LOCKING_STYLE
31575   int isAutoProxy  = (flags & SQLCIPHER_OPEN_AUTOPROXY);
31576 #endif
31577 #if defined(__APPLE__) || SQLCIPHER_ENABLE_LOCKING_STYLE
31578   struct statfs fsInfo;
31579 #endif
31580
31581   /* If creating a master or main-file journal, this function will open
31582   ** a file-descriptor on the directory too. The first time unixSync()
31583   ** is called the directory file descriptor will be fsync()ed and close()d.
31584   */
31585   int syncDir = (isCreate && (
31586         eType==SQLCIPHER_OPEN_MASTER_JOURNAL 
31587      || eType==SQLCIPHER_OPEN_MAIN_JOURNAL 
31588      || eType==SQLCIPHER_OPEN_WAL
31589   ));
31590
31591   /* If argument zPath is a NULL pointer, this function is required to open
31592   ** a temporary file. Use this buffer to store the file name in.
31593   */
31594   char zTmpname[MAX_PATHNAME+1];
31595   const char *zName = zPath;
31596
31597   /* Check the following statements are true: 
31598   **
31599   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
31600   **   (b) if CREATE is set, then READWRITE must also be set, and
31601   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
31602   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
31603   */
31604   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
31605   assert(isCreate==0 || isReadWrite);
31606   assert(isExclusive==0 || isCreate);
31607   assert(isDelete==0 || isCreate);
31608
31609   /* The main DB, main journal, WAL file and master journal are never 
31610   ** automatically deleted. Nor are they ever temporary files.  */
31611   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MAIN_DB );
31612   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MAIN_JOURNAL );
31613   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MASTER_JOURNAL );
31614   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_WAL );
31615
31616   /* Assert that the upper layer has set one of the "file-type" flags. */
31617   assert( eType==SQLCIPHER_OPEN_MAIN_DB      || eType==SQLCIPHER_OPEN_TEMP_DB 
31618        || eType==SQLCIPHER_OPEN_MAIN_JOURNAL || eType==SQLCIPHER_OPEN_TEMP_JOURNAL 
31619        || eType==SQLCIPHER_OPEN_SUBJOURNAL   || eType==SQLCIPHER_OPEN_MASTER_JOURNAL 
31620        || eType==SQLCIPHER_OPEN_TRANSIENT_DB || eType==SQLCIPHER_OPEN_WAL
31621   );
31622
31623   memset(p, 0, sizeof(unixFile));
31624
31625   if( eType==SQLCIPHER_OPEN_MAIN_DB ){
31626     UnixUnusedFd *pUnused;
31627     pUnused = findReusableFd(zName, flags);
31628     if( pUnused ){
31629       fd = pUnused->fd;
31630     }else{
31631       pUnused = sqlcipher3_malloc(sizeof(*pUnused));
31632       if( !pUnused ){
31633         return SQLCIPHER_NOMEM;
31634       }
31635     }
31636     p->pUnused = pUnused;
31637   }else if( !zName ){
31638     /* If zName is NULL, the upper layer is requesting a temp file. */
31639     assert(isDelete && !syncDir);
31640     rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
31641     if( rc!=SQLCIPHER_OK ){
31642       return rc;
31643     }
31644     zName = zTmpname;
31645   }
31646
31647   /* Determine the value of the flags parameter passed to POSIX function
31648   ** open(). These must be calculated even if open() is not called, as
31649   ** they may be stored as part of the file handle and used by the 
31650   ** 'conch file' locking functions later on.  */
31651   if( isReadonly )  openFlags |= O_RDONLY;
31652   if( isReadWrite ) openFlags |= O_RDWR;
31653   if( isCreate )    openFlags |= O_CREAT;
31654   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
31655   openFlags |= (O_LARGEFILE|O_BINARY);
31656
31657   if( fd<0 ){
31658     mode_t openMode;              /* Permissions to create file with */
31659     rc = findCreateFileMode(zName, flags, &openMode);
31660     if( rc!=SQLCIPHER_OK ){
31661       assert( !p->pUnused );
31662       assert( eType==SQLCIPHER_OPEN_WAL || eType==SQLCIPHER_OPEN_MAIN_JOURNAL );
31663       return rc;
31664     }
31665     fd = robust_open(zName, openFlags, openMode);
31666     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
31667     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
31668       /* Failed to open the file for read/write access. Try read-only. */
31669       flags &= ~(SQLCIPHER_OPEN_READWRITE|SQLCIPHER_OPEN_CREATE);
31670       openFlags &= ~(O_RDWR|O_CREAT);
31671       flags |= SQLCIPHER_OPEN_READONLY;
31672       openFlags |= O_RDONLY;
31673       isReadonly = 1;
31674       fd = robust_open(zName, openFlags, openMode);
31675     }
31676     if( fd<0 ){
31677       rc = unixLogError(SQLCIPHER_CANTOPEN_BKPT, "open", zName);
31678       goto open_finished;
31679     }
31680   }
31681   assert( fd>=0 );
31682   if( pOutFlags ){
31683     *pOutFlags = flags;
31684   }
31685
31686   if( p->pUnused ){
31687     p->pUnused->fd = fd;
31688     p->pUnused->flags = flags;
31689   }
31690
31691   if( isDelete ){
31692 #if OS_VXWORKS
31693     zPath = zName;
31694 #else
31695     osUnlink(zName);
31696 #endif
31697   }
31698 #if SQLCIPHER_ENABLE_LOCKING_STYLE
31699   else{
31700     p->openFlags = openFlags;
31701   }
31702 #endif
31703
31704 #ifdef FD_CLOEXEC
31705   osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
31706 #endif
31707
31708   noLock = eType!=SQLCIPHER_OPEN_MAIN_DB;
31709
31710   
31711 #if defined(__APPLE__) || SQLCIPHER_ENABLE_LOCKING_STYLE
31712   if( fstatfs(fd, &fsInfo) == -1 ){
31713     ((unixFile*)pFile)->lastErrno = errno;
31714     robust_close(p, fd, __LINE__);
31715     return SQLCIPHER_IOERR_ACCESS;
31716   }
31717   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
31718     ((unixFile*)pFile)->fsFlags |= SQLCIPHER_FSFLAGS_IS_MSDOS;
31719   }
31720 #endif
31721   
31722 #if SQLCIPHER_ENABLE_LOCKING_STYLE
31723 #if SQLCIPHER_PREFER_PROXY_LOCKING
31724   isAutoProxy = 1;
31725 #endif
31726   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
31727     char *envforce = getenv("SQLCIPHER_FORCE_PROXY_LOCKING");
31728     int useProxy = 0;
31729
31730     /* SQLCIPHER_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
31731     ** never use proxy, NULL means use proxy for non-local files only.  */
31732     if( envforce!=NULL ){
31733       useProxy = atoi(envforce)>0;
31734     }else{
31735       if( statfs(zPath, &fsInfo) == -1 ){
31736         /* In theory, the close(fd) call is sub-optimal. If the file opened
31737         ** with fd is a database file, and there are other connections open
31738         ** on that file that are currently holding advisory locks on it,
31739         ** then the call to close() will cancel those locks. In practice,
31740         ** we're assuming that statfs() doesn't fail very often. At least
31741         ** not while other file descriptors opened by the same process on
31742         ** the same file are working.  */
31743         p->lastErrno = errno;
31744         robust_close(p, fd, __LINE__);
31745         rc = SQLCIPHER_IOERR_ACCESS;
31746         goto open_finished;
31747       }
31748       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
31749     }
31750     if( useProxy ){
31751       rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
31752                           isDelete, isReadonly);
31753       if( rc==SQLCIPHER_OK ){
31754         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
31755         if( rc!=SQLCIPHER_OK ){
31756           /* Use unixClose to clean up the resources added in fillInUnixFile 
31757           ** and clear all the structure's references.  Specifically, 
31758           ** pFile->pMethods will be NULL so sqlcipher3OsClose will be a no-op 
31759           */
31760           unixClose(pFile);
31761           return rc;
31762         }
31763       }
31764       goto open_finished;
31765     }
31766   }
31767 #endif
31768   
31769   rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
31770                       isDelete, isReadonly);
31771 open_finished:
31772   if( rc!=SQLCIPHER_OK ){
31773     sqlcipher3_free(p->pUnused);
31774   }
31775   return rc;
31776 }
31777
31778
31779 /*
31780 ** Delete the file at zPath. If the dirSync argument is true, fsync()
31781 ** the directory after deleting the file.
31782 */
31783 static int unixDelete(
31784   sqlcipher3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
31785   const char *zPath,        /* Name of file to be deleted */
31786   int dirSync               /* If true, fsync() directory after deleting file */
31787 ){
31788   int rc = SQLCIPHER_OK;
31789   UNUSED_PARAMETER(NotUsed);
31790   SimulateIOError(return SQLCIPHER_IOERR_DELETE);
31791   if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
31792     return unixLogError(SQLCIPHER_IOERR_DELETE, "unlink", zPath);
31793   }
31794 #ifndef SQLCIPHER_DISABLE_DIRSYNC
31795   if( dirSync ){
31796     int fd;
31797     rc = osOpenDirectory(zPath, &fd);
31798     if( rc==SQLCIPHER_OK ){
31799 #if OS_VXWORKS
31800       if( fsync(fd)==-1 )
31801 #else
31802       if( fsync(fd) )
31803 #endif
31804       {
31805         rc = unixLogError(SQLCIPHER_IOERR_DIR_FSYNC, "fsync", zPath);
31806       }
31807       robust_close(0, fd, __LINE__);
31808     }else if( rc==SQLCIPHER_CANTOPEN ){
31809       rc = SQLCIPHER_OK;
31810     }
31811   }
31812 #endif
31813   return rc;
31814 }
31815
31816 /*
31817 ** Test the existance of or access permissions of file zPath. The
31818 ** test performed depends on the value of flags:
31819 **
31820 **     SQLCIPHER_ACCESS_EXISTS: Return 1 if the file exists
31821 **     SQLCIPHER_ACCESS_READWRITE: Return 1 if the file is read and writable.
31822 **     SQLCIPHER_ACCESS_READONLY: Return 1 if the file is readable.
31823 **
31824 ** Otherwise return 0.
31825 */
31826 static int unixAccess(
31827   sqlcipher3_vfs *NotUsed,   /* The VFS containing this xAccess method */
31828   const char *zPath,      /* Path of the file to examine */
31829   int flags,              /* What do we want to learn about the zPath file? */
31830   int *pResOut            /* Write result boolean here */
31831 ){
31832   int amode = 0;
31833   UNUSED_PARAMETER(NotUsed);
31834   SimulateIOError( return SQLCIPHER_IOERR_ACCESS; );
31835   switch( flags ){
31836     case SQLCIPHER_ACCESS_EXISTS:
31837       amode = F_OK;
31838       break;
31839     case SQLCIPHER_ACCESS_READWRITE:
31840       amode = W_OK|R_OK;
31841       break;
31842     case SQLCIPHER_ACCESS_READ:
31843       amode = R_OK;
31844       break;
31845
31846     default:
31847       assert(!"Invalid flags argument");
31848   }
31849   *pResOut = (osAccess(zPath, amode)==0);
31850   if( flags==SQLCIPHER_ACCESS_EXISTS && *pResOut ){
31851     struct stat buf;
31852     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
31853       *pResOut = 0;
31854     }
31855   }
31856   return SQLCIPHER_OK;
31857 }
31858
31859
31860 /*
31861 ** Turn a relative pathname into a full pathname. The relative path
31862 ** is stored as a nul-terminated string in the buffer pointed to by
31863 ** zPath. 
31864 **
31865 ** zOut points to a buffer of at least sqlcipher3_vfs.mxPathname bytes 
31866 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
31867 ** this buffer before returning.
31868 */
31869 static int unixFullPathname(
31870   sqlcipher3_vfs *pVfs,            /* Pointer to vfs object */
31871   const char *zPath,            /* Possibly relative input path */
31872   int nOut,                     /* Size of output buffer in bytes */
31873   char *zOut                    /* Output buffer */
31874 ){
31875
31876   /* It's odd to simulate an io-error here, but really this is just
31877   ** using the io-error infrastructure to test that SQLite handles this
31878   ** function failing. This function could fail if, for example, the
31879   ** current working directory has been unlinked.
31880   */
31881   SimulateIOError( return SQLCIPHER_ERROR );
31882
31883   assert( pVfs->mxPathname==MAX_PATHNAME );
31884   UNUSED_PARAMETER(pVfs);
31885
31886   zOut[nOut-1] = '\0';
31887   if( zPath[0]=='/' ){
31888     sqlcipher3_snprintf(nOut, zOut, "%s", zPath);
31889   }else{
31890     int nCwd;
31891     if( osGetcwd(zOut, nOut-1)==0 ){
31892       return unixLogError(SQLCIPHER_CANTOPEN_BKPT, "getcwd", zPath);
31893     }
31894     nCwd = (int)strlen(zOut);
31895     sqlcipher3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
31896   }
31897   return SQLCIPHER_OK;
31898 }
31899
31900
31901 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
31902 /*
31903 ** Interfaces for opening a shared library, finding entry points
31904 ** within the shared library, and closing the shared library.
31905 */
31906 #include <dlfcn.h>
31907 static void *unixDlOpen(sqlcipher3_vfs *NotUsed, const char *zFilename){
31908   UNUSED_PARAMETER(NotUsed);
31909   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
31910 }
31911
31912 /*
31913 ** SQLite calls this function immediately after a call to unixDlSym() or
31914 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
31915 ** message is available, it is written to zBufOut. If no error message
31916 ** is available, zBufOut is left unmodified and SQLite uses a default
31917 ** error message.
31918 */
31919 static void unixDlError(sqlcipher3_vfs *NotUsed, int nBuf, char *zBufOut){
31920   const char *zErr;
31921   UNUSED_PARAMETER(NotUsed);
31922   unixEnterMutex();
31923   zErr = dlerror();
31924   if( zErr ){
31925     sqlcipher3_snprintf(nBuf, zBufOut, "%s", zErr);
31926   }
31927   unixLeaveMutex();
31928 }
31929 static void (*unixDlSym(sqlcipher3_vfs *NotUsed, void *p, const char*zSym))(void){
31930   /* 
31931   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
31932   ** cast into a pointer to a function.  And yet the library dlsym() routine
31933   ** returns a void* which is really a pointer to a function.  So how do we
31934   ** use dlsym() with -pedantic-errors?
31935   **
31936   ** Variable x below is defined to be a pointer to a function taking
31937   ** parameters void* and const char* and returning a pointer to a function.
31938   ** We initialize x by assigning it a pointer to the dlsym() function.
31939   ** (That assignment requires a cast.)  Then we call the function that
31940   ** x points to.  
31941   **
31942   ** This work-around is unlikely to work correctly on any system where
31943   ** you really cannot cast a function pointer into void*.  But then, on the
31944   ** other hand, dlsym() will not work on such a system either, so we have
31945   ** not really lost anything.
31946   */
31947   void (*(*x)(void*,const char*))(void);
31948   UNUSED_PARAMETER(NotUsed);
31949   x = (void(*(*)(void*,const char*))(void))dlsym;
31950   return (*x)(p, zSym);
31951 }
31952 static void unixDlClose(sqlcipher3_vfs *NotUsed, void *pHandle){
31953   UNUSED_PARAMETER(NotUsed);
31954   dlclose(pHandle);
31955 }
31956 #else /* if SQLCIPHER_OMIT_LOAD_EXTENSION is defined: */
31957   #define unixDlOpen  0
31958   #define unixDlError 0
31959   #define unixDlSym   0
31960   #define unixDlClose 0
31961 #endif
31962
31963 /*
31964 ** Write nBuf bytes of random data to the supplied buffer zBuf.
31965 */
31966 static int unixRandomness(sqlcipher3_vfs *NotUsed, int nBuf, char *zBuf){
31967   UNUSED_PARAMETER(NotUsed);
31968   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
31969
31970   /* We have to initialize zBuf to prevent valgrind from reporting
31971   ** errors.  The reports issued by valgrind are incorrect - we would
31972   ** prefer that the randomness be increased by making use of the
31973   ** uninitialized space in zBuf - but valgrind errors tend to worry
31974   ** some users.  Rather than argue, it seems easier just to initialize
31975   ** the whole array and silence valgrind, even if that means less randomness
31976   ** in the random seed.
31977   **
31978   ** When testing, initializing zBuf[] to zero is all we do.  That means
31979   ** that we always use the same random number sequence.  This makes the
31980   ** tests repeatable.
31981   */
31982   memset(zBuf, 0, nBuf);
31983 #if !defined(SQLCIPHER_TEST)
31984   {
31985     int pid, fd;
31986     fd = robust_open("/dev/urandom", O_RDONLY, 0);
31987     if( fd<0 ){
31988       time_t t;
31989       time(&t);
31990       memcpy(zBuf, &t, sizeof(t));
31991       pid = getpid();
31992       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
31993       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
31994       nBuf = sizeof(t) + sizeof(pid);
31995     }else{
31996       do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
31997       robust_close(0, fd, __LINE__);
31998     }
31999   }
32000 #endif
32001   return nBuf;
32002 }
32003
32004
32005 /*
32006 ** Sleep for a little while.  Return the amount of time slept.
32007 ** The argument is the number of microseconds we want to sleep.
32008 ** The return value is the number of microseconds of sleep actually
32009 ** requested from the underlying operating system, a number which
32010 ** might be greater than or equal to the argument, but not less
32011 ** than the argument.
32012 */
32013 static int unixSleep(sqlcipher3_vfs *NotUsed, int microseconds){
32014 #if OS_VXWORKS
32015   struct timespec sp;
32016
32017   sp.tv_sec = microseconds / 1000000;
32018   sp.tv_nsec = (microseconds % 1000000) * 1000;
32019   nanosleep(&sp, NULL);
32020   UNUSED_PARAMETER(NotUsed);
32021   return microseconds;
32022 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
32023   usleep(microseconds);
32024   UNUSED_PARAMETER(NotUsed);
32025   return microseconds;
32026 #else
32027   int seconds = (microseconds+999999)/1000000;
32028   sleep(seconds);
32029   UNUSED_PARAMETER(NotUsed);
32030   return seconds*1000000;
32031 #endif
32032 }
32033
32034 /*
32035 ** The following variable, if set to a non-zero value, is interpreted as
32036 ** the number of seconds since 1970 and is used to set the result of
32037 ** sqlcipher3OsCurrentTime() during testing.
32038 */
32039 #ifdef SQLCIPHER_TEST
32040 SQLCIPHER_API int sqlcipher3_current_time = 0;  /* Fake system time in seconds since 1970. */
32041 #endif
32042
32043 /*
32044 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
32045 ** the current time and date as a Julian Day number times 86_400_000.  In
32046 ** other words, write into *piNow the number of milliseconds since the Julian
32047 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
32048 ** proleptic Gregorian calendar.
32049 **
32050 ** On success, return SQLCIPHER_OK.  Return SQLCIPHER_ERROR if the time and date 
32051 ** cannot be found.
32052 */
32053 static int unixCurrentTimeInt64(sqlcipher3_vfs *NotUsed, sqlcipher3_int64 *piNow){
32054   static const sqlcipher3_int64 unixEpoch = 24405875*(sqlcipher3_int64)8640000;
32055   int rc = SQLCIPHER_OK;
32056 #if defined(NO_GETTOD)
32057   time_t t;
32058   time(&t);
32059   *piNow = ((sqlcipher3_int64)t)*1000 + unixEpoch;
32060 #elif OS_VXWORKS
32061   struct timespec sNow;
32062   clock_gettime(CLOCK_REALTIME, &sNow);
32063   *piNow = unixEpoch + 1000*(sqlcipher3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
32064 #else
32065   struct timeval sNow;
32066   if( gettimeofday(&sNow, 0)==0 ){
32067     *piNow = unixEpoch + 1000*(sqlcipher3_int64)sNow.tv_sec + sNow.tv_usec/1000;
32068   }else{
32069     rc = SQLCIPHER_ERROR;
32070   }
32071 #endif
32072
32073 #ifdef SQLCIPHER_TEST
32074   if( sqlcipher3_current_time ){
32075     *piNow = 1000*(sqlcipher3_int64)sqlcipher3_current_time + unixEpoch;
32076   }
32077 #endif
32078   UNUSED_PARAMETER(NotUsed);
32079   return rc;
32080 }
32081
32082 /*
32083 ** Find the current time (in Universal Coordinated Time).  Write the
32084 ** current time and date as a Julian Day number into *prNow and
32085 ** return 0.  Return 1 if the time and date cannot be found.
32086 */
32087 static int unixCurrentTime(sqlcipher3_vfs *NotUsed, double *prNow){
32088   sqlcipher3_int64 i = 0;
32089   int rc;
32090   UNUSED_PARAMETER(NotUsed);
32091   rc = unixCurrentTimeInt64(0, &i);
32092   *prNow = i/86400000.0;
32093   return rc;
32094 }
32095
32096 /*
32097 ** We added the xGetLastError() method with the intention of providing
32098 ** better low-level error messages when operating-system problems come up
32099 ** during SQLite operation.  But so far, none of that has been implemented
32100 ** in the core.  So this routine is never called.  For now, it is merely
32101 ** a place-holder.
32102 */
32103 static int unixGetLastError(sqlcipher3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
32104   UNUSED_PARAMETER(NotUsed);
32105   UNUSED_PARAMETER(NotUsed2);
32106   UNUSED_PARAMETER(NotUsed3);
32107   return 0;
32108 }
32109
32110
32111 /*
32112 ************************ End of sqlcipher3_vfs methods ***************************
32113 ******************************************************************************/
32114
32115 /******************************************************************************
32116 ************************** Begin Proxy Locking ********************************
32117 **
32118 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
32119 ** other locking methods on secondary lock files.  Proxy locking is a
32120 ** meta-layer over top of the primitive locking implemented above.  For
32121 ** this reason, the division that implements of proxy locking is deferred
32122 ** until late in the file (here) after all of the other I/O methods have
32123 ** been defined - so that the primitive locking methods are available
32124 ** as services to help with the implementation of proxy locking.
32125 **
32126 ****
32127 **
32128 ** The default locking schemes in SQLite use byte-range locks on the
32129 ** database file to coordinate safe, concurrent access by multiple readers
32130 ** and writers [http://sqlcipher.org/lockingv3.html].  The five file locking
32131 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
32132 ** as POSIX read & write locks over fixed set of locations (via fsctl),
32133 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
32134 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
32135 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
32136 ** address in the shared range is taken for a SHARED lock, the entire
32137 ** shared range is taken for an EXCLUSIVE lock):
32138 **
32139 **      PENDING_BYTE        0x40000000                  
32140 **      RESERVED_BYTE       0x40000001
32141 **      SHARED_RANGE        0x40000002 -> 0x40000200
32142 **
32143 ** This works well on the local file system, but shows a nearly 100x
32144 ** slowdown in read performance on AFP because the AFP client disables
32145 ** the read cache when byte-range locks are present.  Enabling the read
32146 ** cache exposes a cache coherency problem that is present on all OS X
32147 ** supported network file systems.  NFS and AFP both observe the
32148 ** close-to-open semantics for ensuring cache coherency
32149 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
32150 ** address the requirements for concurrent database access by multiple
32151 ** readers and writers
32152 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
32153 **
32154 ** To address the performance and cache coherency issues, proxy file locking
32155 ** changes the way database access is controlled by limiting access to a
32156 ** single host at a time and moving file locks off of the database file
32157 ** and onto a proxy file on the local file system.  
32158 **
32159 **
32160 ** Using proxy locks
32161 ** -----------------
32162 **
32163 ** C APIs
32164 **
32165 **  sqlcipher3_file_control(db, dbname, SQLCIPHER_SET_LOCKPROXYFILE,
32166 **                       <proxy_path> | ":auto:");
32167 **  sqlcipher3_file_control(db, dbname, SQLCIPHER_GET_LOCKPROXYFILE, &<proxy_path>);
32168 **
32169 **
32170 ** SQL pragmas
32171 **
32172 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
32173 **  PRAGMA [database.]lock_proxy_file
32174 **
32175 ** Specifying ":auto:" means that if there is a conch file with a matching
32176 ** host ID in it, the proxy path in the conch file will be used, otherwise
32177 ** a proxy path based on the user's temp dir
32178 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
32179 ** actual proxy file name is generated from the name and path of the
32180 ** database file.  For example:
32181 **
32182 **       For database path "/Users/me/foo.db" 
32183 **       The lock path will be "<tmpdir>/sqlcipherplocks/_Users_me_foo.db:auto:")
32184 **
32185 ** Once a lock proxy is configured for a database connection, it can not
32186 ** be removed, however it may be switched to a different proxy path via
32187 ** the above APIs (assuming the conch file is not being held by another
32188 ** connection or process). 
32189 **
32190 **
32191 ** How proxy locking works
32192 ** -----------------------
32193 **
32194 ** Proxy file locking relies primarily on two new supporting files: 
32195 **
32196 **   *  conch file to limit access to the database file to a single host
32197 **      at a time
32198 **
32199 **   *  proxy file to act as a proxy for the advisory locks normally
32200 **      taken on the database
32201 **
32202 ** The conch file - to use a proxy file, sqlcipher must first "hold the conch"
32203 ** by taking an sqlcipher-style shared lock on the conch file, reading the
32204 ** contents and comparing the host's unique host ID (see below) and lock
32205 ** proxy path against the values stored in the conch.  The conch file is
32206 ** stored in the same directory as the database file and the file name
32207 ** is patterned after the database file name as ".<databasename>-conch".
32208 ** If the conch file does not exist, or it's contents do not match the
32209 ** host ID and/or proxy path, then the lock is escalated to an exclusive
32210 ** lock and the conch file contents is updated with the host ID and proxy
32211 ** path and the lock is downgraded to a shared lock again.  If the conch
32212 ** is held by another process (with a shared lock), the exclusive lock
32213 ** will fail and SQLCIPHER_BUSY is returned.
32214 **
32215 ** The proxy file - a single-byte file used for all advisory file locks
32216 ** normally taken on the database file.   This allows for safe sharing
32217 ** of the database file for multiple readers and writers on the same
32218 ** host (the conch ensures that they all use the same local lock file).
32219 **
32220 ** Requesting the lock proxy does not immediately take the conch, it is
32221 ** only taken when the first request to lock database file is made.  
32222 ** This matches the semantics of the traditional locking behavior, where
32223 ** opening a connection to a database file does not take a lock on it.
32224 ** The shared lock and an open file descriptor are maintained until 
32225 ** the connection to the database is closed. 
32226 **
32227 ** The proxy file and the lock file are never deleted so they only need
32228 ** to be created the first time they are used.
32229 **
32230 ** Configuration options
32231 ** ---------------------
32232 **
32233 **  SQLCIPHER_PREFER_PROXY_LOCKING
32234 **
32235 **       Database files accessed on non-local file systems are
32236 **       automatically configured for proxy locking, lock files are
32237 **       named automatically using the same logic as
32238 **       PRAGMA lock_proxy_file=":auto:"
32239 **    
32240 **  SQLCIPHER_PROXY_DEBUG
32241 **
32242 **       Enables the logging of error messages during host id file
32243 **       retrieval and creation
32244 **
32245 **  LOCKPROXYDIR
32246 **
32247 **       Overrides the default directory used for lock proxy files that
32248 **       are named automatically via the ":auto:" setting
32249 **
32250 **  SQLCIPHER_DEFAULT_PROXYDIR_PERMISSIONS
32251 **
32252 **       Permissions to use when creating a directory for storing the
32253 **       lock proxy files, only used when LOCKPROXYDIR is not set.
32254 **    
32255 **    
32256 ** As mentioned above, when compiled with SQLCIPHER_PREFER_PROXY_LOCKING,
32257 ** setting the environment variable SQLCIPHER_FORCE_PROXY_LOCKING to 1 will
32258 ** force proxy locking to be used for every database file opened, and 0
32259 ** will force automatic proxy locking to be disabled for all database
32260 ** files (explicity calling the SQLCIPHER_SET_LOCKPROXYFILE pragma or
32261 ** sqlcipher_file_control API is not affected by SQLCIPHER_FORCE_PROXY_LOCKING).
32262 */
32263
32264 /*
32265 ** Proxy locking is only available on MacOSX 
32266 */
32267 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
32268
32269 /*
32270 ** The proxyLockingContext has the path and file structures for the remote 
32271 ** and local proxy files in it
32272 */
32273 typedef struct proxyLockingContext proxyLockingContext;
32274 struct proxyLockingContext {
32275   unixFile *conchFile;         /* Open conch file */
32276   char *conchFilePath;         /* Name of the conch file */
32277   unixFile *lockProxy;         /* Open proxy lock file */
32278   char *lockProxyPath;         /* Name of the proxy lock file */
32279   char *dbPath;                /* Name of the open file */
32280   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
32281   void *oldLockingContext;     /* Original lockingcontext to restore on close */
32282   sqlcipher3_io_methods const *pOldMethod;     /* Original I/O methods for close */
32283 };
32284
32285 /* 
32286 ** The proxy lock file path for the database at dbPath is written into lPath, 
32287 ** which must point to valid, writable memory large enough for a maxLen length
32288 ** file path. 
32289 */
32290 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
32291   int len;
32292   int dbLen;
32293   int i;
32294
32295 #ifdef LOCKPROXYDIR
32296   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
32297 #else
32298 # ifdef _CS_DARWIN_USER_TEMP_DIR
32299   {
32300     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
32301       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
32302                lPath, errno, getpid()));
32303       return SQLCIPHER_IOERR_LOCK;
32304     }
32305     len = strlcat(lPath, "sqlcipherplocks", maxLen);    
32306   }
32307 # else
32308   len = strlcpy(lPath, "/tmp/", maxLen);
32309 # endif
32310 #endif
32311
32312   if( lPath[len-1]!='/' ){
32313     len = strlcat(lPath, "/", maxLen);
32314   }
32315   
32316   /* transform the db path to a unique cache name */
32317   dbLen = (int)strlen(dbPath);
32318   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
32319     char c = dbPath[i];
32320     lPath[i+len] = (c=='/')?'_':c;
32321   }
32322   lPath[i+len]='\0';
32323   strlcat(lPath, ":auto:", maxLen);
32324   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
32325   return SQLCIPHER_OK;
32326 }
32327
32328 /* 
32329  ** Creates the lock file and any missing directories in lockPath
32330  */
32331 static int proxyCreateLockPath(const char *lockPath){
32332   int i, len;
32333   char buf[MAXPATHLEN];
32334   int start = 0;
32335   
32336   assert(lockPath!=NULL);
32337   /* try to create all the intermediate directories */
32338   len = (int)strlen(lockPath);
32339   buf[0] = lockPath[0];
32340   for( i=1; i<len; i++ ){
32341     if( lockPath[i] == '/' && (i - start > 0) ){
32342       /* only mkdir if leaf dir != "." or "/" or ".." */
32343       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
32344          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
32345         buf[i]='\0';
32346         if( mkdir(buf, SQLCIPHER_DEFAULT_PROXYDIR_PERMISSIONS) ){
32347           int err=errno;
32348           if( err!=EEXIST ) {
32349             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
32350                      "'%s' proxy lock path=%s pid=%d\n",
32351                      buf, strerror(err), lockPath, getpid()));
32352             return err;
32353           }
32354         }
32355       }
32356       start=i+1;
32357     }
32358     buf[i] = lockPath[i];
32359   }
32360   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
32361   return 0;
32362 }
32363
32364 /*
32365 ** Create a new VFS file descriptor (stored in memory obtained from
32366 ** sqlcipher3_malloc) and open the file named "path" in the file descriptor.
32367 **
32368 ** The caller is responsible not only for closing the file descriptor
32369 ** but also for freeing the memory associated with the file descriptor.
32370 */
32371 static int proxyCreateUnixFile(
32372     const char *path,        /* path for the new unixFile */
32373     unixFile **ppFile,       /* unixFile created and returned by ref */
32374     int islockfile           /* if non zero missing dirs will be created */
32375 ) {
32376   int fd = -1;
32377   unixFile *pNew;
32378   int rc = SQLCIPHER_OK;
32379   int openFlags = O_RDWR | O_CREAT;
32380   sqlcipher3_vfs dummyVfs;
32381   int terrno = 0;
32382   UnixUnusedFd *pUnused = NULL;
32383
32384   /* 1. first try to open/create the file
32385   ** 2. if that fails, and this is a lock file (not-conch), try creating
32386   ** the parent directories and then try again.
32387   ** 3. if that fails, try to open the file read-only
32388   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
32389   */
32390   pUnused = findReusableFd(path, openFlags);
32391   if( pUnused ){
32392     fd = pUnused->fd;
32393   }else{
32394     pUnused = sqlcipher3_malloc(sizeof(*pUnused));
32395     if( !pUnused ){
32396       return SQLCIPHER_NOMEM;
32397     }
32398   }
32399   if( fd<0 ){
32400     fd = robust_open(path, openFlags, SQLCIPHER_DEFAULT_FILE_PERMISSIONS);
32401     terrno = errno;
32402     if( fd<0 && errno==ENOENT && islockfile ){
32403       if( proxyCreateLockPath(path) == SQLCIPHER_OK ){
32404         fd = robust_open(path, openFlags, SQLCIPHER_DEFAULT_FILE_PERMISSIONS);
32405       }
32406     }
32407   }
32408   if( fd<0 ){
32409     openFlags = O_RDONLY;
32410     fd = robust_open(path, openFlags, SQLCIPHER_DEFAULT_FILE_PERMISSIONS);
32411     terrno = errno;
32412   }
32413   if( fd<0 ){
32414     if( islockfile ){
32415       return SQLCIPHER_BUSY;
32416     }
32417     switch (terrno) {
32418       case EACCES:
32419         return SQLCIPHER_PERM;
32420       case EIO: 
32421         return SQLCIPHER_IOERR_LOCK; /* even though it is the conch */
32422       default:
32423         return SQLCIPHER_CANTOPEN_BKPT;
32424     }
32425   }
32426   
32427   pNew = (unixFile *)sqlcipher3_malloc(sizeof(*pNew));
32428   if( pNew==NULL ){
32429     rc = SQLCIPHER_NOMEM;
32430     goto end_create_proxy;
32431   }
32432   memset(pNew, 0, sizeof(unixFile));
32433   pNew->openFlags = openFlags;
32434   memset(&dummyVfs, 0, sizeof(dummyVfs));
32435   dummyVfs.pAppData = (void*)&autolockIoFinder;
32436   dummyVfs.zName = "dummy";
32437   pUnused->fd = fd;
32438   pUnused->flags = openFlags;
32439   pNew->pUnused = pUnused;
32440   
32441   rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlcipher3_file*)pNew, path, 0, 0, 0);
32442   if( rc==SQLCIPHER_OK ){
32443     *ppFile = pNew;
32444     return SQLCIPHER_OK;
32445   }
32446 end_create_proxy:    
32447   robust_close(pNew, fd, __LINE__);
32448   sqlcipher3_free(pNew);
32449   sqlcipher3_free(pUnused);
32450   return rc;
32451 }
32452
32453 #ifdef SQLCIPHER_TEST
32454 /* simulate multiple hosts by creating unique hostid file paths */
32455 SQLCIPHER_API int sqlcipher3_hostid_num = 0;
32456 #endif
32457
32458 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
32459
32460 /* Not always defined in the headers as it ought to be */
32461 extern int gethostuuid(uuid_t id, const struct timespec *wait);
32462
32463 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
32464 ** bytes of writable memory.
32465 */
32466 static int proxyGetHostID(unsigned char *pHostID, int *pError){
32467   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
32468   memset(pHostID, 0, PROXY_HOSTIDLEN);
32469 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
32470                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
32471   {
32472     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
32473     if( gethostuuid(pHostID, &timeout) ){
32474       int err = errno;
32475       if( pError ){
32476         *pError = err;
32477       }
32478       return SQLCIPHER_IOERR;
32479     }
32480   }
32481 #else
32482   UNUSED_PARAMETER(pError);
32483 #endif
32484 #ifdef SQLCIPHER_TEST
32485   /* simulate multiple hosts by creating unique hostid file paths */
32486   if( sqlcipher3_hostid_num != 0){
32487     pHostID[0] = (char)(pHostID[0] + (char)(sqlcipher3_hostid_num & 0xFF));
32488   }
32489 #endif
32490   
32491   return SQLCIPHER_OK;
32492 }
32493
32494 /* The conch file contains the header, host id and lock file path
32495  */
32496 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
32497 #define PROXY_HEADERLEN    1   /* conch file header length */
32498 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
32499 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
32500
32501 /* 
32502 ** Takes an open conch file, copies the contents to a new path and then moves 
32503 ** it back.  The newly created file's file descriptor is assigned to the
32504 ** conch file structure and finally the original conch file descriptor is 
32505 ** closed.  Returns zero if successful.
32506 */
32507 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
32508   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
32509   unixFile *conchFile = pCtx->conchFile;
32510   char tPath[MAXPATHLEN];
32511   char buf[PROXY_MAXCONCHLEN];
32512   char *cPath = pCtx->conchFilePath;
32513   size_t readLen = 0;
32514   size_t pathLen = 0;
32515   char errmsg[64] = "";
32516   int fd = -1;
32517   int rc = -1;
32518   UNUSED_PARAMETER(myHostID);
32519
32520   /* create a new path by replace the trailing '-conch' with '-break' */
32521   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
32522   if( pathLen>MAXPATHLEN || pathLen<6 || 
32523      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
32524     sqlcipher3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
32525     goto end_breaklock;
32526   }
32527   /* read the conch content */
32528   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
32529   if( readLen<PROXY_PATHINDEX ){
32530     sqlcipher3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
32531     goto end_breaklock;
32532   }
32533   /* write it out to the temporary break file */
32534   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
32535                    SQLCIPHER_DEFAULT_FILE_PERMISSIONS);
32536   if( fd<0 ){
32537     sqlcipher3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
32538     goto end_breaklock;
32539   }
32540   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
32541     sqlcipher3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
32542     goto end_breaklock;
32543   }
32544   if( rename(tPath, cPath) ){
32545     sqlcipher3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
32546     goto end_breaklock;
32547   }
32548   rc = 0;
32549   fprintf(stderr, "broke stale lock on %s\n", cPath);
32550   robust_close(pFile, conchFile->h, __LINE__);
32551   conchFile->h = fd;
32552   conchFile->openFlags = O_RDWR | O_CREAT;
32553
32554 end_breaklock:
32555   if( rc ){
32556     if( fd>=0 ){
32557       osUnlink(tPath);
32558       robust_close(pFile, fd, __LINE__);
32559     }
32560     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
32561   }
32562   return rc;
32563 }
32564
32565 /* Take the requested lock on the conch file and break a stale lock if the 
32566 ** host id matches.
32567 */
32568 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
32569   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
32570   unixFile *conchFile = pCtx->conchFile;
32571   int rc = SQLCIPHER_OK;
32572   int nTries = 0;
32573   struct timespec conchModTime;
32574   
32575   memset(&conchModTime, 0, sizeof(conchModTime));
32576   do {
32577     rc = conchFile->pMethod->xLock((sqlcipher3_file*)conchFile, lockType);
32578     nTries ++;
32579     if( rc==SQLCIPHER_BUSY ){
32580       /* If the lock failed (busy):
32581        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
32582        * 2nd try: fail if the mod time changed or host id is different, wait 
32583        *           10 sec and try again
32584        * 3rd try: break the lock unless the mod time has changed.
32585        */
32586       struct stat buf;
32587       if( osFstat(conchFile->h, &buf) ){
32588         pFile->lastErrno = errno;
32589         return SQLCIPHER_IOERR_LOCK;
32590       }
32591       
32592       if( nTries==1 ){
32593         conchModTime = buf.st_mtimespec;
32594         usleep(500000); /* wait 0.5 sec and try the lock again*/
32595         continue;  
32596       }
32597
32598       assert( nTries>1 );
32599       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
32600          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
32601         return SQLCIPHER_BUSY;
32602       }
32603       
32604       if( nTries==2 ){  
32605         char tBuf[PROXY_MAXCONCHLEN];
32606         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
32607         if( len<0 ){
32608           pFile->lastErrno = errno;
32609           return SQLCIPHER_IOERR_LOCK;
32610         }
32611         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
32612           /* don't break the lock if the host id doesn't match */
32613           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
32614             return SQLCIPHER_BUSY;
32615           }
32616         }else{
32617           /* don't break the lock on short read or a version mismatch */
32618           return SQLCIPHER_BUSY;
32619         }
32620         usleep(10000000); /* wait 10 sec and try the lock again */
32621         continue; 
32622       }
32623       
32624       assert( nTries==3 );
32625       if( 0==proxyBreakConchLock(pFile, myHostID) ){
32626         rc = SQLCIPHER_OK;
32627         if( lockType==EXCLUSIVE_LOCK ){
32628           rc = conchFile->pMethod->xLock((sqlcipher3_file*)conchFile, SHARED_LOCK);          
32629         }
32630         if( !rc ){
32631           rc = conchFile->pMethod->xLock((sqlcipher3_file*)conchFile, lockType);
32632         }
32633       }
32634     }
32635   } while( rc==SQLCIPHER_BUSY && nTries<3 );
32636   
32637   return rc;
32638 }
32639
32640 /* Takes the conch by taking a shared lock and read the contents conch, if 
32641 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
32642 ** lockPath means that the lockPath in the conch file will be used if the 
32643 ** host IDs match, or a new lock path will be generated automatically 
32644 ** and written to the conch file.
32645 */
32646 static int proxyTakeConch(unixFile *pFile){
32647   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
32648   
32649   if( pCtx->conchHeld!=0 ){
32650     return SQLCIPHER_OK;
32651   }else{
32652     unixFile *conchFile = pCtx->conchFile;
32653     uuid_t myHostID;
32654     int pError = 0;
32655     char readBuf[PROXY_MAXCONCHLEN];
32656     char lockPath[MAXPATHLEN];
32657     char *tempLockPath = NULL;
32658     int rc = SQLCIPHER_OK;
32659     int createConch = 0;
32660     int hostIdMatch = 0;
32661     int readLen = 0;
32662     int tryOldLockPath = 0;
32663     int forceNewLockPath = 0;
32664     
32665     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
32666              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
32667
32668     rc = proxyGetHostID(myHostID, &pError);
32669     if( (rc&0xff)==SQLCIPHER_IOERR ){
32670       pFile->lastErrno = pError;
32671       goto end_takeconch;
32672     }
32673     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
32674     if( rc!=SQLCIPHER_OK ){
32675       goto end_takeconch;
32676     }
32677     /* read the existing conch file */
32678     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
32679     if( readLen<0 ){
32680       /* I/O error: lastErrno set by seekAndRead */
32681       pFile->lastErrno = conchFile->lastErrno;
32682       rc = SQLCIPHER_IOERR_READ;
32683       goto end_takeconch;
32684     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
32685              readBuf[0]!=(char)PROXY_CONCHVERSION ){
32686       /* a short read or version format mismatch means we need to create a new 
32687       ** conch file. 
32688       */
32689       createConch = 1;
32690     }
32691     /* if the host id matches and the lock path already exists in the conch
32692     ** we'll try to use the path there, if we can't open that path, we'll 
32693     ** retry with a new auto-generated path 
32694     */
32695     do { /* in case we need to try again for an :auto: named lock file */
32696
32697       if( !createConch && !forceNewLockPath ){
32698         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
32699                                   PROXY_HOSTIDLEN);
32700         /* if the conch has data compare the contents */
32701         if( !pCtx->lockProxyPath ){
32702           /* for auto-named local lock file, just check the host ID and we'll
32703            ** use the local lock file path that's already in there
32704            */
32705           if( hostIdMatch ){
32706             size_t pathLen = (readLen - PROXY_PATHINDEX);
32707             
32708             if( pathLen>=MAXPATHLEN ){
32709               pathLen=MAXPATHLEN-1;
32710             }
32711             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
32712             lockPath[pathLen] = 0;
32713             tempLockPath = lockPath;
32714             tryOldLockPath = 1;
32715             /* create a copy of the lock path if the conch is taken */
32716             goto end_takeconch;
32717           }
32718         }else if( hostIdMatch
32719                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
32720                            readLen-PROXY_PATHINDEX)
32721         ){
32722           /* conch host and lock path match */
32723           goto end_takeconch; 
32724         }
32725       }
32726       
32727       /* if the conch isn't writable and doesn't match, we can't take it */
32728       if( (conchFile->openFlags&O_RDWR) == 0 ){
32729         rc = SQLCIPHER_BUSY;
32730         goto end_takeconch;
32731       }
32732       
32733       /* either the conch didn't match or we need to create a new one */
32734       if( !pCtx->lockProxyPath ){
32735         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
32736         tempLockPath = lockPath;
32737         /* create a copy of the lock path _only_ if the conch is taken */
32738       }
32739       
32740       /* update conch with host and path (this will fail if other process
32741       ** has a shared lock already), if the host id matches, use the big
32742       ** stick.
32743       */
32744       futimes(conchFile->h, NULL);
32745       if( hostIdMatch && !createConch ){
32746         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
32747           /* We are trying for an exclusive lock but another thread in this
32748            ** same process is still holding a shared lock. */
32749           rc = SQLCIPHER_BUSY;
32750         } else {          
32751           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
32752         }
32753       }else{
32754         rc = conchFile->pMethod->xLock((sqlcipher3_file*)conchFile, EXCLUSIVE_LOCK);
32755       }
32756       if( rc==SQLCIPHER_OK ){
32757         char writeBuffer[PROXY_MAXCONCHLEN];
32758         int writeSize = 0;
32759         
32760         writeBuffer[0] = (char)PROXY_CONCHVERSION;
32761         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
32762         if( pCtx->lockProxyPath!=NULL ){
32763           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
32764         }else{
32765           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
32766         }
32767         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
32768         robust_ftruncate(conchFile->h, writeSize);
32769         rc = unixWrite((sqlcipher3_file *)conchFile, writeBuffer, writeSize, 0);
32770         fsync(conchFile->h);
32771         /* If we created a new conch file (not just updated the contents of a 
32772          ** valid conch file), try to match the permissions of the database 
32773          */
32774         if( rc==SQLCIPHER_OK && createConch ){
32775           struct stat buf;
32776           int err = osFstat(pFile->h, &buf);
32777           if( err==0 ){
32778             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
32779                                         S_IROTH|S_IWOTH);
32780             /* try to match the database file R/W permissions, ignore failure */
32781 #ifndef SQLCIPHER_PROXY_DEBUG
32782             osFchmod(conchFile->h, cmode);
32783 #else
32784             do{
32785               rc = osFchmod(conchFile->h, cmode);
32786             }while( rc==(-1) && errno==EINTR );
32787             if( rc!=0 ){
32788               int code = errno;
32789               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
32790                       cmode, code, strerror(code));
32791             } else {
32792               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
32793             }
32794           }else{
32795             int code = errno;
32796             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
32797                     err, code, strerror(code));
32798 #endif
32799           }
32800         }
32801       }
32802       conchFile->pMethod->xUnlock((sqlcipher3_file*)conchFile, SHARED_LOCK);
32803       
32804     end_takeconch:
32805       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
32806       if( rc==SQLCIPHER_OK && pFile->openFlags ){
32807         int fd;
32808         if( pFile->h>=0 ){
32809           robust_close(pFile, pFile->h, __LINE__);
32810         }
32811         pFile->h = -1;
32812         fd = robust_open(pCtx->dbPath, pFile->openFlags,
32813                       SQLCIPHER_DEFAULT_FILE_PERMISSIONS);
32814         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
32815         if( fd>=0 ){
32816           pFile->h = fd;
32817         }else{
32818           rc=SQLCIPHER_CANTOPEN_BKPT; /* SQLCIPHER_BUSY? proxyTakeConch called
32819            during locking */
32820         }
32821       }
32822       if( rc==SQLCIPHER_OK && !pCtx->lockProxy ){
32823         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
32824         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
32825         if( rc!=SQLCIPHER_OK && rc!=SQLCIPHER_NOMEM && tryOldLockPath ){
32826           /* we couldn't create the proxy lock file with the old lock file path
32827            ** so try again via auto-naming 
32828            */
32829           forceNewLockPath = 1;
32830           tryOldLockPath = 0;
32831           continue; /* go back to the do {} while start point, try again */
32832         }
32833       }
32834       if( rc==SQLCIPHER_OK ){
32835         /* Need to make a copy of path if we extracted the value
32836          ** from the conch file or the path was allocated on the stack
32837          */
32838         if( tempLockPath ){
32839           pCtx->lockProxyPath = sqlcipher3DbStrDup(0, tempLockPath);
32840           if( !pCtx->lockProxyPath ){
32841             rc = SQLCIPHER_NOMEM;
32842           }
32843         }
32844       }
32845       if( rc==SQLCIPHER_OK ){
32846         pCtx->conchHeld = 1;
32847         
32848         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
32849           afpLockingContext *afpCtx;
32850           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
32851           afpCtx->dbPath = pCtx->lockProxyPath;
32852         }
32853       } else {
32854         conchFile->pMethod->xUnlock((sqlcipher3_file*)conchFile, NO_LOCK);
32855       }
32856       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
32857                rc==SQLCIPHER_OK?"ok":"failed"));
32858       return rc;
32859     } while (1); /* in case we need to retry the :auto: lock file - 
32860                  ** we should never get here except via the 'continue' call. */
32861   }
32862 }
32863
32864 /*
32865 ** If pFile holds a lock on a conch file, then release that lock.
32866 */
32867 static int proxyReleaseConch(unixFile *pFile){
32868   int rc = SQLCIPHER_OK;         /* Subroutine return code */
32869   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
32870   unixFile *conchFile;        /* Name of the conch file */
32871
32872   pCtx = (proxyLockingContext *)pFile->lockingContext;
32873   conchFile = pCtx->conchFile;
32874   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
32875            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
32876            getpid()));
32877   if( pCtx->conchHeld>0 ){
32878     rc = conchFile->pMethod->xUnlock((sqlcipher3_file*)conchFile, NO_LOCK);
32879   }
32880   pCtx->conchHeld = 0;
32881   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
32882            (rc==SQLCIPHER_OK ? "ok" : "failed")));
32883   return rc;
32884 }
32885
32886 /*
32887 ** Given the name of a database file, compute the name of its conch file.
32888 ** Store the conch filename in memory obtained from sqlcipher3_malloc().
32889 ** Make *pConchPath point to the new name.  Return SQLCIPHER_OK on success
32890 ** or SQLCIPHER_NOMEM if unable to obtain memory.
32891 **
32892 ** The caller is responsible for ensuring that the allocated memory
32893 ** space is eventually freed.
32894 **
32895 ** *pConchPath is set to NULL if a memory allocation error occurs.
32896 */
32897 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
32898   int i;                        /* Loop counter */
32899   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
32900   char *conchPath;              /* buffer in which to construct conch name */
32901
32902   /* Allocate space for the conch filename and initialize the name to
32903   ** the name of the original database file. */  
32904   *pConchPath = conchPath = (char *)sqlcipher3_malloc(len + 8);
32905   if( conchPath==0 ){
32906     return SQLCIPHER_NOMEM;
32907   }
32908   memcpy(conchPath, dbPath, len+1);
32909   
32910   /* now insert a "." before the last / character */
32911   for( i=(len-1); i>=0; i-- ){
32912     if( conchPath[i]=='/' ){
32913       i++;
32914       break;
32915     }
32916   }
32917   conchPath[i]='.';
32918   while ( i<len ){
32919     conchPath[i+1]=dbPath[i];
32920     i++;
32921   }
32922
32923   /* append the "-conch" suffix to the file */
32924   memcpy(&conchPath[i+1], "-conch", 7);
32925   assert( (int)strlen(conchPath) == len+7 );
32926
32927   return SQLCIPHER_OK;
32928 }
32929
32930
32931 /* Takes a fully configured proxy locking-style unix file and switches
32932 ** the local lock file path 
32933 */
32934 static int switchLockProxyPath(unixFile *pFile, const char *path) {
32935   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
32936   char *oldPath = pCtx->lockProxyPath;
32937   int rc = SQLCIPHER_OK;
32938
32939   if( pFile->eFileLock!=NO_LOCK ){
32940     return SQLCIPHER_BUSY;
32941   }  
32942
32943   /* nothing to do if the path is NULL, :auto: or matches the existing path */
32944   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
32945     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
32946     return SQLCIPHER_OK;
32947   }else{
32948     unixFile *lockProxy = pCtx->lockProxy;
32949     pCtx->lockProxy=NULL;
32950     pCtx->conchHeld = 0;
32951     if( lockProxy!=NULL ){
32952       rc=lockProxy->pMethod->xClose((sqlcipher3_file *)lockProxy);
32953       if( rc ) return rc;
32954       sqlcipher3_free(lockProxy);
32955     }
32956     sqlcipher3_free(oldPath);
32957     pCtx->lockProxyPath = sqlcipher3DbStrDup(0, path);
32958   }
32959   
32960   return rc;
32961 }
32962
32963 /*
32964 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
32965 ** is a string buffer at least MAXPATHLEN+1 characters in size.
32966 **
32967 ** This routine find the filename associated with pFile and writes it
32968 ** int dbPath.
32969 */
32970 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
32971 #if defined(__APPLE__)
32972   if( pFile->pMethod == &afpIoMethods ){
32973     /* afp style keeps a reference to the db path in the filePath field 
32974     ** of the struct */
32975     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
32976     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
32977   } else
32978 #endif
32979   if( pFile->pMethod == &dotlockIoMethods ){
32980     /* dot lock style uses the locking context to store the dot lock
32981     ** file path */
32982     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
32983     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
32984   }else{
32985     /* all other styles use the locking context to store the db file path */
32986     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
32987     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
32988   }
32989   return SQLCIPHER_OK;
32990 }
32991
32992 /*
32993 ** Takes an already filled in unix file and alters it so all file locking 
32994 ** will be performed on the local proxy lock file.  The following fields
32995 ** are preserved in the locking context so that they can be restored and 
32996 ** the unix structure properly cleaned up at close time:
32997 **  ->lockingContext
32998 **  ->pMethod
32999 */
33000 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
33001   proxyLockingContext *pCtx;
33002   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
33003   char *lockPath=NULL;
33004   int rc = SQLCIPHER_OK;
33005   
33006   if( pFile->eFileLock!=NO_LOCK ){
33007     return SQLCIPHER_BUSY;
33008   }
33009   proxyGetDbPathForUnixFile(pFile, dbPath);
33010   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
33011     lockPath=NULL;
33012   }else{
33013     lockPath=(char *)path;
33014   }
33015   
33016   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
33017            (lockPath ? lockPath : ":auto:"), getpid()));
33018
33019   pCtx = sqlcipher3_malloc( sizeof(*pCtx) );
33020   if( pCtx==0 ){
33021     return SQLCIPHER_NOMEM;
33022   }
33023   memset(pCtx, 0, sizeof(*pCtx));
33024
33025   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
33026   if( rc==SQLCIPHER_OK ){
33027     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
33028     if( rc==SQLCIPHER_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
33029       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
33030       ** (c) the file system is read-only, then enable no-locking access.
33031       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
33032       ** that openFlags will have only one of O_RDONLY or O_RDWR.
33033       */
33034       struct statfs fsInfo;
33035       struct stat conchInfo;
33036       int goLockless = 0;
33037
33038       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
33039         int err = errno;
33040         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
33041           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
33042         }
33043       }
33044       if( goLockless ){
33045         pCtx->conchHeld = -1; /* read only FS/ lockless */
33046         rc = SQLCIPHER_OK;
33047       }
33048     }
33049   }  
33050   if( rc==SQLCIPHER_OK && lockPath ){
33051     pCtx->lockProxyPath = sqlcipher3DbStrDup(0, lockPath);
33052   }
33053
33054   if( rc==SQLCIPHER_OK ){
33055     pCtx->dbPath = sqlcipher3DbStrDup(0, dbPath);
33056     if( pCtx->dbPath==NULL ){
33057       rc = SQLCIPHER_NOMEM;
33058     }
33059   }
33060   if( rc==SQLCIPHER_OK ){
33061     /* all memory is allocated, proxys are created and assigned, 
33062     ** switch the locking context and pMethod then return.
33063     */
33064     pCtx->oldLockingContext = pFile->lockingContext;
33065     pFile->lockingContext = pCtx;
33066     pCtx->pOldMethod = pFile->pMethod;
33067     pFile->pMethod = &proxyIoMethods;
33068   }else{
33069     if( pCtx->conchFile ){ 
33070       pCtx->conchFile->pMethod->xClose((sqlcipher3_file *)pCtx->conchFile);
33071       sqlcipher3_free(pCtx->conchFile);
33072     }
33073     sqlcipher3DbFree(0, pCtx->lockProxyPath);
33074     sqlcipher3_free(pCtx->conchFilePath); 
33075     sqlcipher3_free(pCtx);
33076   }
33077   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
33078            (rc==SQLCIPHER_OK ? "ok" : "failed")));
33079   return rc;
33080 }
33081
33082
33083 /*
33084 ** This routine handles sqlcipher3_file_control() calls that are specific
33085 ** to proxy locking.
33086 */
33087 static int proxyFileControl(sqlcipher3_file *id, int op, void *pArg){
33088   switch( op ){
33089     case SQLCIPHER_GET_LOCKPROXYFILE: {
33090       unixFile *pFile = (unixFile*)id;
33091       if( pFile->pMethod == &proxyIoMethods ){
33092         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
33093         proxyTakeConch(pFile);
33094         if( pCtx->lockProxyPath ){
33095           *(const char **)pArg = pCtx->lockProxyPath;
33096         }else{
33097           *(const char **)pArg = ":auto: (not held)";
33098         }
33099       } else {
33100         *(const char **)pArg = NULL;
33101       }
33102       return SQLCIPHER_OK;
33103     }
33104     case SQLCIPHER_SET_LOCKPROXYFILE: {
33105       unixFile *pFile = (unixFile*)id;
33106       int rc = SQLCIPHER_OK;
33107       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
33108       if( pArg==NULL || (const char *)pArg==0 ){
33109         if( isProxyStyle ){
33110           /* turn off proxy locking - not supported */
33111           rc = SQLCIPHER_ERROR /*SQLCIPHER_PROTOCOL? SQLCIPHER_MISUSE?*/;
33112         }else{
33113           /* turn off proxy locking - already off - NOOP */
33114           rc = SQLCIPHER_OK;
33115         }
33116       }else{
33117         const char *proxyPath = (const char *)pArg;
33118         if( isProxyStyle ){
33119           proxyLockingContext *pCtx = 
33120             (proxyLockingContext*)pFile->lockingContext;
33121           if( !strcmp(pArg, ":auto:") 
33122            || (pCtx->lockProxyPath &&
33123                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
33124           ){
33125             rc = SQLCIPHER_OK;
33126           }else{
33127             rc = switchLockProxyPath(pFile, proxyPath);
33128           }
33129         }else{
33130           /* turn on proxy file locking */
33131           rc = proxyTransformUnixFile(pFile, proxyPath);
33132         }
33133       }
33134       return rc;
33135     }
33136     default: {
33137       assert( 0 );  /* The call assures that only valid opcodes are sent */
33138     }
33139   }
33140   /*NOTREACHED*/
33141   return SQLCIPHER_ERROR;
33142 }
33143
33144 /*
33145 ** Within this division (the proxying locking implementation) the procedures
33146 ** above this point are all utilities.  The lock-related methods of the
33147 ** proxy-locking sqlcipher3_io_method object follow.
33148 */
33149
33150
33151 /*
33152 ** This routine checks if there is a RESERVED lock held on the specified
33153 ** file by this or any other process. If such a lock is held, set *pResOut
33154 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
33155 ** is set to SQLCIPHER_OK unless an I/O error occurs during lock checking.
33156 */
33157 static int proxyCheckReservedLock(sqlcipher3_file *id, int *pResOut) {
33158   unixFile *pFile = (unixFile*)id;
33159   int rc = proxyTakeConch(pFile);
33160   if( rc==SQLCIPHER_OK ){
33161     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33162     if( pCtx->conchHeld>0 ){
33163       unixFile *proxy = pCtx->lockProxy;
33164       return proxy->pMethod->xCheckReservedLock((sqlcipher3_file*)proxy, pResOut);
33165     }else{ /* conchHeld < 0 is lockless */
33166       pResOut=0;
33167     }
33168   }
33169   return rc;
33170 }
33171
33172 /*
33173 ** Lock the file with the lock specified by parameter eFileLock - one
33174 ** of the following:
33175 **
33176 **     (1) SHARED_LOCK
33177 **     (2) RESERVED_LOCK
33178 **     (3) PENDING_LOCK
33179 **     (4) EXCLUSIVE_LOCK
33180 **
33181 ** Sometimes when requesting one lock state, additional lock states
33182 ** are inserted in between.  The locking might fail on one of the later
33183 ** transitions leaving the lock state different from what it started but
33184 ** still short of its goal.  The following chart shows the allowed
33185 ** transitions and the inserted intermediate states:
33186 **
33187 **    UNLOCKED -> SHARED
33188 **    SHARED -> RESERVED
33189 **    SHARED -> (PENDING) -> EXCLUSIVE
33190 **    RESERVED -> (PENDING) -> EXCLUSIVE
33191 **    PENDING -> EXCLUSIVE
33192 **
33193 ** This routine will only increase a lock.  Use the sqlcipher3OsUnlock()
33194 ** routine to lower a locking level.
33195 */
33196 static int proxyLock(sqlcipher3_file *id, int eFileLock) {
33197   unixFile *pFile = (unixFile*)id;
33198   int rc = proxyTakeConch(pFile);
33199   if( rc==SQLCIPHER_OK ){
33200     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33201     if( pCtx->conchHeld>0 ){
33202       unixFile *proxy = pCtx->lockProxy;
33203       rc = proxy->pMethod->xLock((sqlcipher3_file*)proxy, eFileLock);
33204       pFile->eFileLock = proxy->eFileLock;
33205     }else{
33206       /* conchHeld < 0 is lockless */
33207     }
33208   }
33209   return rc;
33210 }
33211
33212
33213 /*
33214 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
33215 ** must be either NO_LOCK or SHARED_LOCK.
33216 **
33217 ** If the locking level of the file descriptor is already at or below
33218 ** the requested locking level, this routine is a no-op.
33219 */
33220 static int proxyUnlock(sqlcipher3_file *id, int eFileLock) {
33221   unixFile *pFile = (unixFile*)id;
33222   int rc = proxyTakeConch(pFile);
33223   if( rc==SQLCIPHER_OK ){
33224     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33225     if( pCtx->conchHeld>0 ){
33226       unixFile *proxy = pCtx->lockProxy;
33227       rc = proxy->pMethod->xUnlock((sqlcipher3_file*)proxy, eFileLock);
33228       pFile->eFileLock = proxy->eFileLock;
33229     }else{
33230       /* conchHeld < 0 is lockless */
33231     }
33232   }
33233   return rc;
33234 }
33235
33236 /*
33237 ** Close a file that uses proxy locks.
33238 */
33239 static int proxyClose(sqlcipher3_file *id) {
33240   if( id ){
33241     unixFile *pFile = (unixFile*)id;
33242     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33243     unixFile *lockProxy = pCtx->lockProxy;
33244     unixFile *conchFile = pCtx->conchFile;
33245     int rc = SQLCIPHER_OK;
33246     
33247     if( lockProxy ){
33248       rc = lockProxy->pMethod->xUnlock((sqlcipher3_file*)lockProxy, NO_LOCK);
33249       if( rc ) return rc;
33250       rc = lockProxy->pMethod->xClose((sqlcipher3_file*)lockProxy);
33251       if( rc ) return rc;
33252       sqlcipher3_free(lockProxy);
33253       pCtx->lockProxy = 0;
33254     }
33255     if( conchFile ){
33256       if( pCtx->conchHeld ){
33257         rc = proxyReleaseConch(pFile);
33258         if( rc ) return rc;
33259       }
33260       rc = conchFile->pMethod->xClose((sqlcipher3_file*)conchFile);
33261       if( rc ) return rc;
33262       sqlcipher3_free(conchFile);
33263     }
33264     sqlcipher3DbFree(0, pCtx->lockProxyPath);
33265     sqlcipher3_free(pCtx->conchFilePath);
33266     sqlcipher3DbFree(0, pCtx->dbPath);
33267     /* restore the original locking context and pMethod then close it */
33268     pFile->lockingContext = pCtx->oldLockingContext;
33269     pFile->pMethod = pCtx->pOldMethod;
33270     sqlcipher3_free(pCtx);
33271     return pFile->pMethod->xClose(id);
33272   }
33273   return SQLCIPHER_OK;
33274 }
33275
33276
33277
33278 #endif /* defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE */
33279 /*
33280 ** The proxy locking style is intended for use with AFP filesystems.
33281 ** And since AFP is only supported on MacOSX, the proxy locking is also
33282 ** restricted to MacOSX.
33283 ** 
33284 **
33285 ******************* End of the proxy lock implementation **********************
33286 ******************************************************************************/
33287
33288 /*
33289 ** Initialize the operating system interface.
33290 **
33291 ** This routine registers all VFS implementations for unix-like operating
33292 ** systems.  This routine, and the sqlcipher3_os_end() routine that follows,
33293 ** should be the only routines in this file that are visible from other
33294 ** files.
33295 **
33296 ** This routine is called once during SQLite initialization and by a
33297 ** single thread.  The memory allocation and mutex subsystems have not
33298 ** necessarily been initialized when this routine is called, and so they
33299 ** should not be used.
33300 */
33301 SQLCIPHER_API int sqlcipher3_os_init(void){ 
33302   /* 
33303   ** The following macro defines an initializer for an sqlcipher3_vfs object.
33304   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
33305   ** to the "finder" function.  (pAppData is a pointer to a pointer because
33306   ** silly C90 rules prohibit a void* from being cast to a function pointer
33307   ** and so we have to go through the intermediate pointer to avoid problems
33308   ** when compiling with -pedantic-errors on GCC.)
33309   **
33310   ** The FINDER parameter to this macro is the name of the pointer to the
33311   ** finder-function.  The finder-function returns a pointer to the
33312   ** sqlcipher_io_methods object that implements the desired locking
33313   ** behaviors.  See the division above that contains the IOMETHODS
33314   ** macro for addition information on finder-functions.
33315   **
33316   ** Most finders simply return a pointer to a fixed sqlcipher3_io_methods
33317   ** object.  But the "autolockIoFinder" available on MacOSX does a little
33318   ** more than that; it looks at the filesystem type that hosts the 
33319   ** database file and tries to choose an locking method appropriate for
33320   ** that filesystem time.
33321   */
33322   #define UNIXVFS(VFSNAME, FINDER) {                        \
33323     3,                    /* iVersion */                    \
33324     sizeof(unixFile),     /* szOsFile */                    \
33325     MAX_PATHNAME,         /* mxPathname */                  \
33326     0,                    /* pNext */                       \
33327     VFSNAME,              /* zName */                       \
33328     (void*)&FINDER,       /* pAppData */                    \
33329     unixOpen,             /* xOpen */                       \
33330     unixDelete,           /* xDelete */                     \
33331     unixAccess,           /* xAccess */                     \
33332     unixFullPathname,     /* xFullPathname */               \
33333     unixDlOpen,           /* xDlOpen */                     \
33334     unixDlError,          /* xDlError */                    \
33335     unixDlSym,            /* xDlSym */                      \
33336     unixDlClose,          /* xDlClose */                    \
33337     unixRandomness,       /* xRandomness */                 \
33338     unixSleep,            /* xSleep */                      \
33339     unixCurrentTime,      /* xCurrentTime */                \
33340     unixGetLastError,     /* xGetLastError */               \
33341     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
33342     unixSetSystemCall,    /* xSetSystemCall */              \
33343     unixGetSystemCall,    /* xGetSystemCall */              \
33344     unixNextSystemCall,   /* xNextSystemCall */             \
33345   }
33346
33347   /*
33348   ** All default VFSes for unix are contained in the following array.
33349   **
33350   ** Note that the sqlcipher3_vfs.pNext field of the VFS object is modified
33351   ** by the SQLite core when the VFS is registered.  So the following
33352   ** array cannot be const.
33353   */
33354   static sqlcipher3_vfs aVfs[] = {
33355 #if SQLCIPHER_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
33356     UNIXVFS("unix",          autolockIoFinder ),
33357 #else
33358     UNIXVFS("unix",          posixIoFinder ),
33359 #endif
33360     UNIXVFS("unix-none",     nolockIoFinder ),
33361     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
33362     UNIXVFS("unix-excl",     posixIoFinder ),
33363 #if OS_VXWORKS
33364     UNIXVFS("unix-namedsem", semIoFinder ),
33365 #endif
33366 #if SQLCIPHER_ENABLE_LOCKING_STYLE
33367     UNIXVFS("unix-posix",    posixIoFinder ),
33368 #if !OS_VXWORKS
33369     UNIXVFS("unix-flock",    flockIoFinder ),
33370 #endif
33371 #endif
33372 #if SQLCIPHER_ENABLE_LOCKING_STYLE && defined(__APPLE__)
33373     UNIXVFS("unix-afp",      afpIoFinder ),
33374     UNIXVFS("unix-nfs",      nfsIoFinder ),
33375     UNIXVFS("unix-proxy",    proxyIoFinder ),
33376 #endif
33377   };
33378   unsigned int i;          /* Loop counter */
33379
33380   /* Double-check that the aSyscall[] array has been constructed
33381   ** correctly.  See ticket [bb3a86e890c8e96ab] */
33382   assert( ArraySize(aSyscall)==18 );
33383
33384   /* Register all VFSes defined in the aVfs[] array */
33385   for(i=0; i<(sizeof(aVfs)/sizeof(sqlcipher3_vfs)); i++){
33386     sqlcipher3_vfs_register(&aVfs[i], i==0);
33387   }
33388   return SQLCIPHER_OK; 
33389 }
33390
33391 /*
33392 ** Shutdown the operating system interface.
33393 **
33394 ** Some operating systems might need to do some cleanup in this routine,
33395 ** to release dynamically allocated objects.  But not on unix.
33396 ** This routine is a no-op for unix.
33397 */
33398 SQLCIPHER_API int sqlcipher3_os_end(void){ 
33399   return SQLCIPHER_OK; 
33400 }
33401  
33402 #endif /* SQLCIPHER_OS_UNIX */
33403
33404 /************** End of os_unix.c *********************************************/
33405 /************** Begin file os_win.c ******************************************/
33406 /*
33407 ** 2004 May 22
33408 **
33409 ** The author disclaims copyright to this source code.  In place of
33410 ** a legal notice, here is a blessing:
33411 **
33412 **    May you do good and not evil.
33413 **    May you find forgiveness for yourself and forgive others.
33414 **    May you share freely, never taking more than you give.
33415 **
33416 ******************************************************************************
33417 **
33418 ** This file contains code that is specific to windows.
33419 */
33420 #if SQLCIPHER_OS_WIN               /* This file is used for windows only */
33421
33422
33423 /*
33424 ** A Note About Memory Allocation:
33425 **
33426 ** This driver uses malloc()/free() directly rather than going through
33427 ** the SQLite-wrappers sqlcipher3_malloc()/sqlcipher3_free().  Those wrappers
33428 ** are designed for use on embedded systems where memory is scarce and
33429 ** malloc failures happen frequently.  Win32 does not typically run on
33430 ** embedded systems, and when it does the developers normally have bigger
33431 ** problems to worry about than running out of memory.  So there is not
33432 ** a compelling need to use the wrappers.
33433 **
33434 ** But there is a good reason to not use the wrappers.  If we use the
33435 ** wrappers then we will get simulated malloc() failures within this
33436 ** driver.  And that causes all kinds of problems for our tests.  We
33437 ** could enhance SQLite to deal with simulated malloc failures within
33438 ** the OS driver, but the code to deal with those failure would not
33439 ** be exercised on Linux (which does not need to malloc() in the driver)
33440 ** and so we would have difficulty writing coverage tests for that
33441 ** code.  Better to leave the code out, we think.
33442 **
33443 ** The point of this discussion is as follows:  When creating a new
33444 ** OS layer for an embedded system, if you use this file as an example,
33445 ** avoid the use of malloc()/free().  Those routines work ok on windows
33446 ** desktops but not so well in embedded systems.
33447 */
33448
33449 #include <winbase.h>
33450
33451 #ifdef __CYGWIN__
33452 # include <sys/cygwin.h>
33453 #endif
33454
33455 /*
33456 ** Macros used to determine whether or not to use threads.
33457 */
33458 #if defined(THREADSAFE) && THREADSAFE
33459 # define SQLCIPHER_W32_THREADS 1
33460 #endif
33461
33462 /*
33463 ** Include code that is common to all os_*.c files
33464 */
33465 /************** Include os_common.h in the middle of os_win.c ****************/
33466 /************** Begin file os_common.h ***************************************/
33467 /*
33468 ** 2004 May 22
33469 **
33470 ** The author disclaims copyright to this source code.  In place of
33471 ** a legal notice, here is a blessing:
33472 **
33473 **    May you do good and not evil.
33474 **    May you find forgiveness for yourself and forgive others.
33475 **    May you share freely, never taking more than you give.
33476 **
33477 ******************************************************************************
33478 **
33479 ** This file contains macros and a little bit of code that is common to
33480 ** all of the platform-specific files (os_*.c) and is #included into those
33481 ** files.
33482 **
33483 ** This file should be #included by the os_*.c files only.  It is not a
33484 ** general purpose header file.
33485 */
33486 #ifndef _OS_COMMON_H_
33487 #define _OS_COMMON_H_
33488
33489 /*
33490 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
33491 ** macro to SQLCIPHER_DEBUG and some older makefiles have not yet made the
33492 ** switch.  The following code should catch this problem at compile-time.
33493 */
33494 #ifdef MEMORY_DEBUG
33495 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLCIPHER_DEBUG instead."
33496 #endif
33497
33498 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
33499 # ifndef SQLCIPHER_DEBUG_OS_TRACE
33500 #   define SQLCIPHER_DEBUG_OS_TRACE 0
33501 # endif
33502   int sqlcipher3OSTrace = SQLCIPHER_DEBUG_OS_TRACE;
33503 # define OSTRACE(X)          if( sqlcipher3OSTrace ) sqlcipher3DebugPrintf X
33504 #else
33505 # define OSTRACE(X)
33506 #endif
33507
33508 /*
33509 ** Macros for performance tracing.  Normally turned off.  Only works
33510 ** on i486 hardware.
33511 */
33512 #ifdef SQLCIPHER_PERFORMANCE_TRACE
33513
33514 /* 
33515 ** hwtime.h contains inline assembler code for implementing 
33516 ** high-performance timing routines.
33517 */
33518 /************** Include hwtime.h in the middle of os_common.h ****************/
33519 /************** Begin file hwtime.h ******************************************/
33520 /*
33521 ** 2008 May 27
33522 **
33523 ** The author disclaims copyright to this source code.  In place of
33524 ** a legal notice, here is a blessing:
33525 **
33526 **    May you do good and not evil.
33527 **    May you find forgiveness for yourself and forgive others.
33528 **    May you share freely, never taking more than you give.
33529 **
33530 ******************************************************************************
33531 **
33532 ** This file contains inline asm code for retrieving "high-performance"
33533 ** counters for x86 class CPUs.
33534 */
33535 #ifndef _HWTIME_H_
33536 #define _HWTIME_H_
33537
33538 /*
33539 ** The following routine only works on pentium-class (or newer) processors.
33540 ** It uses the RDTSC opcode to read the cycle count value out of the
33541 ** processor and returns that value.  This can be used for high-res
33542 ** profiling.
33543 */
33544 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
33545       (defined(i386) || defined(__i386__) || defined(_M_IX86))
33546
33547   #if defined(__GNUC__)
33548
33549   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
33550      unsigned int lo, hi;
33551      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
33552      return (sqlcipher_uint64)hi << 32 | lo;
33553   }
33554
33555   #elif defined(_MSC_VER)
33556
33557   __declspec(naked) __inline sqlcipher_uint64 __cdecl sqlcipher3Hwtime(void){
33558      __asm {
33559         rdtsc
33560         ret       ; return value at EDX:EAX
33561      }
33562   }
33563
33564   #endif
33565
33566 #elif (defined(__GNUC__) && defined(__x86_64__))
33567
33568   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
33569       unsigned long val;
33570       __asm__ __volatile__ ("rdtsc" : "=A" (val));
33571       return val;
33572   }
33573  
33574 #elif (defined(__GNUC__) && defined(__ppc__))
33575
33576   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
33577       unsigned long long retval;
33578       unsigned long junk;
33579       __asm__ __volatile__ ("\n\
33580           1:      mftbu   %1\n\
33581                   mftb    %L0\n\
33582                   mftbu   %0\n\
33583                   cmpw    %0,%1\n\
33584                   bne     1b"
33585                   : "=r" (retval), "=r" (junk));
33586       return retval;
33587   }
33588
33589 #else
33590
33591   #error Need implementation of sqlcipher3Hwtime() for your platform.
33592
33593   /*
33594   ** To compile without implementing sqlcipher3Hwtime() for your platform,
33595   ** you can remove the above #error and use the following
33596   ** stub function.  You will lose timing support for many
33597   ** of the debugging and testing utilities, but it should at
33598   ** least compile and run.
33599   */
33600 SQLCIPHER_PRIVATE   sqlcipher_uint64 sqlcipher3Hwtime(void){ return ((sqlcipher_uint64)0); }
33601
33602 #endif
33603
33604 #endif /* !defined(_HWTIME_H_) */
33605
33606 /************** End of hwtime.h **********************************************/
33607 /************** Continuing where we left off in os_common.h ******************/
33608
33609 static sqlcipher_uint64 g_start;
33610 static sqlcipher_uint64 g_elapsed;
33611 #define TIMER_START       g_start=sqlcipher3Hwtime()
33612 #define TIMER_END         g_elapsed=sqlcipher3Hwtime()-g_start
33613 #define TIMER_ELAPSED     g_elapsed
33614 #else
33615 #define TIMER_START
33616 #define TIMER_END
33617 #define TIMER_ELAPSED     ((sqlcipher_uint64)0)
33618 #endif
33619
33620 /*
33621 ** If we compile with the SQLCIPHER_TEST macro set, then the following block
33622 ** of code will give us the ability to simulate a disk I/O error.  This
33623 ** is used for testing the I/O recovery logic.
33624 */
33625 #ifdef SQLCIPHER_TEST
33626 SQLCIPHER_API int sqlcipher3_io_error_hit = 0;            /* Total number of I/O Errors */
33627 SQLCIPHER_API int sqlcipher3_io_error_hardhit = 0;        /* Number of non-benign errors */
33628 SQLCIPHER_API int sqlcipher3_io_error_pending = 0;        /* Count down to first I/O error */
33629 SQLCIPHER_API int sqlcipher3_io_error_persist = 0;        /* True if I/O errors persist */
33630 SQLCIPHER_API int sqlcipher3_io_error_benign = 0;         /* True if errors are benign */
33631 SQLCIPHER_API int sqlcipher3_diskfull_pending = 0;
33632 SQLCIPHER_API int sqlcipher3_diskfull = 0;
33633 #define SimulateIOErrorBenign(X) sqlcipher3_io_error_benign=(X)
33634 #define SimulateIOError(CODE)  \
33635   if( (sqlcipher3_io_error_persist && sqlcipher3_io_error_hit) \
33636        || sqlcipher3_io_error_pending-- == 1 )  \
33637               { local_ioerr(); CODE; }
33638 static void local_ioerr(){
33639   IOTRACE(("IOERR\n"));
33640   sqlcipher3_io_error_hit++;
33641   if( !sqlcipher3_io_error_benign ) sqlcipher3_io_error_hardhit++;
33642 }
33643 #define SimulateDiskfullError(CODE) \
33644    if( sqlcipher3_diskfull_pending ){ \
33645      if( sqlcipher3_diskfull_pending == 1 ){ \
33646        local_ioerr(); \
33647        sqlcipher3_diskfull = 1; \
33648        sqlcipher3_io_error_hit = 1; \
33649        CODE; \
33650      }else{ \
33651        sqlcipher3_diskfull_pending--; \
33652      } \
33653    }
33654 #else
33655 #define SimulateIOErrorBenign(X)
33656 #define SimulateIOError(A)
33657 #define SimulateDiskfullError(A)
33658 #endif
33659
33660 /*
33661 ** When testing, keep a count of the number of open files.
33662 */
33663 #ifdef SQLCIPHER_TEST
33664 SQLCIPHER_API int sqlcipher3_open_file_count = 0;
33665 #define OpenCounter(X)  sqlcipher3_open_file_count+=(X)
33666 #else
33667 #define OpenCounter(X)
33668 #endif
33669
33670 #endif /* !defined(_OS_COMMON_H_) */
33671
33672 /************** End of os_common.h *******************************************/
33673 /************** Continuing where we left off in os_win.c *********************/
33674
33675 /*
33676 ** Some microsoft compilers lack this definition.
33677 */
33678 #ifndef INVALID_FILE_ATTRIBUTES
33679 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
33680 #endif
33681
33682 /*
33683 ** Determine if we are dealing with WindowsCE - which has a much
33684 ** reduced API.
33685 */
33686 #if SQLCIPHER_OS_WINCE
33687 # define AreFileApisANSI() 1
33688 # define FormatMessageW(a,b,c,d,e,f,g) 0
33689 #endif
33690
33691 /* Forward references */
33692 typedef struct winShm winShm;           /* A connection to shared-memory */
33693 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
33694
33695 /*
33696 ** WinCE lacks native support for file locking so we have to fake it
33697 ** with some code of our own.
33698 */
33699 #if SQLCIPHER_OS_WINCE
33700 typedef struct winceLock {
33701   int nReaders;       /* Number of reader locks obtained */
33702   BOOL bPending;      /* Indicates a pending lock has been obtained */
33703   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
33704   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
33705 } winceLock;
33706 #endif
33707
33708 /*
33709 ** The winFile structure is a subclass of sqlcipher3_file* specific to the win32
33710 ** portability layer.
33711 */
33712 typedef struct winFile winFile;
33713 struct winFile {
33714   const sqlcipher3_io_methods *pMethod; /*** Must be first ***/
33715   sqlcipher3_vfs *pVfs;      /* The VFS used to open this file */
33716   HANDLE h;               /* Handle for accessing the file */
33717   u8 locktype;            /* Type of lock currently held on this file */
33718   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
33719   u8 bPersistWal;         /* True to persist WAL files */
33720   DWORD lastErrno;        /* The Windows errno from the last I/O error */
33721   DWORD sectorSize;       /* Sector size of the device file is on */
33722   winShm *pShm;           /* Instance of shared memory on this file */
33723   const char *zPath;      /* Full pathname of this file */
33724   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
33725 #if SQLCIPHER_OS_WINCE
33726   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
33727   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
33728   HANDLE hShared;         /* Shared memory segment used for locking */
33729   winceLock local;        /* Locks obtained by this instance of winFile */
33730   winceLock *shared;      /* Global shared lock memory for the file  */
33731 #endif
33732 };
33733
33734 /*
33735  * If compiled with SQLCIPHER_WIN32_MALLOC on Windows, we will use the
33736  * various Win32 API heap functions instead of our own.
33737  */
33738 #ifdef SQLCIPHER_WIN32_MALLOC
33739 /*
33740  * The initial size of the Win32-specific heap.  This value may be zero.
33741  */
33742 #ifndef SQLCIPHER_WIN32_HEAP_INIT_SIZE
33743 #  define SQLCIPHER_WIN32_HEAP_INIT_SIZE ((SQLCIPHER_DEFAULT_CACHE_SIZE) * \
33744                                        (SQLCIPHER_DEFAULT_PAGE_SIZE) + 4194304)
33745 #endif
33746
33747 /*
33748  * The maximum size of the Win32-specific heap.  This value may be zero.
33749  */
33750 #ifndef SQLCIPHER_WIN32_HEAP_MAX_SIZE
33751 #  define SQLCIPHER_WIN32_HEAP_MAX_SIZE  (0)
33752 #endif
33753
33754 /*
33755  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
33756  * zero for the default behavior.
33757  */
33758 #ifndef SQLCIPHER_WIN32_HEAP_FLAGS
33759 #  define SQLCIPHER_WIN32_HEAP_FLAGS     (0)
33760 #endif
33761
33762 /*
33763 ** The winMemData structure stores information required by the Win32-specific
33764 ** sqlcipher3_mem_methods implementation.
33765 */
33766 typedef struct winMemData winMemData;
33767 struct winMemData {
33768 #ifndef NDEBUG
33769   u32 magic;    /* Magic number to detect structure corruption. */
33770 #endif
33771   HANDLE hHeap; /* The handle to our heap. */
33772   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
33773 };
33774
33775 #ifndef NDEBUG
33776 #define WINMEM_MAGIC     0x42b2830b
33777 #endif
33778
33779 static struct winMemData win_mem_data = {
33780 #ifndef NDEBUG
33781   WINMEM_MAGIC,
33782 #endif
33783   NULL, FALSE
33784 };
33785
33786 #ifndef NDEBUG
33787 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
33788 #else
33789 #define winMemAssertMagic()
33790 #endif
33791
33792 #define winMemGetHeap() win_mem_data.hHeap
33793
33794 static void *winMemMalloc(int nBytes);
33795 static void winMemFree(void *pPrior);
33796 static void *winMemRealloc(void *pPrior, int nBytes);
33797 static int winMemSize(void *p);
33798 static int winMemRoundup(int n);
33799 static int winMemInit(void *pAppData);
33800 static void winMemShutdown(void *pAppData);
33801
33802 SQLCIPHER_PRIVATE const sqlcipher3_mem_methods *sqlcipher3MemGetWin32(void);
33803 #endif /* SQLCIPHER_WIN32_MALLOC */
33804
33805 /*
33806 ** Forward prototypes.
33807 */
33808 static int getSectorSize(
33809     sqlcipher3_vfs *pVfs,
33810     const char *zRelative     /* UTF-8 file name */
33811 );
33812
33813 /*
33814 ** The following variable is (normally) set once and never changes
33815 ** thereafter.  It records whether the operating system is Win95
33816 ** or WinNT.
33817 **
33818 ** 0:   Operating system unknown.
33819 ** 1:   Operating system is Win95.
33820 ** 2:   Operating system is WinNT.
33821 **
33822 ** In order to facilitate testing on a WinNT system, the test fixture
33823 ** can manually set this value to 1 to emulate Win98 behavior.
33824 */
33825 #ifdef SQLCIPHER_TEST
33826 SQLCIPHER_API int sqlcipher3_os_type = 0;
33827 #else
33828 static int sqlcipher3_os_type = 0;
33829 #endif
33830
33831 /*
33832 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
33833 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
33834 **
33835 ** Here is an interesting observation:  Win95, Win98, and WinME lack
33836 ** the LockFileEx() API.  But we can still statically link against that
33837 ** API as long as we don't call it when running Win95/98/ME.  A call to
33838 ** this routine is used to determine if the host is Win95/98/ME or
33839 ** WinNT/2K/XP so that we will know whether or not we can safely call
33840 ** the LockFileEx() API.
33841 */
33842 #if SQLCIPHER_OS_WINCE
33843 # define isNT()  (1)
33844 #else
33845   static int isNT(void){
33846     if( sqlcipher3_os_type==0 ){
33847       OSVERSIONINFO sInfo;
33848       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
33849       GetVersionEx(&sInfo);
33850       sqlcipher3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
33851     }
33852     return sqlcipher3_os_type==2;
33853   }
33854 #endif /* SQLCIPHER_OS_WINCE */
33855
33856 #ifdef SQLCIPHER_WIN32_MALLOC
33857 /*
33858 ** Allocate nBytes of memory.
33859 */
33860 static void *winMemMalloc(int nBytes){
33861   HANDLE hHeap;
33862   void *p;
33863
33864   winMemAssertMagic();
33865   hHeap = winMemGetHeap();
33866   assert( hHeap!=0 );
33867   assert( hHeap!=INVALID_HANDLE_VALUE );
33868 #ifdef SQLCIPHER_WIN32_MALLOC_VALIDATE
33869   assert ( HeapValidate(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, NULL) );
33870 #endif
33871   assert( nBytes>=0 );
33872   p = HeapAlloc(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
33873   if( !p ){
33874     sqlcipher3_log(SQLCIPHER_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
33875         nBytes, GetLastError(), (void*)hHeap);
33876   }
33877   return p;
33878 }
33879
33880 /*
33881 ** Free memory.
33882 */
33883 static void winMemFree(void *pPrior){
33884   HANDLE hHeap;
33885
33886   winMemAssertMagic();
33887   hHeap = winMemGetHeap();
33888   assert( hHeap!=0 );
33889   assert( hHeap!=INVALID_HANDLE_VALUE );
33890 #ifdef SQLCIPHER_WIN32_MALLOC_VALIDATE
33891   assert ( HeapValidate(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, pPrior) );
33892 #endif
33893   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
33894   if( !HeapFree(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, pPrior) ){
33895     sqlcipher3_log(SQLCIPHER_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
33896         pPrior, GetLastError(), (void*)hHeap);
33897   }
33898 }
33899
33900 /*
33901 ** Change the size of an existing memory allocation
33902 */
33903 static void *winMemRealloc(void *pPrior, int nBytes){
33904   HANDLE hHeap;
33905   void *p;
33906
33907   winMemAssertMagic();
33908   hHeap = winMemGetHeap();
33909   assert( hHeap!=0 );
33910   assert( hHeap!=INVALID_HANDLE_VALUE );
33911 #ifdef SQLCIPHER_WIN32_MALLOC_VALIDATE
33912   assert ( HeapValidate(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, pPrior) );
33913 #endif
33914   assert( nBytes>=0 );
33915   if( !pPrior ){
33916     p = HeapAlloc(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
33917   }else{
33918     p = HeapReAlloc(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
33919   }
33920   if( !p ){
33921     sqlcipher3_log(SQLCIPHER_NOMEM, "failed to %s %u bytes (%d), heap=%p",
33922         pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, GetLastError(),
33923         (void*)hHeap);
33924   }
33925   return p;
33926 }
33927
33928 /*
33929 ** Return the size of an outstanding allocation, in bytes.
33930 */
33931 static int winMemSize(void *p){
33932   HANDLE hHeap;
33933   SIZE_T n;
33934
33935   winMemAssertMagic();
33936   hHeap = winMemGetHeap();
33937   assert( hHeap!=0 );
33938   assert( hHeap!=INVALID_HANDLE_VALUE );
33939 #ifdef SQLCIPHER_WIN32_MALLOC_VALIDATE
33940   assert ( HeapValidate(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, NULL) );
33941 #endif
33942   if( !p ) return 0;
33943   n = HeapSize(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, p);
33944   if( n==(SIZE_T)-1 ){
33945     sqlcipher3_log(SQLCIPHER_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
33946         p, GetLastError(), (void*)hHeap);
33947     return 0;
33948   }
33949   return (int)n;
33950 }
33951
33952 /*
33953 ** Round up a request size to the next valid allocation size.
33954 */
33955 static int winMemRoundup(int n){
33956   return n;
33957 }
33958
33959 /*
33960 ** Initialize this module.
33961 */
33962 static int winMemInit(void *pAppData){
33963   winMemData *pWinMemData = (winMemData *)pAppData;
33964
33965   if( !pWinMemData ) return SQLCIPHER_ERROR;
33966   assert( pWinMemData->magic==WINMEM_MAGIC );
33967   if( !pWinMemData->hHeap ){
33968     pWinMemData->hHeap = HeapCreate(SQLCIPHER_WIN32_HEAP_FLAGS,
33969                                     SQLCIPHER_WIN32_HEAP_INIT_SIZE,
33970                                     SQLCIPHER_WIN32_HEAP_MAX_SIZE);
33971     if( !pWinMemData->hHeap ){
33972       sqlcipher3_log(SQLCIPHER_NOMEM,
33973           "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
33974           GetLastError(), SQLCIPHER_WIN32_HEAP_FLAGS, SQLCIPHER_WIN32_HEAP_INIT_SIZE,
33975           SQLCIPHER_WIN32_HEAP_MAX_SIZE);
33976       return SQLCIPHER_NOMEM;
33977     }
33978     pWinMemData->bOwned = TRUE;
33979   }
33980   assert( pWinMemData->hHeap!=0 );
33981   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
33982 #ifdef SQLCIPHER_WIN32_MALLOC_VALIDATE
33983   assert( HeapValidate(pWinMemData->hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, NULL) );
33984 #endif
33985   return SQLCIPHER_OK;
33986 }
33987
33988 /*
33989 ** Deinitialize this module.
33990 */
33991 static void winMemShutdown(void *pAppData){
33992   winMemData *pWinMemData = (winMemData *)pAppData;
33993
33994   if( !pWinMemData ) return;
33995   if( pWinMemData->hHeap ){
33996     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
33997 #ifdef SQLCIPHER_WIN32_MALLOC_VALIDATE
33998     assert( HeapValidate(pWinMemData->hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, NULL) );
33999 #endif
34000     if( pWinMemData->bOwned ){
34001       if( !HeapDestroy(pWinMemData->hHeap) ){
34002         sqlcipher3_log(SQLCIPHER_NOMEM, "failed to HeapDestroy (%d), heap=%p",
34003             GetLastError(), (void*)pWinMemData->hHeap);
34004       }
34005       pWinMemData->bOwned = FALSE;
34006     }
34007     pWinMemData->hHeap = NULL;
34008   }
34009 }
34010
34011 /*
34012 ** Populate the low-level memory allocation function pointers in
34013 ** sqlcipher3GlobalConfig.m with pointers to the routines in this file. The
34014 ** arguments specify the block of memory to manage.
34015 **
34016 ** This routine is only called by sqlcipher3_config(), and therefore
34017 ** is not required to be threadsafe (it is not).
34018 */
34019 SQLCIPHER_PRIVATE const sqlcipher3_mem_methods *sqlcipher3MemGetWin32(void){
34020   static const sqlcipher3_mem_methods winMemMethods = {
34021     winMemMalloc,
34022     winMemFree,
34023     winMemRealloc,
34024     winMemSize,
34025     winMemRoundup,
34026     winMemInit,
34027     winMemShutdown,
34028     &win_mem_data
34029   };
34030   return &winMemMethods;
34031 }
34032
34033 SQLCIPHER_PRIVATE void sqlcipher3MemSetDefault(void){
34034   sqlcipher3_config(SQLCIPHER_CONFIG_MALLOC, sqlcipher3MemGetWin32());
34035 }
34036 #endif /* SQLCIPHER_WIN32_MALLOC */
34037
34038 /*
34039 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
34040 **
34041 ** Space to hold the returned string is obtained from malloc.
34042 */
34043 static WCHAR *utf8ToUnicode(const char *zFilename){
34044   int nChar;
34045   WCHAR *zWideFilename;
34046
34047   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
34048   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
34049   if( zWideFilename==0 ){
34050     return 0;
34051   }
34052   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
34053   if( nChar==0 ){
34054     free(zWideFilename);
34055     zWideFilename = 0;
34056   }
34057   return zWideFilename;
34058 }
34059
34060 /*
34061 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
34062 ** obtained from malloc().
34063 */
34064 static char *unicodeToUtf8(const WCHAR *zWideFilename){
34065   int nByte;
34066   char *zFilename;
34067
34068   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
34069   zFilename = malloc( nByte );
34070   if( zFilename==0 ){
34071     return 0;
34072   }
34073   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
34074                               0, 0);
34075   if( nByte == 0 ){
34076     free(zFilename);
34077     zFilename = 0;
34078   }
34079   return zFilename;
34080 }
34081
34082 /*
34083 ** Convert an ansi string to microsoft unicode, based on the
34084 ** current codepage settings for file apis.
34085 ** 
34086 ** Space to hold the returned string is obtained
34087 ** from malloc.
34088 */
34089 static WCHAR *mbcsToUnicode(const char *zFilename){
34090   int nByte;
34091   WCHAR *zMbcsFilename;
34092   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
34093
34094   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
34095   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
34096   if( zMbcsFilename==0 ){
34097     return 0;
34098   }
34099   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
34100   if( nByte==0 ){
34101     free(zMbcsFilename);
34102     zMbcsFilename = 0;
34103   }
34104   return zMbcsFilename;
34105 }
34106
34107 /*
34108 ** Convert microsoft unicode to multibyte character string, based on the
34109 ** user's Ansi codepage.
34110 **
34111 ** Space to hold the returned string is obtained from
34112 ** malloc().
34113 */
34114 static char *unicodeToMbcs(const WCHAR *zWideFilename){
34115   int nByte;
34116   char *zFilename;
34117   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
34118
34119   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
34120   zFilename = malloc( nByte );
34121   if( zFilename==0 ){
34122     return 0;
34123   }
34124   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
34125                               0, 0);
34126   if( nByte == 0 ){
34127     free(zFilename);
34128     zFilename = 0;
34129   }
34130   return zFilename;
34131 }
34132
34133 /*
34134 ** Convert multibyte character string to UTF-8.  Space to hold the
34135 ** returned string is obtained from malloc().
34136 */
34137 SQLCIPHER_API char *sqlcipher3_win32_mbcs_to_utf8(const char *zFilename){
34138   char *zFilenameUtf8;
34139   WCHAR *zTmpWide;
34140
34141   zTmpWide = mbcsToUnicode(zFilename);
34142   if( zTmpWide==0 ){
34143     return 0;
34144   }
34145   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
34146   free(zTmpWide);
34147   return zFilenameUtf8;
34148 }
34149
34150 /*
34151 ** Convert UTF-8 to multibyte character string.  Space to hold the 
34152 ** returned string is obtained from malloc().
34153 */
34154 SQLCIPHER_API char *sqlcipher3_win32_utf8_to_mbcs(const char *zFilename){
34155   char *zFilenameMbcs;
34156   WCHAR *zTmpWide;
34157
34158   zTmpWide = utf8ToUnicode(zFilename);
34159   if( zTmpWide==0 ){
34160     return 0;
34161   }
34162   zFilenameMbcs = unicodeToMbcs(zTmpWide);
34163   free(zTmpWide);
34164   return zFilenameMbcs;
34165 }
34166
34167
34168 /*
34169 ** The return value of getLastErrorMsg
34170 ** is zero if the error message fits in the buffer, or non-zero
34171 ** otherwise (if the message was truncated).
34172 */
34173 static int getLastErrorMsg(int nBuf, char *zBuf){
34174   /* FormatMessage returns 0 on failure.  Otherwise it
34175   ** returns the number of TCHARs written to the output
34176   ** buffer, excluding the terminating null char.
34177   */
34178   DWORD error = GetLastError();
34179   DWORD dwLen = 0;
34180   char *zOut = 0;
34181
34182   if( isNT() ){
34183     WCHAR *zTempWide = NULL;
34184     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
34185                            NULL,
34186                            error,
34187                            0,
34188                            (LPWSTR) &zTempWide,
34189                            0,
34190                            0);
34191     if( dwLen > 0 ){
34192       /* allocate a buffer and convert to UTF8 */
34193       zOut = unicodeToUtf8(zTempWide);
34194       /* free the system buffer allocated by FormatMessage */
34195       LocalFree(zTempWide);
34196     }
34197 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
34198 ** Since the ASCII version of these Windows API do not exist for WINCE,
34199 ** it's important to not reference them for WINCE builds.
34200 */
34201 #if SQLCIPHER_OS_WINCE==0
34202   }else{
34203     char *zTemp = NULL;
34204     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
34205                            NULL,
34206                            error,
34207                            0,
34208                            (LPSTR) &zTemp,
34209                            0,
34210                            0);
34211     if( dwLen > 0 ){
34212       /* allocate a buffer and convert to UTF8 */
34213       zOut = sqlcipher3_win32_mbcs_to_utf8(zTemp);
34214       /* free the system buffer allocated by FormatMessage */
34215       LocalFree(zTemp);
34216     }
34217 #endif
34218   }
34219   if( 0 == dwLen ){
34220     sqlcipher3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
34221   }else{
34222     /* copy a maximum of nBuf chars to output buffer */
34223     sqlcipher3_snprintf(nBuf, zBuf, "%s", zOut);
34224     /* free the UTF8 buffer */
34225     free(zOut);
34226   }
34227   return 0;
34228 }
34229
34230 /*
34231 **
34232 ** This function - winLogErrorAtLine() - is only ever called via the macro
34233 ** winLogError().
34234 **
34235 ** This routine is invoked after an error occurs in an OS function.
34236 ** It logs a message using sqlcipher3_log() containing the current value of
34237 ** error code and, if possible, the human-readable equivalent from 
34238 ** FormatMessage.
34239 **
34240 ** The first argument passed to the macro should be the error code that
34241 ** will be returned to SQLite (e.g. SQLCIPHER_IOERR_DELETE, SQLCIPHER_CANTOPEN). 
34242 ** The two subsequent arguments should be the name of the OS function that
34243 ** failed and the the associated file-system path, if any.
34244 */
34245 #define winLogError(a,b,c)     winLogErrorAtLine(a,b,c,__LINE__)
34246 static int winLogErrorAtLine(
34247   int errcode,                    /* SQLite error code */
34248   const char *zFunc,              /* Name of OS function that failed */
34249   const char *zPath,              /* File path associated with error */
34250   int iLine                       /* Source line number where error occurred */
34251 ){
34252   char zMsg[500];                 /* Human readable error text */
34253   int i;                          /* Loop counter */
34254   DWORD iErrno = GetLastError();  /* Error code */
34255
34256   zMsg[0] = 0;
34257   getLastErrorMsg(sizeof(zMsg), zMsg);
34258   assert( errcode!=SQLCIPHER_OK );
34259   if( zPath==0 ) zPath = "";
34260   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
34261   zMsg[i] = 0;
34262   sqlcipher3_log(errcode,
34263       "os_win.c:%d: (%d) %s(%s) - %s",
34264       iLine, iErrno, zFunc, zPath, zMsg
34265   );
34266
34267   return errcode;
34268 }
34269
34270 /*
34271 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
34272 ** will be retried following a locking error - probably caused by 
34273 ** antivirus software.  Also the initial delay before the first retry.
34274 ** The delay increases linearly with each retry.
34275 */
34276 #ifndef SQLCIPHER_WIN32_IOERR_RETRY
34277 # define SQLCIPHER_WIN32_IOERR_RETRY 10
34278 #endif
34279 #ifndef SQLCIPHER_WIN32_IOERR_RETRY_DELAY
34280 # define SQLCIPHER_WIN32_IOERR_RETRY_DELAY 25
34281 #endif
34282 static int win32IoerrRetry = SQLCIPHER_WIN32_IOERR_RETRY;
34283 static int win32IoerrRetryDelay = SQLCIPHER_WIN32_IOERR_RETRY_DELAY;
34284
34285 /*
34286 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
34287 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
34288 ** to give up with an error.
34289 */
34290 static int retryIoerr(int *pnRetry){
34291   DWORD e;
34292   if( *pnRetry>=win32IoerrRetry ){
34293     return 0;
34294   }
34295   e = GetLastError();
34296   if( e==ERROR_ACCESS_DENIED ||
34297       e==ERROR_LOCK_VIOLATION ||
34298       e==ERROR_SHARING_VIOLATION ){
34299     Sleep(win32IoerrRetryDelay*(1+*pnRetry));
34300     ++*pnRetry;
34301     return 1;
34302   }
34303   return 0;
34304 }
34305
34306 /*
34307 ** Log a I/O error retry episode.
34308 */
34309 static void logIoerr(int nRetry){
34310   if( nRetry ){
34311     sqlcipher3_log(SQLCIPHER_IOERR, 
34312       "delayed %dms for lock/sharing conflict",
34313       win32IoerrRetryDelay*nRetry*(nRetry+1)/2
34314     );
34315   }
34316 }
34317
34318 #if SQLCIPHER_OS_WINCE
34319 /*************************************************************************
34320 ** This section contains code for WinCE only.
34321 */
34322 /*
34323 ** WindowsCE does not have a localtime() function.  So create a
34324 ** substitute.
34325 */
34326 /* #include <time.h> */
34327 struct tm *__cdecl localtime(const time_t *t)
34328 {
34329   static struct tm y;
34330   FILETIME uTm, lTm;
34331   SYSTEMTIME pTm;
34332   sqlcipher3_int64 t64;
34333   t64 = *t;
34334   t64 = (t64 + 11644473600)*10000000;
34335   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
34336   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
34337   FileTimeToLocalFileTime(&uTm,&lTm);
34338   FileTimeToSystemTime(&lTm,&pTm);
34339   y.tm_year = pTm.wYear - 1900;
34340   y.tm_mon = pTm.wMonth - 1;
34341   y.tm_wday = pTm.wDayOfWeek;
34342   y.tm_mday = pTm.wDay;
34343   y.tm_hour = pTm.wHour;
34344   y.tm_min = pTm.wMinute;
34345   y.tm_sec = pTm.wSecond;
34346   return &y;
34347 }
34348
34349 /* This will never be called, but defined to make the code compile */
34350 #define GetTempPathA(a,b)
34351
34352 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
34353 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
34354 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
34355
34356 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
34357
34358 /*
34359 ** Acquire a lock on the handle h
34360 */
34361 static void winceMutexAcquire(HANDLE h){
34362    DWORD dwErr;
34363    do {
34364      dwErr = WaitForSingleObject(h, INFINITE);
34365    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
34366 }
34367 /*
34368 ** Release a lock acquired by winceMutexAcquire()
34369 */
34370 #define winceMutexRelease(h) ReleaseMutex(h)
34371
34372 /*
34373 ** Create the mutex and shared memory used for locking in the file
34374 ** descriptor pFile
34375 */
34376 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
34377   WCHAR *zTok;
34378   WCHAR *zName = utf8ToUnicode(zFilename);
34379   BOOL bInit = TRUE;
34380
34381   /* Initialize the local lockdata */
34382   ZeroMemory(&pFile->local, sizeof(pFile->local));
34383
34384   /* Replace the backslashes from the filename and lowercase it
34385   ** to derive a mutex name. */
34386   zTok = CharLowerW(zName);
34387   for (;*zTok;zTok++){
34388     if (*zTok == '\\') *zTok = '_';
34389   }
34390
34391   /* Create/open the named mutex */
34392   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
34393   if (!pFile->hMutex){
34394     pFile->lastErrno = GetLastError();
34395     winLogError(SQLCIPHER_ERROR, "winceCreateLock1", zFilename);
34396     free(zName);
34397     return FALSE;
34398   }
34399
34400   /* Acquire the mutex before continuing */
34401   winceMutexAcquire(pFile->hMutex);
34402   
34403   /* Since the names of named mutexes, semaphores, file mappings etc are 
34404   ** case-sensitive, take advantage of that by uppercasing the mutex name
34405   ** and using that as the shared filemapping name.
34406   */
34407   CharUpperW(zName);
34408   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
34409                                        PAGE_READWRITE, 0, sizeof(winceLock),
34410                                        zName);  
34411
34412   /* Set a flag that indicates we're the first to create the memory so it 
34413   ** must be zero-initialized */
34414   if (GetLastError() == ERROR_ALREADY_EXISTS){
34415     bInit = FALSE;
34416   }
34417
34418   free(zName);
34419
34420   /* If we succeeded in making the shared memory handle, map it. */
34421   if (pFile->hShared){
34422     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
34423              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
34424     /* If mapping failed, close the shared memory handle and erase it */
34425     if (!pFile->shared){
34426       pFile->lastErrno = GetLastError();
34427       winLogError(SQLCIPHER_ERROR, "winceCreateLock2", zFilename);
34428       CloseHandle(pFile->hShared);
34429       pFile->hShared = NULL;
34430     }
34431   }
34432
34433   /* If shared memory could not be created, then close the mutex and fail */
34434   if (pFile->hShared == NULL){
34435     winceMutexRelease(pFile->hMutex);
34436     CloseHandle(pFile->hMutex);
34437     pFile->hMutex = NULL;
34438     return FALSE;
34439   }
34440   
34441   /* Initialize the shared memory if we're supposed to */
34442   if (bInit) {
34443     ZeroMemory(pFile->shared, sizeof(winceLock));
34444   }
34445
34446   winceMutexRelease(pFile->hMutex);
34447   return TRUE;
34448 }
34449
34450 /*
34451 ** Destroy the part of winFile that deals with wince locks
34452 */
34453 static void winceDestroyLock(winFile *pFile){
34454   if (pFile->hMutex){
34455     /* Acquire the mutex */
34456     winceMutexAcquire(pFile->hMutex);
34457
34458     /* The following blocks should probably assert in debug mode, but they
34459        are to cleanup in case any locks remained open */
34460     if (pFile->local.nReaders){
34461       pFile->shared->nReaders --;
34462     }
34463     if (pFile->local.bReserved){
34464       pFile->shared->bReserved = FALSE;
34465     }
34466     if (pFile->local.bPending){
34467       pFile->shared->bPending = FALSE;
34468     }
34469     if (pFile->local.bExclusive){
34470       pFile->shared->bExclusive = FALSE;
34471     }
34472
34473     /* De-reference and close our copy of the shared memory handle */
34474     UnmapViewOfFile(pFile->shared);
34475     CloseHandle(pFile->hShared);
34476
34477     /* Done with the mutex */
34478     winceMutexRelease(pFile->hMutex);    
34479     CloseHandle(pFile->hMutex);
34480     pFile->hMutex = NULL;
34481   }
34482 }
34483
34484 /* 
34485 ** An implementation of the LockFile() API of windows for wince
34486 */
34487 static BOOL winceLockFile(
34488   HANDLE *phFile,
34489   DWORD dwFileOffsetLow,
34490   DWORD dwFileOffsetHigh,
34491   DWORD nNumberOfBytesToLockLow,
34492   DWORD nNumberOfBytesToLockHigh
34493 ){
34494   winFile *pFile = HANDLE_TO_WINFILE(phFile);
34495   BOOL bReturn = FALSE;
34496
34497   UNUSED_PARAMETER(dwFileOffsetHigh);
34498   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
34499
34500   if (!pFile->hMutex) return TRUE;
34501   winceMutexAcquire(pFile->hMutex);
34502
34503   /* Wanting an exclusive lock? */
34504   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
34505        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
34506     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
34507        pFile->shared->bExclusive = TRUE;
34508        pFile->local.bExclusive = TRUE;
34509        bReturn = TRUE;
34510     }
34511   }
34512
34513   /* Want a read-only lock? */
34514   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
34515            nNumberOfBytesToLockLow == 1){
34516     if (pFile->shared->bExclusive == 0){
34517       pFile->local.nReaders ++;
34518       if (pFile->local.nReaders == 1){
34519         pFile->shared->nReaders ++;
34520       }
34521       bReturn = TRUE;
34522     }
34523   }
34524
34525   /* Want a pending lock? */
34526   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
34527     /* If no pending lock has been acquired, then acquire it */
34528     if (pFile->shared->bPending == 0) {
34529       pFile->shared->bPending = TRUE;
34530       pFile->local.bPending = TRUE;
34531       bReturn = TRUE;
34532     }
34533   }
34534
34535   /* Want a reserved lock? */
34536   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
34537     if (pFile->shared->bReserved == 0) {
34538       pFile->shared->bReserved = TRUE;
34539       pFile->local.bReserved = TRUE;
34540       bReturn = TRUE;
34541     }
34542   }
34543
34544   winceMutexRelease(pFile->hMutex);
34545   return bReturn;
34546 }
34547
34548 /*
34549 ** An implementation of the UnlockFile API of windows for wince
34550 */
34551 static BOOL winceUnlockFile(
34552   HANDLE *phFile,
34553   DWORD dwFileOffsetLow,
34554   DWORD dwFileOffsetHigh,
34555   DWORD nNumberOfBytesToUnlockLow,
34556   DWORD nNumberOfBytesToUnlockHigh
34557 ){
34558   winFile *pFile = HANDLE_TO_WINFILE(phFile);
34559   BOOL bReturn = FALSE;
34560
34561   UNUSED_PARAMETER(dwFileOffsetHigh);
34562   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
34563
34564   if (!pFile->hMutex) return TRUE;
34565   winceMutexAcquire(pFile->hMutex);
34566
34567   /* Releasing a reader lock or an exclusive lock */
34568   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
34569     /* Did we have an exclusive lock? */
34570     if (pFile->local.bExclusive){
34571       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
34572       pFile->local.bExclusive = FALSE;
34573       pFile->shared->bExclusive = FALSE;
34574       bReturn = TRUE;
34575     }
34576
34577     /* Did we just have a reader lock? */
34578     else if (pFile->local.nReaders){
34579       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
34580       pFile->local.nReaders --;
34581       if (pFile->local.nReaders == 0)
34582       {
34583         pFile->shared->nReaders --;
34584       }
34585       bReturn = TRUE;
34586     }
34587   }
34588
34589   /* Releasing a pending lock */
34590   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
34591     if (pFile->local.bPending){
34592       pFile->local.bPending = FALSE;
34593       pFile->shared->bPending = FALSE;
34594       bReturn = TRUE;
34595     }
34596   }
34597   /* Releasing a reserved lock */
34598   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
34599     if (pFile->local.bReserved) {
34600       pFile->local.bReserved = FALSE;
34601       pFile->shared->bReserved = FALSE;
34602       bReturn = TRUE;
34603     }
34604   }
34605
34606   winceMutexRelease(pFile->hMutex);
34607   return bReturn;
34608 }
34609
34610 /*
34611 ** An implementation of the LockFileEx() API of windows for wince
34612 */
34613 static BOOL winceLockFileEx(
34614   HANDLE *phFile,
34615   DWORD dwFlags,
34616   DWORD dwReserved,
34617   DWORD nNumberOfBytesToLockLow,
34618   DWORD nNumberOfBytesToLockHigh,
34619   LPOVERLAPPED lpOverlapped
34620 ){
34621   UNUSED_PARAMETER(dwReserved);
34622   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
34623
34624   /* If the caller wants a shared read lock, forward this call
34625   ** to winceLockFile */
34626   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
34627       dwFlags == 1 &&
34628       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
34629     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
34630   }
34631   return FALSE;
34632 }
34633 /*
34634 ** End of the special code for wince
34635 *****************************************************************************/
34636 #endif /* SQLCIPHER_OS_WINCE */
34637
34638 /*****************************************************************************
34639 ** The next group of routines implement the I/O methods specified
34640 ** by the sqlcipher3_io_methods object.
34641 ******************************************************************************/
34642
34643 /*
34644 ** Some microsoft compilers lack this definition.
34645 */
34646 #ifndef INVALID_SET_FILE_POINTER
34647 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
34648 #endif
34649
34650 /*
34651 ** Move the current position of the file handle passed as the first 
34652 ** argument to offset iOffset within the file. If successful, return 0. 
34653 ** Otherwise, set pFile->lastErrno and return non-zero.
34654 */
34655 static int seekWinFile(winFile *pFile, sqlcipher3_int64 iOffset){
34656   LONG upperBits;                 /* Most sig. 32 bits of new offset */
34657   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
34658   DWORD dwRet;                    /* Value returned by SetFilePointer() */
34659
34660   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
34661   lowerBits = (LONG)(iOffset & 0xffffffff);
34662
34663   /* API oddity: If successful, SetFilePointer() returns a dword 
34664   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
34665   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
34666   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
34667   ** whether an error has actually occured, it is also necessary to call 
34668   ** GetLastError().
34669   */
34670   dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
34671   if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
34672     pFile->lastErrno = GetLastError();
34673     winLogError(SQLCIPHER_IOERR_SEEK, "seekWinFile", pFile->zPath);
34674     return 1;
34675   }
34676
34677   return 0;
34678 }
34679
34680 /*
34681 ** Close a file.
34682 **
34683 ** It is reported that an attempt to close a handle might sometimes
34684 ** fail.  This is a very unreasonable result, but windows is notorious
34685 ** for being unreasonable so I do not doubt that it might happen.  If
34686 ** the close fails, we pause for 100 milliseconds and try again.  As
34687 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
34688 ** giving up and returning an error.
34689 */
34690 #define MX_CLOSE_ATTEMPT 3
34691 static int winClose(sqlcipher3_file *id){
34692   int rc, cnt = 0;
34693   winFile *pFile = (winFile*)id;
34694
34695   assert( id!=0 );
34696   assert( pFile->pShm==0 );
34697   OSTRACE(("CLOSE %d\n", pFile->h));
34698   do{
34699     rc = CloseHandle(pFile->h);
34700     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
34701   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
34702 #if SQLCIPHER_OS_WINCE
34703 #define WINCE_DELETION_ATTEMPTS 3
34704   winceDestroyLock(pFile);
34705   if( pFile->zDeleteOnClose ){
34706     int cnt = 0;
34707     while(
34708            DeleteFileW(pFile->zDeleteOnClose)==0
34709         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
34710         && cnt++ < WINCE_DELETION_ATTEMPTS
34711     ){
34712        Sleep(100);  /* Wait a little before trying again */
34713     }
34714     free(pFile->zDeleteOnClose);
34715   }
34716 #endif
34717   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
34718   OpenCounter(-1);
34719   return rc ? SQLCIPHER_OK
34720             : winLogError(SQLCIPHER_IOERR_CLOSE, "winClose", pFile->zPath);
34721 }
34722
34723 /*
34724 ** Read data from a file into a buffer.  Return SQLCIPHER_OK if all
34725 ** bytes were read successfully and SQLCIPHER_IOERR if anything goes
34726 ** wrong.
34727 */
34728 static int winRead(
34729   sqlcipher3_file *id,          /* File to read from */
34730   void *pBuf,                /* Write content into this buffer */
34731   int amt,                   /* Number of bytes to read */
34732   sqlcipher3_int64 offset       /* Begin reading at this offset */
34733 ){
34734   winFile *pFile = (winFile*)id;  /* file handle */
34735   DWORD nRead;                    /* Number of bytes actually read from file */
34736   int nRetry = 0;                 /* Number of retrys */
34737
34738   assert( id!=0 );
34739   SimulateIOError(return SQLCIPHER_IOERR_READ);
34740   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
34741
34742   if( seekWinFile(pFile, offset) ){
34743     return SQLCIPHER_FULL;
34744   }
34745   while( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
34746     if( retryIoerr(&nRetry) ) continue;
34747     pFile->lastErrno = GetLastError();
34748     return winLogError(SQLCIPHER_IOERR_READ, "winRead", pFile->zPath);
34749   }
34750   logIoerr(nRetry);
34751   if( nRead<(DWORD)amt ){
34752     /* Unread parts of the buffer must be zero-filled */
34753     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
34754     return SQLCIPHER_IOERR_SHORT_READ;
34755   }
34756
34757   return SQLCIPHER_OK;
34758 }
34759
34760 /*
34761 ** Write data from a buffer into a file.  Return SQLCIPHER_OK on success
34762 ** or some other error code on failure.
34763 */
34764 static int winWrite(
34765   sqlcipher3_file *id,               /* File to write into */
34766   const void *pBuf,               /* The bytes to be written */
34767   int amt,                        /* Number of bytes to write */
34768   sqlcipher3_int64 offset            /* Offset into the file to begin writing at */
34769 ){
34770   int rc;                         /* True if error has occured, else false */
34771   winFile *pFile = (winFile*)id;  /* File handle */
34772   int nRetry = 0;                 /* Number of retries */
34773
34774   assert( amt>0 );
34775   assert( pFile );
34776   SimulateIOError(return SQLCIPHER_IOERR_WRITE);
34777   SimulateDiskfullError(return SQLCIPHER_FULL);
34778
34779   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
34780
34781   rc = seekWinFile(pFile, offset);
34782   if( rc==0 ){
34783     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
34784     int nRem = amt;               /* Number of bytes yet to be written */
34785     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
34786
34787     while( nRem>0 ){
34788       if( !WriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
34789         if( retryIoerr(&nRetry) ) continue;
34790         break;
34791       }
34792       if( nWrite<=0 ) break;
34793       aRem += nWrite;
34794       nRem -= nWrite;
34795     }
34796     if( nRem>0 ){
34797       pFile->lastErrno = GetLastError();
34798       rc = 1;
34799     }
34800   }
34801
34802   if( rc ){
34803     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
34804        || ( pFile->lastErrno==ERROR_DISK_FULL )){
34805       return SQLCIPHER_FULL;
34806     }
34807     return winLogError(SQLCIPHER_IOERR_WRITE, "winWrite", pFile->zPath);
34808   }else{
34809     logIoerr(nRetry);
34810   }
34811   return SQLCIPHER_OK;
34812 }
34813
34814 /*
34815 ** Truncate an open file to a specified size
34816 */
34817 static int winTruncate(sqlcipher3_file *id, sqlcipher3_int64 nByte){
34818   winFile *pFile = (winFile*)id;  /* File handle object */
34819   int rc = SQLCIPHER_OK;             /* Return code for this function */
34820
34821   assert( pFile );
34822
34823   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
34824   SimulateIOError(return SQLCIPHER_IOERR_TRUNCATE);
34825
34826   /* If the user has configured a chunk-size for this file, truncate the
34827   ** file so that it consists of an integer number of chunks (i.e. the
34828   ** actual file size after the operation may be larger than the requested
34829   ** size).
34830   */
34831   if( pFile->szChunk>0 ){
34832     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
34833   }
34834
34835   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
34836   if( seekWinFile(pFile, nByte) ){
34837     rc = winLogError(SQLCIPHER_IOERR_TRUNCATE, "winTruncate1", pFile->zPath);
34838   }else if( 0==SetEndOfFile(pFile->h) ){
34839     pFile->lastErrno = GetLastError();
34840     rc = winLogError(SQLCIPHER_IOERR_TRUNCATE, "winTruncate2", pFile->zPath);
34841   }
34842
34843   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
34844   return rc;
34845 }
34846
34847 #ifdef SQLCIPHER_TEST
34848 /*
34849 ** Count the number of fullsyncs and normal syncs.  This is used to test
34850 ** that syncs and fullsyncs are occuring at the right times.
34851 */
34852 SQLCIPHER_API int sqlcipher3_sync_count = 0;
34853 SQLCIPHER_API int sqlcipher3_fullsync_count = 0;
34854 #endif
34855
34856 /*
34857 ** Make sure all writes to a particular file are committed to disk.
34858 */
34859 static int winSync(sqlcipher3_file *id, int flags){
34860 #ifndef SQLCIPHER_NO_SYNC
34861   /*
34862   ** Used only when SQLCIPHER_NO_SYNC is not defined.
34863    */
34864   BOOL rc;
34865 #endif
34866 #if !defined(NDEBUG) || !defined(SQLCIPHER_NO_SYNC) || \
34867     (defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG))
34868   /*
34869   ** Used when SQLCIPHER_NO_SYNC is not defined and by the assert() and/or
34870   ** OSTRACE() macros.
34871    */
34872   winFile *pFile = (winFile*)id;
34873 #else
34874   UNUSED_PARAMETER(id);
34875 #endif
34876
34877   assert( pFile );
34878   /* Check that one of SQLCIPHER_SYNC_NORMAL or FULL was passed */
34879   assert((flags&0x0F)==SQLCIPHER_SYNC_NORMAL
34880       || (flags&0x0F)==SQLCIPHER_SYNC_FULL
34881   );
34882
34883   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
34884
34885   /* Unix cannot, but some systems may return SQLCIPHER_FULL from here. This
34886   ** line is to test that doing so does not cause any problems.
34887   */
34888   SimulateDiskfullError( return SQLCIPHER_FULL );
34889
34890 #ifndef SQLCIPHER_TEST
34891   UNUSED_PARAMETER(flags);
34892 #else
34893   if( (flags&0x0F)==SQLCIPHER_SYNC_FULL ){
34894     sqlcipher3_fullsync_count++;
34895   }
34896   sqlcipher3_sync_count++;
34897 #endif
34898
34899   /* If we compiled with the SQLCIPHER_NO_SYNC flag, then syncing is a
34900   ** no-op
34901   */
34902 #ifdef SQLCIPHER_NO_SYNC
34903   return SQLCIPHER_OK;
34904 #else
34905   rc = FlushFileBuffers(pFile->h);
34906   SimulateIOError( rc=FALSE );
34907   if( rc ){
34908     return SQLCIPHER_OK;
34909   }else{
34910     pFile->lastErrno = GetLastError();
34911     return winLogError(SQLCIPHER_IOERR_FSYNC, "winSync", pFile->zPath);
34912   }
34913 #endif
34914 }
34915
34916 /*
34917 ** Determine the current size of a file in bytes
34918 */
34919 static int winFileSize(sqlcipher3_file *id, sqlcipher3_int64 *pSize){
34920   DWORD upperBits;
34921   DWORD lowerBits;
34922   winFile *pFile = (winFile*)id;
34923   DWORD error;
34924
34925   assert( id!=0 );
34926   SimulateIOError(return SQLCIPHER_IOERR_FSTAT);
34927   lowerBits = GetFileSize(pFile->h, &upperBits);
34928   if(   (lowerBits == INVALID_FILE_SIZE)
34929      && ((error = GetLastError()) != NO_ERROR) )
34930   {
34931     pFile->lastErrno = error;
34932     return winLogError(SQLCIPHER_IOERR_FSTAT, "winFileSize", pFile->zPath);
34933   }
34934   *pSize = (((sqlcipher3_int64)upperBits)<<32) + lowerBits;
34935   return SQLCIPHER_OK;
34936 }
34937
34938 /*
34939 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
34940 */
34941 #ifndef LOCKFILE_FAIL_IMMEDIATELY
34942 # define LOCKFILE_FAIL_IMMEDIATELY 1
34943 #endif
34944
34945 /*
34946 ** Acquire a reader lock.
34947 ** Different API routines are called depending on whether or not this
34948 ** is Win95 or WinNT.
34949 */
34950 static int getReadLock(winFile *pFile){
34951   int res;
34952   if( isNT() ){
34953     OVERLAPPED ovlp;
34954     ovlp.Offset = SHARED_FIRST;
34955     ovlp.OffsetHigh = 0;
34956     ovlp.hEvent = 0;
34957     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
34958                      0, SHARED_SIZE, 0, &ovlp);
34959 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
34960 */
34961 #if SQLCIPHER_OS_WINCE==0
34962   }else{
34963     int lk;
34964     sqlcipher3_randomness(sizeof(lk), &lk);
34965     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
34966     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
34967 #endif
34968   }
34969   if( res == 0 ){
34970     pFile->lastErrno = GetLastError();
34971     /* No need to log a failure to lock */
34972   }
34973   return res;
34974 }
34975
34976 /*
34977 ** Undo a readlock
34978 */
34979 static int unlockReadLock(winFile *pFile){
34980   int res;
34981   if( isNT() ){
34982     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34983 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
34984 */
34985 #if SQLCIPHER_OS_WINCE==0
34986   }else{
34987     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
34988 #endif
34989   }
34990   if( res==0 && GetLastError()!=ERROR_NOT_LOCKED ){
34991     pFile->lastErrno = GetLastError();
34992     winLogError(SQLCIPHER_IOERR_UNLOCK, "unlockReadLock", pFile->zPath);
34993   }
34994   return res;
34995 }
34996
34997 /*
34998 ** Lock the file with the lock specified by parameter locktype - one
34999 ** of the following:
35000 **
35001 **     (1) SHARED_LOCK
35002 **     (2) RESERVED_LOCK
35003 **     (3) PENDING_LOCK
35004 **     (4) EXCLUSIVE_LOCK
35005 **
35006 ** Sometimes when requesting one lock state, additional lock states
35007 ** are inserted in between.  The locking might fail on one of the later
35008 ** transitions leaving the lock state different from what it started but
35009 ** still short of its goal.  The following chart shows the allowed
35010 ** transitions and the inserted intermediate states:
35011 **
35012 **    UNLOCKED -> SHARED
35013 **    SHARED -> RESERVED
35014 **    SHARED -> (PENDING) -> EXCLUSIVE
35015 **    RESERVED -> (PENDING) -> EXCLUSIVE
35016 **    PENDING -> EXCLUSIVE
35017 **
35018 ** This routine will only increase a lock.  The winUnlock() routine
35019 ** erases all locks at once and returns us immediately to locking level 0.
35020 ** It is not possible to lower the locking level one step at a time.  You
35021 ** must go straight to locking level 0.
35022 */
35023 static int winLock(sqlcipher3_file *id, int locktype){
35024   int rc = SQLCIPHER_OK;    /* Return code from subroutines */
35025   int res = 1;           /* Result of a windows lock call */
35026   int newLocktype;       /* Set pFile->locktype to this value before exiting */
35027   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
35028   winFile *pFile = (winFile*)id;
35029   DWORD error = NO_ERROR;
35030
35031   assert( id!=0 );
35032   OSTRACE(("LOCK %d %d was %d(%d)\n",
35033            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
35034
35035   /* If there is already a lock of this type or more restrictive on the
35036   ** OsFile, do nothing. Don't use the end_lock: exit path, as
35037   ** sqlcipher3OsEnterMutex() hasn't been called yet.
35038   */
35039   if( pFile->locktype>=locktype ){
35040     return SQLCIPHER_OK;
35041   }
35042
35043   /* Make sure the locking sequence is correct
35044   */
35045   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
35046   assert( locktype!=PENDING_LOCK );
35047   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
35048
35049   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
35050   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
35051   ** the PENDING_LOCK byte is temporary.
35052   */
35053   newLocktype = pFile->locktype;
35054   if(   (pFile->locktype==NO_LOCK)
35055      || (   (locktype==EXCLUSIVE_LOCK)
35056          && (pFile->locktype==RESERVED_LOCK))
35057   ){
35058     int cnt = 3;
35059     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
35060       /* Try 3 times to get the pending lock.  The pending lock might be
35061       ** held by another reader process who will release it momentarily.
35062       */
35063       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
35064       Sleep(1);
35065     }
35066     gotPendingLock = res;
35067     if( !res ){
35068       error = GetLastError();
35069     }
35070   }
35071
35072   /* Acquire a shared lock
35073   */
35074   if( locktype==SHARED_LOCK && res ){
35075     assert( pFile->locktype==NO_LOCK );
35076     res = getReadLock(pFile);
35077     if( res ){
35078       newLocktype = SHARED_LOCK;
35079     }else{
35080       error = GetLastError();
35081     }
35082   }
35083
35084   /* Acquire a RESERVED lock
35085   */
35086   if( locktype==RESERVED_LOCK && res ){
35087     assert( pFile->locktype==SHARED_LOCK );
35088     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
35089     if( res ){
35090       newLocktype = RESERVED_LOCK;
35091     }else{
35092       error = GetLastError();
35093     }
35094   }
35095
35096   /* Acquire a PENDING lock
35097   */
35098   if( locktype==EXCLUSIVE_LOCK && res ){
35099     newLocktype = PENDING_LOCK;
35100     gotPendingLock = 0;
35101   }
35102
35103   /* Acquire an EXCLUSIVE lock
35104   */
35105   if( locktype==EXCLUSIVE_LOCK && res ){
35106     assert( pFile->locktype>=SHARED_LOCK );
35107     res = unlockReadLock(pFile);
35108     OSTRACE(("unreadlock = %d\n", res));
35109     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
35110     if( res ){
35111       newLocktype = EXCLUSIVE_LOCK;
35112     }else{
35113       error = GetLastError();
35114       OSTRACE(("error-code = %d\n", error));
35115       getReadLock(pFile);
35116     }
35117   }
35118
35119   /* If we are holding a PENDING lock that ought to be released, then
35120   ** release it now.
35121   */
35122   if( gotPendingLock && locktype==SHARED_LOCK ){
35123     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
35124   }
35125
35126   /* Update the state of the lock has held in the file descriptor then
35127   ** return the appropriate result code.
35128   */
35129   if( res ){
35130     rc = SQLCIPHER_OK;
35131   }else{
35132     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
35133            locktype, newLocktype));
35134     pFile->lastErrno = error;
35135     rc = SQLCIPHER_BUSY;
35136   }
35137   pFile->locktype = (u8)newLocktype;
35138   return rc;
35139 }
35140
35141 /*
35142 ** This routine checks if there is a RESERVED lock held on the specified
35143 ** file by this or any other process. If such a lock is held, return
35144 ** non-zero, otherwise zero.
35145 */
35146 static int winCheckReservedLock(sqlcipher3_file *id, int *pResOut){
35147   int rc;
35148   winFile *pFile = (winFile*)id;
35149
35150   SimulateIOError( return SQLCIPHER_IOERR_CHECKRESERVEDLOCK; );
35151
35152   assert( id!=0 );
35153   if( pFile->locktype>=RESERVED_LOCK ){
35154     rc = 1;
35155     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
35156   }else{
35157     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
35158     if( rc ){
35159       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
35160     }
35161     rc = !rc;
35162     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
35163   }
35164   *pResOut = rc;
35165   return SQLCIPHER_OK;
35166 }
35167
35168 /*
35169 ** Lower the locking level on file descriptor id to locktype.  locktype
35170 ** must be either NO_LOCK or SHARED_LOCK.
35171 **
35172 ** If the locking level of the file descriptor is already at or below
35173 ** the requested locking level, this routine is a no-op.
35174 **
35175 ** It is not possible for this routine to fail if the second argument
35176 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
35177 ** might return SQLCIPHER_IOERR;
35178 */
35179 static int winUnlock(sqlcipher3_file *id, int locktype){
35180   int type;
35181   winFile *pFile = (winFile*)id;
35182   int rc = SQLCIPHER_OK;
35183   assert( pFile!=0 );
35184   assert( locktype<=SHARED_LOCK );
35185   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
35186           pFile->locktype, pFile->sharedLockByte));
35187   type = pFile->locktype;
35188   if( type>=EXCLUSIVE_LOCK ){
35189     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
35190     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
35191       /* This should never happen.  We should always be able to
35192       ** reacquire the read lock */
35193       rc = winLogError(SQLCIPHER_IOERR_UNLOCK, "winUnlock", pFile->zPath);
35194     }
35195   }
35196   if( type>=RESERVED_LOCK ){
35197     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
35198   }
35199   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
35200     unlockReadLock(pFile);
35201   }
35202   if( type>=PENDING_LOCK ){
35203     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
35204   }
35205   pFile->locktype = (u8)locktype;
35206   return rc;
35207 }
35208
35209 /*
35210 ** Control and query of the open file handle.
35211 */
35212 static int winFileControl(sqlcipher3_file *id, int op, void *pArg){
35213   winFile *pFile = (winFile*)id;
35214   switch( op ){
35215     case SQLCIPHER_FCNTL_LOCKSTATE: {
35216       *(int*)pArg = pFile->locktype;
35217       return SQLCIPHER_OK;
35218     }
35219     case SQLCIPHER_LAST_ERRNO: {
35220       *(int*)pArg = (int)pFile->lastErrno;
35221       return SQLCIPHER_OK;
35222     }
35223     case SQLCIPHER_FCNTL_CHUNK_SIZE: {
35224       pFile->szChunk = *(int *)pArg;
35225       return SQLCIPHER_OK;
35226     }
35227     case SQLCIPHER_FCNTL_SIZE_HINT: {
35228       if( pFile->szChunk>0 ){
35229         sqlcipher3_int64 oldSz;
35230         int rc = winFileSize(id, &oldSz);
35231         if( rc==SQLCIPHER_OK ){
35232           sqlcipher3_int64 newSz = *(sqlcipher3_int64*)pArg;
35233           if( newSz>oldSz ){
35234             SimulateIOErrorBenign(1);
35235             rc = winTruncate(id, newSz);
35236             SimulateIOErrorBenign(0);
35237           }
35238         }
35239         return rc;
35240       }
35241       return SQLCIPHER_OK;
35242     }
35243     case SQLCIPHER_FCNTL_PERSIST_WAL: {
35244       int bPersist = *(int*)pArg;
35245       if( bPersist<0 ){
35246         *(int*)pArg = pFile->bPersistWal;
35247       }else{
35248         pFile->bPersistWal = bPersist!=0;
35249       }
35250       return SQLCIPHER_OK;
35251     }
35252     case SQLCIPHER_FCNTL_SYNC_OMITTED: {
35253       return SQLCIPHER_OK;
35254     }
35255     case SQLCIPHER_FCNTL_WIN32_AV_RETRY: {
35256       int *a = (int*)pArg;
35257       if( a[0]>0 ){
35258         win32IoerrRetry = a[0];
35259       }else{
35260         a[0] = win32IoerrRetry;
35261       }
35262       if( a[1]>0 ){
35263         win32IoerrRetryDelay = a[1];
35264       }else{
35265         a[1] = win32IoerrRetryDelay;
35266       }
35267       return SQLCIPHER_OK;
35268     }
35269   }
35270   return SQLCIPHER_NOTFOUND;
35271 }
35272
35273 /*
35274 ** Return the sector size in bytes of the underlying block device for
35275 ** the specified file. This is almost always 512 bytes, but may be
35276 ** larger for some devices.
35277 **
35278 ** SQLite code assumes this function cannot fail. It also assumes that
35279 ** if two files are created in the same file-system directory (i.e.
35280 ** a database and its journal file) that the sector size will be the
35281 ** same for both.
35282 */
35283 static int winSectorSize(sqlcipher3_file *id){
35284   assert( id!=0 );
35285   return (int)(((winFile*)id)->sectorSize);
35286 }
35287
35288 /*
35289 ** Return a vector of device characteristics.
35290 */
35291 static int winDeviceCharacteristics(sqlcipher3_file *id){
35292   UNUSED_PARAMETER(id);
35293   return SQLCIPHER_IOCAP_UNDELETABLE_WHEN_OPEN;
35294 }
35295
35296 #ifndef SQLCIPHER_OMIT_WAL
35297
35298 /* 
35299 ** Windows will only let you create file view mappings
35300 ** on allocation size granularity boundaries.
35301 ** During sqlcipher3_os_init() we do a GetSystemInfo()
35302 ** to get the granularity size.
35303 */
35304 SYSTEM_INFO winSysInfo;
35305
35306 /*
35307 ** Helper functions to obtain and relinquish the global mutex. The
35308 ** global mutex is used to protect the winLockInfo objects used by 
35309 ** this file, all of which may be shared by multiple threads.
35310 **
35311 ** Function winShmMutexHeld() is used to assert() that the global mutex 
35312 ** is held when required. This function is only used as part of assert() 
35313 ** statements. e.g.
35314 **
35315 **   winShmEnterMutex()
35316 **     assert( winShmMutexHeld() );
35317 **   winShmLeaveMutex()
35318 */
35319 static void winShmEnterMutex(void){
35320   sqlcipher3_mutex_enter(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
35321 }
35322 static void winShmLeaveMutex(void){
35323   sqlcipher3_mutex_leave(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
35324 }
35325 #ifdef SQLCIPHER_DEBUG
35326 static int winShmMutexHeld(void) {
35327   return sqlcipher3_mutex_held(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
35328 }
35329 #endif
35330
35331 /*
35332 ** Object used to represent a single file opened and mmapped to provide
35333 ** shared memory.  When multiple threads all reference the same
35334 ** log-summary, each thread has its own winFile object, but they all
35335 ** point to a single instance of this object.  In other words, each
35336 ** log-summary is opened only once per process.
35337 **
35338 ** winShmMutexHeld() must be true when creating or destroying
35339 ** this object or while reading or writing the following fields:
35340 **
35341 **      nRef
35342 **      pNext 
35343 **
35344 ** The following fields are read-only after the object is created:
35345 ** 
35346 **      fid
35347 **      zFilename
35348 **
35349 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
35350 ** winShmMutexHeld() is true when reading or writing any other field
35351 ** in this structure.
35352 **
35353 */
35354 struct winShmNode {
35355   sqlcipher3_mutex *mutex;      /* Mutex to access this object */
35356   char *zFilename;           /* Name of the file */
35357   winFile hFile;             /* File handle from winOpen */
35358
35359   int szRegion;              /* Size of shared-memory regions */
35360   int nRegion;               /* Size of array apRegion */
35361   struct ShmRegion {
35362     HANDLE hMap;             /* File handle from CreateFileMapping */
35363     void *pMap;
35364   } *aRegion;
35365   DWORD lastErrno;           /* The Windows errno from the last I/O error */
35366
35367   int nRef;                  /* Number of winShm objects pointing to this */
35368   winShm *pFirst;            /* All winShm objects pointing to this */
35369   winShmNode *pNext;         /* Next in list of all winShmNode objects */
35370 #ifdef SQLCIPHER_DEBUG
35371   u8 nextShmId;              /* Next available winShm.id value */
35372 #endif
35373 };
35374
35375 /*
35376 ** A global array of all winShmNode objects.
35377 **
35378 ** The winShmMutexHeld() must be true while reading or writing this list.
35379 */
35380 static winShmNode *winShmNodeList = 0;
35381
35382 /*
35383 ** Structure used internally by this VFS to record the state of an
35384 ** open shared memory connection.
35385 **
35386 ** The following fields are initialized when this object is created and
35387 ** are read-only thereafter:
35388 **
35389 **    winShm.pShmNode
35390 **    winShm.id
35391 **
35392 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
35393 ** while accessing any read/write fields.
35394 */
35395 struct winShm {
35396   winShmNode *pShmNode;      /* The underlying winShmNode object */
35397   winShm *pNext;             /* Next winShm with the same winShmNode */
35398   u8 hasMutex;               /* True if holding the winShmNode mutex */
35399   u16 sharedMask;            /* Mask of shared locks held */
35400   u16 exclMask;              /* Mask of exclusive locks held */
35401 #ifdef SQLCIPHER_DEBUG
35402   u8 id;                     /* Id of this connection with its winShmNode */
35403 #endif
35404 };
35405
35406 /*
35407 ** Constants used for locking
35408 */
35409 #define WIN_SHM_BASE   ((22+SQLCIPHER_SHM_NLOCK)*4)        /* first lock byte */
35410 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLCIPHER_SHM_NLOCK)  /* deadman switch */
35411
35412 /*
35413 ** Apply advisory locks for all n bytes beginning at ofst.
35414 */
35415 #define _SHM_UNLCK  1
35416 #define _SHM_RDLCK  2
35417 #define _SHM_WRLCK  3
35418 static int winShmSystemLock(
35419   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
35420   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
35421   int ofst,             /* Offset to first byte to be locked/unlocked */
35422   int nByte             /* Number of bytes to lock or unlock */
35423 ){
35424   OVERLAPPED ovlp;
35425   DWORD dwFlags;
35426   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
35427
35428   /* Access to the winShmNode object is serialized by the caller */
35429   assert( sqlcipher3_mutex_held(pFile->mutex) || pFile->nRef==0 );
35430
35431   /* Initialize the locking parameters */
35432   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
35433   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
35434
35435   memset(&ovlp, 0, sizeof(OVERLAPPED));
35436   ovlp.Offset = ofst;
35437
35438   /* Release/Acquire the system-level lock */
35439   if( lockType==_SHM_UNLCK ){
35440     rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
35441   }else{
35442     rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
35443   }
35444   
35445   if( rc!= 0 ){
35446     rc = SQLCIPHER_OK;
35447   }else{
35448     pFile->lastErrno =  GetLastError();
35449     rc = SQLCIPHER_BUSY;
35450   }
35451
35452   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
35453            pFile->hFile.h,
35454            rc==SQLCIPHER_OK ? "ok" : "failed",
35455            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
35456            pFile->lastErrno));
35457
35458   return rc;
35459 }
35460
35461 /* Forward references to VFS methods */
35462 static int winOpen(sqlcipher3_vfs*,const char*,sqlcipher3_file*,int,int*);
35463 static int winDelete(sqlcipher3_vfs *,const char*,int);
35464
35465 /*
35466 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
35467 **
35468 ** This is not a VFS shared-memory method; it is a utility function called
35469 ** by VFS shared-memory methods.
35470 */
35471 static void winShmPurge(sqlcipher3_vfs *pVfs, int deleteFlag){
35472   winShmNode **pp;
35473   winShmNode *p;
35474   BOOL bRc;
35475   assert( winShmMutexHeld() );
35476   pp = &winShmNodeList;
35477   while( (p = *pp)!=0 ){
35478     if( p->nRef==0 ){
35479       int i;
35480       if( p->mutex ) sqlcipher3_mutex_free(p->mutex);
35481       for(i=0; i<p->nRegion; i++){
35482         bRc = UnmapViewOfFile(p->aRegion[i].pMap);
35483         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
35484                  (int)GetCurrentProcessId(), i,
35485                  bRc ? "ok" : "failed"));
35486         bRc = CloseHandle(p->aRegion[i].hMap);
35487         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
35488                  (int)GetCurrentProcessId(), i,
35489                  bRc ? "ok" : "failed"));
35490       }
35491       if( p->hFile.h != INVALID_HANDLE_VALUE ){
35492         SimulateIOErrorBenign(1);
35493         winClose((sqlcipher3_file *)&p->hFile);
35494         SimulateIOErrorBenign(0);
35495       }
35496       if( deleteFlag ){
35497         SimulateIOErrorBenign(1);
35498         winDelete(pVfs, p->zFilename, 0);
35499         SimulateIOErrorBenign(0);
35500       }
35501       *pp = p->pNext;
35502       sqlcipher3_free(p->aRegion);
35503       sqlcipher3_free(p);
35504     }else{
35505       pp = &p->pNext;
35506     }
35507   }
35508 }
35509
35510 /*
35511 ** Open the shared-memory area associated with database file pDbFd.
35512 **
35513 ** When opening a new shared-memory file, if no other instances of that
35514 ** file are currently open, in this process or in other processes, then
35515 ** the file must be truncated to zero length or have its header cleared.
35516 */
35517 static int winOpenSharedMemory(winFile *pDbFd){
35518   struct winShm *p;                  /* The connection to be opened */
35519   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
35520   int rc;                            /* Result code */
35521   struct winShmNode *pNew;           /* Newly allocated winShmNode */
35522   int nName;                         /* Size of zName in bytes */
35523
35524   assert( pDbFd->pShm==0 );    /* Not previously opened */
35525
35526   /* Allocate space for the new sqlcipher3_shm object.  Also speculatively
35527   ** allocate space for a new winShmNode and filename.
35528   */
35529   p = sqlcipher3_malloc( sizeof(*p) );
35530   if( p==0 ) return SQLCIPHER_NOMEM;
35531   memset(p, 0, sizeof(*p));
35532   nName = sqlcipher3Strlen30(pDbFd->zPath);
35533   pNew = sqlcipher3_malloc( sizeof(*pShmNode) + nName + 15 );
35534   if( pNew==0 ){
35535     sqlcipher3_free(p);
35536     return SQLCIPHER_NOMEM;
35537   }
35538   memset(pNew, 0, sizeof(*pNew));
35539   pNew->zFilename = (char*)&pNew[1];
35540   sqlcipher3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
35541   sqlcipher3FileSuffix3(pDbFd->zPath, pNew->zFilename); 
35542
35543   /* Look to see if there is an existing winShmNode that can be used.
35544   ** If no matching winShmNode currently exists, create a new one.
35545   */
35546   winShmEnterMutex();
35547   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
35548     /* TBD need to come up with better match here.  Perhaps
35549     ** use FILE_ID_BOTH_DIR_INFO Structure.
35550     */
35551     if( sqlcipher3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
35552   }
35553   if( pShmNode ){
35554     sqlcipher3_free(pNew);
35555   }else{
35556     pShmNode = pNew;
35557     pNew = 0;
35558     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
35559     pShmNode->pNext = winShmNodeList;
35560     winShmNodeList = pShmNode;
35561
35562     pShmNode->mutex = sqlcipher3_mutex_alloc(SQLCIPHER_MUTEX_FAST);
35563     if( pShmNode->mutex==0 ){
35564       rc = SQLCIPHER_NOMEM;
35565       goto shm_open_err;
35566     }
35567
35568     rc = winOpen(pDbFd->pVfs,
35569                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
35570                  (sqlcipher3_file*)&pShmNode->hFile,  /* File handle here */
35571                  SQLCIPHER_OPEN_WAL | SQLCIPHER_OPEN_READWRITE | SQLCIPHER_OPEN_CREATE, /* Mode flags */
35572                  0);
35573     if( SQLCIPHER_OK!=rc ){
35574       rc = SQLCIPHER_CANTOPEN_BKPT;
35575       goto shm_open_err;
35576     }
35577
35578     /* Check to see if another process is holding the dead-man switch.
35579     ** If not, truncate the file to zero length. 
35580     */
35581     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLCIPHER_OK ){
35582       rc = winTruncate((sqlcipher3_file *)&pShmNode->hFile, 0);
35583       if( rc!=SQLCIPHER_OK ){
35584         rc = winLogError(SQLCIPHER_IOERR_SHMOPEN, "winOpenShm", pDbFd->zPath);
35585       }
35586     }
35587     if( rc==SQLCIPHER_OK ){
35588       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
35589       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
35590     }
35591     if( rc ) goto shm_open_err;
35592   }
35593
35594   /* Make the new connection a child of the winShmNode */
35595   p->pShmNode = pShmNode;
35596 #ifdef SQLCIPHER_DEBUG
35597   p->id = pShmNode->nextShmId++;
35598 #endif
35599   pShmNode->nRef++;
35600   pDbFd->pShm = p;
35601   winShmLeaveMutex();
35602
35603   /* The reference count on pShmNode has already been incremented under
35604   ** the cover of the winShmEnterMutex() mutex and the pointer from the
35605   ** new (struct winShm) object to the pShmNode has been set. All that is
35606   ** left to do is to link the new object into the linked list starting
35607   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
35608   ** mutex.
35609   */
35610   sqlcipher3_mutex_enter(pShmNode->mutex);
35611   p->pNext = pShmNode->pFirst;
35612   pShmNode->pFirst = p;
35613   sqlcipher3_mutex_leave(pShmNode->mutex);
35614   return SQLCIPHER_OK;
35615
35616   /* Jump here on any error */
35617 shm_open_err:
35618   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
35619   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
35620   sqlcipher3_free(p);
35621   sqlcipher3_free(pNew);
35622   winShmLeaveMutex();
35623   return rc;
35624 }
35625
35626 /*
35627 ** Close a connection to shared-memory.  Delete the underlying 
35628 ** storage if deleteFlag is true.
35629 */
35630 static int winShmUnmap(
35631   sqlcipher3_file *fd,          /* Database holding shared memory */
35632   int deleteFlag             /* Delete after closing if true */
35633 ){
35634   winFile *pDbFd;       /* Database holding shared-memory */
35635   winShm *p;            /* The connection to be closed */
35636   winShmNode *pShmNode; /* The underlying shared-memory file */
35637   winShm **pp;          /* For looping over sibling connections */
35638
35639   pDbFd = (winFile*)fd;
35640   p = pDbFd->pShm;
35641   if( p==0 ) return SQLCIPHER_OK;
35642   pShmNode = p->pShmNode;
35643
35644   /* Remove connection p from the set of connections associated
35645   ** with pShmNode */
35646   sqlcipher3_mutex_enter(pShmNode->mutex);
35647   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
35648   *pp = p->pNext;
35649
35650   /* Free the connection p */
35651   sqlcipher3_free(p);
35652   pDbFd->pShm = 0;
35653   sqlcipher3_mutex_leave(pShmNode->mutex);
35654
35655   /* If pShmNode->nRef has reached 0, then close the underlying
35656   ** shared-memory file, too */
35657   winShmEnterMutex();
35658   assert( pShmNode->nRef>0 );
35659   pShmNode->nRef--;
35660   if( pShmNode->nRef==0 ){
35661     winShmPurge(pDbFd->pVfs, deleteFlag);
35662   }
35663   winShmLeaveMutex();
35664
35665   return SQLCIPHER_OK;
35666 }
35667
35668 /*
35669 ** Change the lock state for a shared-memory segment.
35670 */
35671 static int winShmLock(
35672   sqlcipher3_file *fd,          /* Database file holding the shared memory */
35673   int ofst,                  /* First lock to acquire or release */
35674   int n,                     /* Number of locks to acquire or release */
35675   int flags                  /* What to do with the lock */
35676 ){
35677   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
35678   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
35679   winShm *pX;                           /* For looping over all siblings */
35680   winShmNode *pShmNode = p->pShmNode;
35681   int rc = SQLCIPHER_OK;                   /* Result code */
35682   u16 mask;                             /* Mask of locks to take or release */
35683
35684   assert( ofst>=0 && ofst+n<=SQLCIPHER_SHM_NLOCK );
35685   assert( n>=1 );
35686   assert( flags==(SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_SHARED)
35687        || flags==(SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_EXCLUSIVE)
35688        || flags==(SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_SHARED)
35689        || flags==(SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_EXCLUSIVE) );
35690   assert( n==1 || (flags & SQLCIPHER_SHM_EXCLUSIVE)!=0 );
35691
35692   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
35693   assert( n>1 || mask==(1<<ofst) );
35694   sqlcipher3_mutex_enter(pShmNode->mutex);
35695   if( flags & SQLCIPHER_SHM_UNLOCK ){
35696     u16 allMask = 0; /* Mask of locks held by siblings */
35697
35698     /* See if any siblings hold this same lock */
35699     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35700       if( pX==p ) continue;
35701       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
35702       allMask |= pX->sharedMask;
35703     }
35704
35705     /* Unlock the system-level locks */
35706     if( (mask & allMask)==0 ){
35707       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
35708     }else{
35709       rc = SQLCIPHER_OK;
35710     }
35711
35712     /* Undo the local locks */
35713     if( rc==SQLCIPHER_OK ){
35714       p->exclMask &= ~mask;
35715       p->sharedMask &= ~mask;
35716     } 
35717   }else if( flags & SQLCIPHER_SHM_SHARED ){
35718     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
35719
35720     /* Find out which shared locks are already held by sibling connections.
35721     ** If any sibling already holds an exclusive lock, go ahead and return
35722     ** SQLCIPHER_BUSY.
35723     */
35724     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35725       if( (pX->exclMask & mask)!=0 ){
35726         rc = SQLCIPHER_BUSY;
35727         break;
35728       }
35729       allShared |= pX->sharedMask;
35730     }
35731
35732     /* Get shared locks at the system level, if necessary */
35733     if( rc==SQLCIPHER_OK ){
35734       if( (allShared & mask)==0 ){
35735         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
35736       }else{
35737         rc = SQLCIPHER_OK;
35738       }
35739     }
35740
35741     /* Get the local shared locks */
35742     if( rc==SQLCIPHER_OK ){
35743       p->sharedMask |= mask;
35744     }
35745   }else{
35746     /* Make sure no sibling connections hold locks that will block this
35747     ** lock.  If any do, return SQLCIPHER_BUSY right away.
35748     */
35749     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35750       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
35751         rc = SQLCIPHER_BUSY;
35752         break;
35753       }
35754     }
35755   
35756     /* Get the exclusive locks at the system level.  Then if successful
35757     ** also mark the local connection as being locked.
35758     */
35759     if( rc==SQLCIPHER_OK ){
35760       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
35761       if( rc==SQLCIPHER_OK ){
35762         assert( (p->sharedMask & mask)==0 );
35763         p->exclMask |= mask;
35764       }
35765     }
35766   }
35767   sqlcipher3_mutex_leave(pShmNode->mutex);
35768   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
35769            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
35770            rc ? "failed" : "ok"));
35771   return rc;
35772 }
35773
35774 /*
35775 ** Implement a memory barrier or memory fence on shared memory.  
35776 **
35777 ** All loads and stores begun before the barrier must complete before
35778 ** any load or store begun after the barrier.
35779 */
35780 static void winShmBarrier(
35781   sqlcipher3_file *fd          /* Database holding the shared memory */
35782 ){
35783   UNUSED_PARAMETER(fd);
35784   /* MemoryBarrier(); // does not work -- do not know why not */
35785   winShmEnterMutex();
35786   winShmLeaveMutex();
35787 }
35788
35789 /*
35790 ** This function is called to obtain a pointer to region iRegion of the 
35791 ** shared-memory associated with the database file fd. Shared-memory regions 
35792 ** are numbered starting from zero. Each shared-memory region is szRegion 
35793 ** bytes in size.
35794 **
35795 ** If an error occurs, an error code is returned and *pp is set to NULL.
35796 **
35797 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
35798 ** region has not been allocated (by any client, including one running in a
35799 ** separate process), then *pp is set to NULL and SQLCIPHER_OK returned. If 
35800 ** isWrite is non-zero and the requested shared-memory region has not yet 
35801 ** been allocated, it is allocated by this function.
35802 **
35803 ** If the shared-memory region has already been allocated or is allocated by
35804 ** this call as described above, then it is mapped into this processes 
35805 ** address space (if it is not already), *pp is set to point to the mapped 
35806 ** memory and SQLCIPHER_OK returned.
35807 */
35808 static int winShmMap(
35809   sqlcipher3_file *fd,               /* Handle open on database file */
35810   int iRegion,                    /* Region to retrieve */
35811   int szRegion,                   /* Size of regions */
35812   int isWrite,                    /* True to extend file if necessary */
35813   void volatile **pp              /* OUT: Mapped memory */
35814 ){
35815   winFile *pDbFd = (winFile*)fd;
35816   winShm *p = pDbFd->pShm;
35817   winShmNode *pShmNode;
35818   int rc = SQLCIPHER_OK;
35819
35820   if( !p ){
35821     rc = winOpenSharedMemory(pDbFd);
35822     if( rc!=SQLCIPHER_OK ) return rc;
35823     p = pDbFd->pShm;
35824   }
35825   pShmNode = p->pShmNode;
35826
35827   sqlcipher3_mutex_enter(pShmNode->mutex);
35828   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
35829
35830   if( pShmNode->nRegion<=iRegion ){
35831     struct ShmRegion *apNew;           /* New aRegion[] array */
35832     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
35833     sqlcipher3_int64 sz;                  /* Current size of wal-index file */
35834
35835     pShmNode->szRegion = szRegion;
35836
35837     /* The requested region is not mapped into this processes address space.
35838     ** Check to see if it has been allocated (i.e. if the wal-index file is
35839     ** large enough to contain the requested region).
35840     */
35841     rc = winFileSize((sqlcipher3_file *)&pShmNode->hFile, &sz);
35842     if( rc!=SQLCIPHER_OK ){
35843       rc = winLogError(SQLCIPHER_IOERR_SHMSIZE, "winShmMap1", pDbFd->zPath);
35844       goto shmpage_out;
35845     }
35846
35847     if( sz<nByte ){
35848       /* The requested memory region does not exist. If isWrite is set to
35849       ** zero, exit early. *pp will be set to NULL and SQLCIPHER_OK returned.
35850       **
35851       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
35852       ** the requested memory region.
35853       */
35854       if( !isWrite ) goto shmpage_out;
35855       rc = winTruncate((sqlcipher3_file *)&pShmNode->hFile, nByte);
35856       if( rc!=SQLCIPHER_OK ){
35857         rc = winLogError(SQLCIPHER_IOERR_SHMSIZE, "winShmMap2", pDbFd->zPath);
35858         goto shmpage_out;
35859       }
35860     }
35861
35862     /* Map the requested memory region into this processes address space. */
35863     apNew = (struct ShmRegion *)sqlcipher3_realloc(
35864         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
35865     );
35866     if( !apNew ){
35867       rc = SQLCIPHER_IOERR_NOMEM;
35868       goto shmpage_out;
35869     }
35870     pShmNode->aRegion = apNew;
35871
35872     while( pShmNode->nRegion<=iRegion ){
35873       HANDLE hMap;                /* file-mapping handle */
35874       void *pMap = 0;             /* Mapped memory region */
35875      
35876       hMap = CreateFileMapping(pShmNode->hFile.h, 
35877           NULL, PAGE_READWRITE, 0, nByte, NULL
35878       );
35879       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
35880                (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
35881                hMap ? "ok" : "failed"));
35882       if( hMap ){
35883         int iOffset = pShmNode->nRegion*szRegion;
35884         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
35885         pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
35886             0, iOffset - iOffsetShift, szRegion + iOffsetShift
35887         );
35888         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
35889                  (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
35890                  pMap ? "ok" : "failed"));
35891       }
35892       if( !pMap ){
35893         pShmNode->lastErrno = GetLastError();
35894         rc = winLogError(SQLCIPHER_IOERR_SHMMAP, "winShmMap3", pDbFd->zPath);
35895         if( hMap ) CloseHandle(hMap);
35896         goto shmpage_out;
35897       }
35898
35899       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
35900       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
35901       pShmNode->nRegion++;
35902     }
35903   }
35904
35905 shmpage_out:
35906   if( pShmNode->nRegion>iRegion ){
35907     int iOffset = iRegion*szRegion;
35908     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
35909     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
35910     *pp = (void *)&p[iOffsetShift];
35911   }else{
35912     *pp = 0;
35913   }
35914   sqlcipher3_mutex_leave(pShmNode->mutex);
35915   return rc;
35916 }
35917
35918 #else
35919 # define winShmMap     0
35920 # define winShmLock    0
35921 # define winShmBarrier 0
35922 # define winShmUnmap   0
35923 #endif /* #ifndef SQLCIPHER_OMIT_WAL */
35924
35925 /*
35926 ** Here ends the implementation of all sqlcipher3_file methods.
35927 **
35928 ********************** End sqlcipher3_file Methods *******************************
35929 ******************************************************************************/
35930
35931 /*
35932 ** This vector defines all the methods that can operate on an
35933 ** sqlcipher3_file for win32.
35934 */
35935 static const sqlcipher3_io_methods winIoMethod = {
35936   2,                              /* iVersion */
35937   winClose,                       /* xClose */
35938   winRead,                        /* xRead */
35939   winWrite,                       /* xWrite */
35940   winTruncate,                    /* xTruncate */
35941   winSync,                        /* xSync */
35942   winFileSize,                    /* xFileSize */
35943   winLock,                        /* xLock */
35944   winUnlock,                      /* xUnlock */
35945   winCheckReservedLock,           /* xCheckReservedLock */
35946   winFileControl,                 /* xFileControl */
35947   winSectorSize,                  /* xSectorSize */
35948   winDeviceCharacteristics,       /* xDeviceCharacteristics */
35949   winShmMap,                      /* xShmMap */
35950   winShmLock,                     /* xShmLock */
35951   winShmBarrier,                  /* xShmBarrier */
35952   winShmUnmap                     /* xShmUnmap */
35953 };
35954
35955 /****************************************************************************
35956 **************************** sqlcipher3_vfs methods ****************************
35957 **
35958 ** This division contains the implementation of methods on the
35959 ** sqlcipher3_vfs object.
35960 */
35961
35962 /*
35963 ** Convert a UTF-8 filename into whatever form the underlying
35964 ** operating system wants filenames in.  Space to hold the result
35965 ** is obtained from malloc and must be freed by the calling
35966 ** function.
35967 */
35968 static void *convertUtf8Filename(const char *zFilename){
35969   void *zConverted = 0;
35970   if( isNT() ){
35971     zConverted = utf8ToUnicode(zFilename);
35972 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
35973 */
35974 #if SQLCIPHER_OS_WINCE==0
35975   }else{
35976     zConverted = sqlcipher3_win32_utf8_to_mbcs(zFilename);
35977 #endif
35978   }
35979   /* caller will handle out of memory */
35980   return zConverted;
35981 }
35982
35983 /*
35984 ** Create a temporary file name in zBuf.  zBuf must be big enough to
35985 ** hold at pVfs->mxPathname characters.
35986 */
35987 static int getTempname(int nBuf, char *zBuf){
35988   static char zChars[] =
35989     "abcdefghijklmnopqrstuvwxyz"
35990     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
35991     "0123456789";
35992   size_t i, j;
35993   char zTempPath[MAX_PATH+1];
35994
35995   /* It's odd to simulate an io-error here, but really this is just
35996   ** using the io-error infrastructure to test that SQLite handles this
35997   ** function failing. 
35998   */
35999   SimulateIOError( return SQLCIPHER_IOERR );
36000
36001   if( sqlcipher3_temp_directory ){
36002     sqlcipher3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlcipher3_temp_directory);
36003   }else if( isNT() ){
36004     char *zMulti;
36005     WCHAR zWidePath[MAX_PATH];
36006     GetTempPathW(MAX_PATH-30, zWidePath);
36007     zMulti = unicodeToUtf8(zWidePath);
36008     if( zMulti ){
36009       sqlcipher3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
36010       free(zMulti);
36011     }else{
36012       return SQLCIPHER_NOMEM;
36013     }
36014 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
36015 ** Since the ASCII version of these Windows API do not exist for WINCE,
36016 ** it's important to not reference them for WINCE builds.
36017 */
36018 #if SQLCIPHER_OS_WINCE==0
36019   }else{
36020     char *zUtf8;
36021     char zMbcsPath[MAX_PATH];
36022     GetTempPathA(MAX_PATH-30, zMbcsPath);
36023     zUtf8 = sqlcipher3_win32_mbcs_to_utf8(zMbcsPath);
36024     if( zUtf8 ){
36025       sqlcipher3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
36026       free(zUtf8);
36027     }else{
36028       return SQLCIPHER_NOMEM;
36029     }
36030 #endif
36031   }
36032
36033   /* Check that the output buffer is large enough for the temporary file 
36034   ** name. If it is not, return SQLCIPHER_ERROR.
36035   */
36036   if( (sqlcipher3Strlen30(zTempPath) + sqlcipher3Strlen30(SQLCIPHER_TEMP_FILE_PREFIX) + 17) >= nBuf ){
36037     return SQLCIPHER_ERROR;
36038   }
36039
36040   for(i=sqlcipher3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
36041   zTempPath[i] = 0;
36042
36043   sqlcipher3_snprintf(nBuf-17, zBuf,
36044                    "%s\\"SQLCIPHER_TEMP_FILE_PREFIX, zTempPath);
36045   j = sqlcipher3Strlen30(zBuf);
36046   sqlcipher3_randomness(15, &zBuf[j]);
36047   for(i=0; i<15; i++, j++){
36048     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
36049   }
36050   zBuf[j] = 0;
36051
36052   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
36053   return SQLCIPHER_OK; 
36054 }
36055
36056 /*
36057 ** Open a file.
36058 */
36059 static int winOpen(
36060   sqlcipher3_vfs *pVfs,        /* Not used */
36061   const char *zName,        /* Name of the file (UTF-8) */
36062   sqlcipher3_file *id,         /* Write the SQLite file handle here */
36063   int flags,                /* Open mode flags */
36064   int *pOutFlags            /* Status return flags */
36065 ){
36066   HANDLE h;
36067   DWORD dwDesiredAccess;
36068   DWORD dwShareMode;
36069   DWORD dwCreationDisposition;
36070   DWORD dwFlagsAndAttributes = 0;
36071 #if SQLCIPHER_OS_WINCE
36072   int isTemp = 0;
36073 #endif
36074   winFile *pFile = (winFile*)id;
36075   void *zConverted;              /* Filename in OS encoding */
36076   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
36077   int cnt = 0;
36078
36079   /* If argument zPath is a NULL pointer, this function is required to open
36080   ** a temporary file. Use this buffer to store the file name in.
36081   */
36082   char zTmpname[MAX_PATH+1];     /* Buffer used to create temp filename */
36083
36084   int rc = SQLCIPHER_OK;            /* Function Return Code */
36085 #if !defined(NDEBUG) || SQLCIPHER_OS_WINCE
36086   int eType = flags&0xFFFFFF00;  /* Type of file to open */
36087 #endif
36088
36089   int isExclusive  = (flags & SQLCIPHER_OPEN_EXCLUSIVE);
36090   int isDelete     = (flags & SQLCIPHER_OPEN_DELETEONCLOSE);
36091   int isCreate     = (flags & SQLCIPHER_OPEN_CREATE);
36092 #ifndef NDEBUG
36093   int isReadonly   = (flags & SQLCIPHER_OPEN_READONLY);
36094 #endif
36095   int isReadWrite  = (flags & SQLCIPHER_OPEN_READWRITE);
36096
36097 #ifndef NDEBUG
36098   int isOpenJournal = (isCreate && (
36099         eType==SQLCIPHER_OPEN_MASTER_JOURNAL 
36100      || eType==SQLCIPHER_OPEN_MAIN_JOURNAL 
36101      || eType==SQLCIPHER_OPEN_WAL
36102   ));
36103 #endif
36104
36105   /* Check the following statements are true: 
36106   **
36107   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
36108   **   (b) if CREATE is set, then READWRITE must also be set, and
36109   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
36110   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
36111   */
36112   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
36113   assert(isCreate==0 || isReadWrite);
36114   assert(isExclusive==0 || isCreate);
36115   assert(isDelete==0 || isCreate);
36116
36117   /* The main DB, main journal, WAL file and master journal are never 
36118   ** automatically deleted. Nor are they ever temporary files.  */
36119   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MAIN_DB );
36120   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MAIN_JOURNAL );
36121   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MASTER_JOURNAL );
36122   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_WAL );
36123
36124   /* Assert that the upper layer has set one of the "file-type" flags. */
36125   assert( eType==SQLCIPHER_OPEN_MAIN_DB      || eType==SQLCIPHER_OPEN_TEMP_DB 
36126        || eType==SQLCIPHER_OPEN_MAIN_JOURNAL || eType==SQLCIPHER_OPEN_TEMP_JOURNAL 
36127        || eType==SQLCIPHER_OPEN_SUBJOURNAL   || eType==SQLCIPHER_OPEN_MASTER_JOURNAL 
36128        || eType==SQLCIPHER_OPEN_TRANSIENT_DB || eType==SQLCIPHER_OPEN_WAL
36129   );
36130
36131   assert( id!=0 );
36132   UNUSED_PARAMETER(pVfs);
36133
36134   pFile->h = INVALID_HANDLE_VALUE;
36135
36136   /* If the second argument to this function is NULL, generate a 
36137   ** temporary file name to use 
36138   */
36139   if( !zUtf8Name ){
36140     assert(isDelete && !isOpenJournal);
36141     rc = getTempname(MAX_PATH+1, zTmpname);
36142     if( rc!=SQLCIPHER_OK ){
36143       return rc;
36144     }
36145     zUtf8Name = zTmpname;
36146   }
36147
36148   /* Convert the filename to the system encoding. */
36149   zConverted = convertUtf8Filename(zUtf8Name);
36150   if( zConverted==0 ){
36151     return SQLCIPHER_NOMEM;
36152   }
36153
36154   if( isReadWrite ){
36155     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
36156   }else{
36157     dwDesiredAccess = GENERIC_READ;
36158   }
36159
36160   /* SQLCIPHER_OPEN_EXCLUSIVE is used to make sure that a new file is 
36161   ** created. SQLite doesn't use it to indicate "exclusive access" 
36162   ** as it is usually understood.
36163   */
36164   if( isExclusive ){
36165     /* Creates a new file, only if it does not already exist. */
36166     /* If the file exists, it fails. */
36167     dwCreationDisposition = CREATE_NEW;
36168   }else if( isCreate ){
36169     /* Open existing file, or create if it doesn't exist */
36170     dwCreationDisposition = OPEN_ALWAYS;
36171   }else{
36172     /* Opens a file, only if it exists. */
36173     dwCreationDisposition = OPEN_EXISTING;
36174   }
36175
36176   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
36177
36178   if( isDelete ){
36179 #if SQLCIPHER_OS_WINCE
36180     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
36181     isTemp = 1;
36182 #else
36183     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
36184                                | FILE_ATTRIBUTE_HIDDEN
36185                                | FILE_FLAG_DELETE_ON_CLOSE;
36186 #endif
36187   }else{
36188     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
36189   }
36190   /* Reports from the internet are that performance is always
36191   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
36192 #if SQLCIPHER_OS_WINCE
36193   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
36194 #endif
36195
36196   if( isNT() ){
36197     while( (h = CreateFileW((WCHAR*)zConverted,
36198                             dwDesiredAccess,
36199                             dwShareMode, NULL,
36200                             dwCreationDisposition,
36201                             dwFlagsAndAttributes,
36202                             NULL))==INVALID_HANDLE_VALUE &&
36203                             retryIoerr(&cnt) ){}
36204 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
36205 ** Since the ASCII version of these Windows API do not exist for WINCE,
36206 ** it's important to not reference them for WINCE builds.
36207 */
36208 #if SQLCIPHER_OS_WINCE==0
36209   }else{
36210     while( (h = CreateFileA((char*)zConverted,
36211                             dwDesiredAccess,
36212                             dwShareMode, NULL,
36213                             dwCreationDisposition,
36214                             dwFlagsAndAttributes,
36215                             NULL))==INVALID_HANDLE_VALUE &&
36216                             retryIoerr(&cnt) ){}
36217 #endif
36218   }
36219
36220   logIoerr(cnt);
36221
36222   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
36223            h, zName, dwDesiredAccess, 
36224            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
36225
36226   if( h==INVALID_HANDLE_VALUE ){
36227     pFile->lastErrno = GetLastError();
36228     winLogError(SQLCIPHER_CANTOPEN, "winOpen", zUtf8Name);
36229     free(zConverted);
36230     if( isReadWrite && !isExclusive ){
36231       return winOpen(pVfs, zName, id, 
36232              ((flags|SQLCIPHER_OPEN_READONLY)&~(SQLCIPHER_OPEN_CREATE|SQLCIPHER_OPEN_READWRITE)), pOutFlags);
36233     }else{
36234       return SQLCIPHER_CANTOPEN_BKPT;
36235     }
36236   }
36237
36238   if( pOutFlags ){
36239     if( isReadWrite ){
36240       *pOutFlags = SQLCIPHER_OPEN_READWRITE;
36241     }else{
36242       *pOutFlags = SQLCIPHER_OPEN_READONLY;
36243     }
36244   }
36245
36246   memset(pFile, 0, sizeof(*pFile));
36247   pFile->pMethod = &winIoMethod;
36248   pFile->h = h;
36249   pFile->lastErrno = NO_ERROR;
36250   pFile->pVfs = pVfs;
36251   pFile->pShm = 0;
36252   pFile->zPath = zName;
36253   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
36254
36255 #if SQLCIPHER_OS_WINCE
36256   if( isReadWrite && eType==SQLCIPHER_OPEN_MAIN_DB
36257        && !winceCreateLock(zName, pFile)
36258   ){
36259     CloseHandle(h);
36260     free(zConverted);
36261     return SQLCIPHER_CANTOPEN_BKPT;
36262   }
36263   if( isTemp ){
36264     pFile->zDeleteOnClose = zConverted;
36265   }else
36266 #endif
36267   {
36268     free(zConverted);
36269   }
36270
36271   OpenCounter(+1);
36272   return rc;
36273 }
36274
36275 /*
36276 ** Delete the named file.
36277 **
36278 ** Note that windows does not allow a file to be deleted if some other
36279 ** process has it open.  Sometimes a virus scanner or indexing program
36280 ** will open a journal file shortly after it is created in order to do
36281 ** whatever it does.  While this other process is holding the
36282 ** file open, we will be unable to delete it.  To work around this
36283 ** problem, we delay 100 milliseconds and try to delete again.  Up
36284 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
36285 ** up and returning an error.
36286 */
36287 static int winDelete(
36288   sqlcipher3_vfs *pVfs,          /* Not used on win32 */
36289   const char *zFilename,      /* Name of file to delete */
36290   int syncDir                 /* Not used on win32 */
36291 ){
36292   int cnt = 0;
36293   int rc;
36294   void *zConverted;
36295   UNUSED_PARAMETER(pVfs);
36296   UNUSED_PARAMETER(syncDir);
36297
36298   SimulateIOError(return SQLCIPHER_IOERR_DELETE);
36299   zConverted = convertUtf8Filename(zFilename);
36300   if( zConverted==0 ){
36301     return SQLCIPHER_NOMEM;
36302   }
36303   if( isNT() ){
36304     rc = 1;
36305     while( GetFileAttributesW(zConverted)!=INVALID_FILE_ATTRIBUTES &&
36306            (rc = DeleteFileW(zConverted))==0 && retryIoerr(&cnt) ){}
36307     rc = rc ? SQLCIPHER_OK : SQLCIPHER_ERROR;
36308 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
36309 ** Since the ASCII version of these Windows API do not exist for WINCE,
36310 ** it's important to not reference them for WINCE builds.
36311 */
36312 #if SQLCIPHER_OS_WINCE==0
36313   }else{
36314     rc = 1;
36315     while( GetFileAttributesA(zConverted)!=INVALID_FILE_ATTRIBUTES &&
36316            (rc = DeleteFileA(zConverted))==0 && retryIoerr(&cnt) ){}
36317     rc = rc ? SQLCIPHER_OK : SQLCIPHER_ERROR;
36318 #endif
36319   }
36320   if( rc ){
36321     rc = winLogError(SQLCIPHER_IOERR_DELETE, "winDelete", zFilename);
36322   }else{
36323     logIoerr(cnt);
36324   }
36325   free(zConverted);
36326   OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
36327   return rc;
36328 }
36329
36330 /*
36331 ** Check the existance and status of a file.
36332 */
36333 static int winAccess(
36334   sqlcipher3_vfs *pVfs,         /* Not used on win32 */
36335   const char *zFilename,     /* Name of file to check */
36336   int flags,                 /* Type of test to make on this file */
36337   int *pResOut               /* OUT: Result */
36338 ){
36339   DWORD attr;
36340   int rc = 0;
36341   void *zConverted;
36342   UNUSED_PARAMETER(pVfs);
36343
36344   SimulateIOError( return SQLCIPHER_IOERR_ACCESS; );
36345   zConverted = convertUtf8Filename(zFilename);
36346   if( zConverted==0 ){
36347     return SQLCIPHER_NOMEM;
36348   }
36349   if( isNT() ){
36350     int cnt = 0;
36351     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
36352     memset(&sAttrData, 0, sizeof(sAttrData));
36353     while( !(rc = GetFileAttributesExW((WCHAR*)zConverted,
36354                              GetFileExInfoStandard, 
36355                              &sAttrData)) && retryIoerr(&cnt) ){}
36356     if( rc ){
36357       /* For an SQLCIPHER_ACCESS_EXISTS query, treat a zero-length file
36358       ** as if it does not exist.
36359       */
36360       if(    flags==SQLCIPHER_ACCESS_EXISTS
36361           && sAttrData.nFileSizeHigh==0 
36362           && sAttrData.nFileSizeLow==0 ){
36363         attr = INVALID_FILE_ATTRIBUTES;
36364       }else{
36365         attr = sAttrData.dwFileAttributes;
36366       }
36367     }else{
36368       logIoerr(cnt);
36369       if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
36370         winLogError(SQLCIPHER_IOERR_ACCESS, "winAccess", zFilename);
36371         free(zConverted);
36372         return SQLCIPHER_IOERR_ACCESS;
36373       }else{
36374         attr = INVALID_FILE_ATTRIBUTES;
36375       }
36376     }
36377 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
36378 ** Since the ASCII version of these Windows API do not exist for WINCE,
36379 ** it's important to not reference them for WINCE builds.
36380 */
36381 #if SQLCIPHER_OS_WINCE==0
36382   }else{
36383     attr = GetFileAttributesA((char*)zConverted);
36384 #endif
36385   }
36386   free(zConverted);
36387   switch( flags ){
36388     case SQLCIPHER_ACCESS_READ:
36389     case SQLCIPHER_ACCESS_EXISTS:
36390       rc = attr!=INVALID_FILE_ATTRIBUTES;
36391       break;
36392     case SQLCIPHER_ACCESS_READWRITE:
36393       rc = attr!=INVALID_FILE_ATTRIBUTES &&
36394              (attr & FILE_ATTRIBUTE_READONLY)==0;
36395       break;
36396     default:
36397       assert(!"Invalid flags argument");
36398   }
36399   *pResOut = rc;
36400   return SQLCIPHER_OK;
36401 }
36402
36403
36404 /*
36405 ** Turn a relative pathname into a full pathname.  Write the full
36406 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
36407 ** bytes in size.
36408 */
36409 static int winFullPathname(
36410   sqlcipher3_vfs *pVfs,            /* Pointer to vfs object */
36411   const char *zRelative,        /* Possibly relative input path */
36412   int nFull,                    /* Size of output buffer in bytes */
36413   char *zFull                   /* Output buffer */
36414 ){
36415   
36416 #if defined(__CYGWIN__)
36417   SimulateIOError( return SQLCIPHER_ERROR );
36418   UNUSED_PARAMETER(nFull);
36419   cygwin_conv_to_full_win32_path(zRelative, zFull);
36420   return SQLCIPHER_OK;
36421 #endif
36422
36423 #if SQLCIPHER_OS_WINCE
36424   SimulateIOError( return SQLCIPHER_ERROR );
36425   UNUSED_PARAMETER(nFull);
36426   /* WinCE has no concept of a relative pathname, or so I am told. */
36427   sqlcipher3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
36428   return SQLCIPHER_OK;
36429 #endif
36430
36431 #if !SQLCIPHER_OS_WINCE && !defined(__CYGWIN__)
36432   int nByte;
36433   void *zConverted;
36434   char *zOut;
36435
36436   /* If this path name begins with "/X:", where "X" is any alphabetic
36437   ** character, discard the initial "/" from the pathname.
36438   */
36439   if( zRelative[0]=='/' && sqlcipher3Isalpha(zRelative[1]) && zRelative[2]==':' ){
36440     zRelative++;
36441   }
36442
36443   /* It's odd to simulate an io-error here, but really this is just
36444   ** using the io-error infrastructure to test that SQLite handles this
36445   ** function failing. This function could fail if, for example, the
36446   ** current working directory has been unlinked.
36447   */
36448   SimulateIOError( return SQLCIPHER_ERROR );
36449   UNUSED_PARAMETER(nFull);
36450   zConverted = convertUtf8Filename(zRelative);
36451   if( isNT() ){
36452     WCHAR *zTemp;
36453     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
36454     zTemp = malloc( nByte*sizeof(zTemp[0]) );
36455     if( zTemp==0 ){
36456       free(zConverted);
36457       return SQLCIPHER_NOMEM;
36458     }
36459     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
36460     free(zConverted);
36461     zOut = unicodeToUtf8(zTemp);
36462     free(zTemp);
36463 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
36464 ** Since the ASCII version of these Windows API do not exist for WINCE,
36465 ** it's important to not reference them for WINCE builds.
36466 */
36467 #if SQLCIPHER_OS_WINCE==0
36468   }else{
36469     char *zTemp;
36470     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
36471     zTemp = malloc( nByte*sizeof(zTemp[0]) );
36472     if( zTemp==0 ){
36473       free(zConverted);
36474       return SQLCIPHER_NOMEM;
36475     }
36476     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
36477     free(zConverted);
36478     zOut = sqlcipher3_win32_mbcs_to_utf8(zTemp);
36479     free(zTemp);
36480 #endif
36481   }
36482   if( zOut ){
36483     sqlcipher3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
36484     free(zOut);
36485     return SQLCIPHER_OK;
36486   }else{
36487     return SQLCIPHER_NOMEM;
36488   }
36489 #endif
36490 }
36491
36492 /*
36493 ** Get the sector size of the device used to store
36494 ** file.
36495 */
36496 static int getSectorSize(
36497     sqlcipher3_vfs *pVfs,
36498     const char *zRelative     /* UTF-8 file name */
36499 ){
36500   DWORD bytesPerSector = SQLCIPHER_DEFAULT_SECTOR_SIZE;
36501   /* GetDiskFreeSpace is not supported under WINCE */
36502 #if SQLCIPHER_OS_WINCE
36503   UNUSED_PARAMETER(pVfs);
36504   UNUSED_PARAMETER(zRelative);
36505 #else
36506   char zFullpath[MAX_PATH+1];
36507   int rc;
36508   DWORD dwRet = 0;
36509   DWORD dwDummy;
36510
36511   /*
36512   ** We need to get the full path name of the file
36513   ** to get the drive letter to look up the sector
36514   ** size.
36515   */
36516   SimulateIOErrorBenign(1);
36517   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
36518   SimulateIOErrorBenign(0);
36519   if( rc == SQLCIPHER_OK )
36520   {
36521     void *zConverted = convertUtf8Filename(zFullpath);
36522     if( zConverted ){
36523       if( isNT() ){
36524         /* trim path to just drive reference */
36525         WCHAR *p = zConverted;
36526         for(;*p;p++){
36527           if( *p == '\\' ){
36528             *p = '\0';
36529             break;
36530           }
36531         }
36532         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
36533                                   &dwDummy,
36534                                   &bytesPerSector,
36535                                   &dwDummy,
36536                                   &dwDummy);
36537       }else{
36538         /* trim path to just drive reference */
36539         char *p = (char *)zConverted;
36540         for(;*p;p++){
36541           if( *p == '\\' ){
36542             *p = '\0';
36543             break;
36544           }
36545         }
36546         dwRet = GetDiskFreeSpaceA((char*)zConverted,
36547                                   &dwDummy,
36548                                   &bytesPerSector,
36549                                   &dwDummy,
36550                                   &dwDummy);
36551       }
36552       free(zConverted);
36553     }
36554     if( !dwRet ){
36555       bytesPerSector = SQLCIPHER_DEFAULT_SECTOR_SIZE;
36556     }
36557   }
36558 #endif
36559   return (int) bytesPerSector; 
36560 }
36561
36562 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
36563 /*
36564 ** Interfaces for opening a shared library, finding entry points
36565 ** within the shared library, and closing the shared library.
36566 */
36567 /*
36568 ** Interfaces for opening a shared library, finding entry points
36569 ** within the shared library, and closing the shared library.
36570 */
36571 static void *winDlOpen(sqlcipher3_vfs *pVfs, const char *zFilename){
36572   HANDLE h;
36573   void *zConverted = convertUtf8Filename(zFilename);
36574   UNUSED_PARAMETER(pVfs);
36575   if( zConverted==0 ){
36576     return 0;
36577   }
36578   if( isNT() ){
36579     h = LoadLibraryW((WCHAR*)zConverted);
36580 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
36581 ** Since the ASCII version of these Windows API do not exist for WINCE,
36582 ** it's important to not reference them for WINCE builds.
36583 */
36584 #if SQLCIPHER_OS_WINCE==0
36585   }else{
36586     h = LoadLibraryA((char*)zConverted);
36587 #endif
36588   }
36589   free(zConverted);
36590   return (void*)h;
36591 }
36592 static void winDlError(sqlcipher3_vfs *pVfs, int nBuf, char *zBufOut){
36593   UNUSED_PARAMETER(pVfs);
36594   getLastErrorMsg(nBuf, zBufOut);
36595 }
36596 static void (*winDlSym(sqlcipher3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
36597   UNUSED_PARAMETER(pVfs);
36598 #if SQLCIPHER_OS_WINCE
36599   /* The GetProcAddressA() routine is only available on wince. */
36600   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
36601 #else
36602   /* All other windows platforms expect GetProcAddress() to take
36603   ** an Ansi string regardless of the _UNICODE setting */
36604   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
36605 #endif
36606 }
36607 static void winDlClose(sqlcipher3_vfs *pVfs, void *pHandle){
36608   UNUSED_PARAMETER(pVfs);
36609   FreeLibrary((HANDLE)pHandle);
36610 }
36611 #else /* if SQLCIPHER_OMIT_LOAD_EXTENSION is defined: */
36612   #define winDlOpen  0
36613   #define winDlError 0
36614   #define winDlSym   0
36615   #define winDlClose 0
36616 #endif
36617
36618
36619 /*
36620 ** Write up to nBuf bytes of randomness into zBuf.
36621 */
36622 static int winRandomness(sqlcipher3_vfs *pVfs, int nBuf, char *zBuf){
36623   int n = 0;
36624   UNUSED_PARAMETER(pVfs);
36625 #if defined(SQLCIPHER_TEST)
36626   n = nBuf;
36627   memset(zBuf, 0, nBuf);
36628 #else
36629   if( sizeof(SYSTEMTIME)<=nBuf-n ){
36630     SYSTEMTIME x;
36631     GetSystemTime(&x);
36632     memcpy(&zBuf[n], &x, sizeof(x));
36633     n += sizeof(x);
36634   }
36635   if( sizeof(DWORD)<=nBuf-n ){
36636     DWORD pid = GetCurrentProcessId();
36637     memcpy(&zBuf[n], &pid, sizeof(pid));
36638     n += sizeof(pid);
36639   }
36640   if( sizeof(DWORD)<=nBuf-n ){
36641     DWORD cnt = GetTickCount();
36642     memcpy(&zBuf[n], &cnt, sizeof(cnt));
36643     n += sizeof(cnt);
36644   }
36645   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
36646     LARGE_INTEGER i;
36647     QueryPerformanceCounter(&i);
36648     memcpy(&zBuf[n], &i, sizeof(i));
36649     n += sizeof(i);
36650   }
36651 #endif
36652   return n;
36653 }
36654
36655
36656 /*
36657 ** Sleep for a little while.  Return the amount of time slept.
36658 */
36659 static int winSleep(sqlcipher3_vfs *pVfs, int microsec){
36660   Sleep((microsec+999)/1000);
36661   UNUSED_PARAMETER(pVfs);
36662   return ((microsec+999)/1000)*1000;
36663 }
36664
36665 /*
36666 ** The following variable, if set to a non-zero value, is interpreted as
36667 ** the number of seconds since 1970 and is used to set the result of
36668 ** sqlcipher3OsCurrentTime() during testing.
36669 */
36670 #ifdef SQLCIPHER_TEST
36671 SQLCIPHER_API int sqlcipher3_current_time = 0;  /* Fake system time in seconds since 1970. */
36672 #endif
36673
36674 /*
36675 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
36676 ** the current time and date as a Julian Day number times 86_400_000.  In
36677 ** other words, write into *piNow the number of milliseconds since the Julian
36678 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
36679 ** proleptic Gregorian calendar.
36680 **
36681 ** On success, return SQLCIPHER_OK.  Return SQLCIPHER_ERROR if the time and date 
36682 ** cannot be found.
36683 */
36684 static int winCurrentTimeInt64(sqlcipher3_vfs *pVfs, sqlcipher3_int64 *piNow){
36685   /* FILETIME structure is a 64-bit value representing the number of 
36686      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
36687   */
36688   FILETIME ft;
36689   static const sqlcipher3_int64 winFiletimeEpoch = 23058135*(sqlcipher3_int64)8640000;
36690 #ifdef SQLCIPHER_TEST
36691   static const sqlcipher3_int64 unixEpoch = 24405875*(sqlcipher3_int64)8640000;
36692 #endif
36693   /* 2^32 - to avoid use of LL and warnings in gcc */
36694   static const sqlcipher3_int64 max32BitValue = 
36695       (sqlcipher3_int64)2000000000 + (sqlcipher3_int64)2000000000 + (sqlcipher3_int64)294967296;
36696
36697 #if SQLCIPHER_OS_WINCE
36698   SYSTEMTIME time;
36699   GetSystemTime(&time);
36700   /* if SystemTimeToFileTime() fails, it returns zero. */
36701   if (!SystemTimeToFileTime(&time,&ft)){
36702     return SQLCIPHER_ERROR;
36703   }
36704 #else
36705   GetSystemTimeAsFileTime( &ft );
36706 #endif
36707
36708   *piNow = winFiletimeEpoch +
36709             ((((sqlcipher3_int64)ft.dwHighDateTime)*max32BitValue) + 
36710                (sqlcipher3_int64)ft.dwLowDateTime)/(sqlcipher3_int64)10000;
36711
36712 #ifdef SQLCIPHER_TEST
36713   if( sqlcipher3_current_time ){
36714     *piNow = 1000*(sqlcipher3_int64)sqlcipher3_current_time + unixEpoch;
36715   }
36716 #endif
36717   UNUSED_PARAMETER(pVfs);
36718   return SQLCIPHER_OK;
36719 }
36720
36721 /*
36722 ** Find the current time (in Universal Coordinated Time).  Write the
36723 ** current time and date as a Julian Day number into *prNow and
36724 ** return 0.  Return 1 if the time and date cannot be found.
36725 */
36726 static int winCurrentTime(sqlcipher3_vfs *pVfs, double *prNow){
36727   int rc;
36728   sqlcipher3_int64 i;
36729   rc = winCurrentTimeInt64(pVfs, &i);
36730   if( !rc ){
36731     *prNow = i/86400000.0;
36732   }
36733   return rc;
36734 }
36735
36736 /*
36737 ** The idea is that this function works like a combination of
36738 ** GetLastError() and FormatMessage() on windows (or errno and
36739 ** strerror_r() on unix). After an error is returned by an OS
36740 ** function, SQLite calls this function with zBuf pointing to
36741 ** a buffer of nBuf bytes. The OS layer should populate the
36742 ** buffer with a nul-terminated UTF-8 encoded error message
36743 ** describing the last IO error to have occurred within the calling
36744 ** thread.
36745 **
36746 ** If the error message is too large for the supplied buffer,
36747 ** it should be truncated. The return value of xGetLastError
36748 ** is zero if the error message fits in the buffer, or non-zero
36749 ** otherwise (if the message was truncated). If non-zero is returned,
36750 ** then it is not necessary to include the nul-terminator character
36751 ** in the output buffer.
36752 **
36753 ** Not supplying an error message will have no adverse effect
36754 ** on SQLite. It is fine to have an implementation that never
36755 ** returns an error message:
36756 **
36757 **   int xGetLastError(sqlcipher3_vfs *pVfs, int nBuf, char *zBuf){
36758 **     assert(zBuf[0]=='\0');
36759 **     return 0;
36760 **   }
36761 **
36762 ** However if an error message is supplied, it will be incorporated
36763 ** by sqlcipher into the error message available to the user using
36764 ** sqlcipher3_errmsg(), possibly making IO errors easier to debug.
36765 */
36766 static int winGetLastError(sqlcipher3_vfs *pVfs, int nBuf, char *zBuf){
36767   UNUSED_PARAMETER(pVfs);
36768   return getLastErrorMsg(nBuf, zBuf);
36769 }
36770
36771
36772
36773 /*
36774 ** Initialize and deinitialize the operating system interface.
36775 */
36776 SQLCIPHER_API int sqlcipher3_os_init(void){
36777   static sqlcipher3_vfs winVfs = {
36778     3,                   /* iVersion */
36779     sizeof(winFile),     /* szOsFile */
36780     MAX_PATH,            /* mxPathname */
36781     0,                   /* pNext */
36782     "win32",             /* zName */
36783     0,                   /* pAppData */
36784     winOpen,             /* xOpen */
36785     winDelete,           /* xDelete */
36786     winAccess,           /* xAccess */
36787     winFullPathname,     /* xFullPathname */
36788     winDlOpen,           /* xDlOpen */
36789     winDlError,          /* xDlError */
36790     winDlSym,            /* xDlSym */
36791     winDlClose,          /* xDlClose */
36792     winRandomness,       /* xRandomness */
36793     winSleep,            /* xSleep */
36794     winCurrentTime,      /* xCurrentTime */
36795     winGetLastError,     /* xGetLastError */
36796     winCurrentTimeInt64, /* xCurrentTimeInt64 */
36797     0,                   /* xSetSystemCall */
36798     0,                   /* xGetSystemCall */
36799     0,                   /* xNextSystemCall */
36800   };
36801
36802 #ifndef SQLCIPHER_OMIT_WAL
36803   /* get memory map allocation granularity */
36804   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
36805   GetSystemInfo(&winSysInfo);
36806   assert(winSysInfo.dwAllocationGranularity > 0);
36807 #endif
36808
36809   sqlcipher3_vfs_register(&winVfs, 1);
36810   return SQLCIPHER_OK; 
36811 }
36812 SQLCIPHER_API int sqlcipher3_os_end(void){ 
36813   return SQLCIPHER_OK;
36814 }
36815
36816 #endif /* SQLCIPHER_OS_WIN */
36817
36818 /************** End of os_win.c **********************************************/
36819 /************** Begin file bitvec.c ******************************************/
36820 /*
36821 ** 2008 February 16
36822 **
36823 ** The author disclaims copyright to this source code.  In place of
36824 ** a legal notice, here is a blessing:
36825 **
36826 **    May you do good and not evil.
36827 **    May you find forgiveness for yourself and forgive others.
36828 **    May you share freely, never taking more than you give.
36829 **
36830 *************************************************************************
36831 ** This file implements an object that represents a fixed-length
36832 ** bitmap.  Bits are numbered starting with 1.
36833 **
36834 ** A bitmap is used to record which pages of a database file have been
36835 ** journalled during a transaction, or which pages have the "dont-write"
36836 ** property.  Usually only a few pages are meet either condition.
36837 ** So the bitmap is usually sparse and has low cardinality.
36838 ** But sometimes (for example when during a DROP of a large table) most
36839 ** or all of the pages in a database can get journalled.  In those cases, 
36840 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
36841 ** to handle both cases well.
36842 **
36843 ** The size of the bitmap is fixed when the object is created.
36844 **
36845 ** All bits are clear when the bitmap is created.  Individual bits
36846 ** may be set or cleared one at a time.
36847 **
36848 ** Test operations are about 100 times more common that set operations.
36849 ** Clear operations are exceedingly rare.  There are usually between
36850 ** 5 and 500 set operations per Bitvec object, though the number of sets can
36851 ** sometimes grow into tens of thousands or larger.  The size of the
36852 ** Bitvec object is the number of pages in the database file at the
36853 ** start of a transaction, and is thus usually less than a few thousand,
36854 ** but can be as large as 2 billion for a really big database.
36855 */
36856
36857 /* Size of the Bitvec structure in bytes. */
36858 #define BITVEC_SZ        512
36859
36860 /* Round the union size down to the nearest pointer boundary, since that's how 
36861 ** it will be aligned within the Bitvec struct. */
36862 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
36863
36864 /* Type of the array "element" for the bitmap representation. 
36865 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
36866 ** Setting this to the "natural word" size of your CPU may improve
36867 ** performance. */
36868 #define BITVEC_TELEM     u8
36869 /* Size, in bits, of the bitmap element. */
36870 #define BITVEC_SZELEM    8
36871 /* Number of elements in a bitmap array. */
36872 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
36873 /* Number of bits in the bitmap array. */
36874 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
36875
36876 /* Number of u32 values in hash table. */
36877 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
36878 /* Maximum number of entries in hash table before 
36879 ** sub-dividing and re-hashing. */
36880 #define BITVEC_MXHASH    (BITVEC_NINT/2)
36881 /* Hashing function for the aHash representation.
36882 ** Empirical testing showed that the *37 multiplier 
36883 ** (an arbitrary prime)in the hash function provided 
36884 ** no fewer collisions than the no-op *1. */
36885 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
36886
36887 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
36888
36889
36890 /*
36891 ** A bitmap is an instance of the following structure.
36892 **
36893 ** This bitmap records the existance of zero or more bits
36894 ** with values between 1 and iSize, inclusive.
36895 **
36896 ** There are three possible representations of the bitmap.
36897 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
36898 ** bitmap.  The least significant bit is bit 1.
36899 **
36900 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
36901 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
36902 **
36903 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
36904 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
36905 ** handles up to iDivisor separate values of i.  apSub[0] holds
36906 ** values between 1 and iDivisor.  apSub[1] holds values between
36907 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
36908 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
36909 ** to hold deal with values between 1 and iDivisor.
36910 */
36911 struct Bitvec {
36912   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
36913   u32 nSet;       /* Number of bits that are set - only valid for aHash
36914                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
36915                   ** this would be 125. */
36916   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
36917                   /* Should >=0 for apSub element. */
36918                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
36919                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
36920   union {
36921     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
36922     u32 aHash[BITVEC_NINT];      /* Hash table representation */
36923     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
36924   } u;
36925 };
36926
36927 /*
36928 ** Create a new bitmap object able to handle bits between 0 and iSize,
36929 ** inclusive.  Return a pointer to the new object.  Return NULL if 
36930 ** malloc fails.
36931 */
36932 SQLCIPHER_PRIVATE Bitvec *sqlcipher3BitvecCreate(u32 iSize){
36933   Bitvec *p;
36934   assert( sizeof(*p)==BITVEC_SZ );
36935   p = sqlcipher3MallocZero( sizeof(*p) );
36936   if( p ){
36937     p->iSize = iSize;
36938   }
36939   return p;
36940 }
36941
36942 /*
36943 ** Check to see if the i-th bit is set.  Return true or false.
36944 ** If p is NULL (if the bitmap has not been created) or if
36945 ** i is out of range, then return false.
36946 */
36947 SQLCIPHER_PRIVATE int sqlcipher3BitvecTest(Bitvec *p, u32 i){
36948   if( p==0 ) return 0;
36949   if( i>p->iSize || i==0 ) return 0;
36950   i--;
36951   while( p->iDivisor ){
36952     u32 bin = i/p->iDivisor;
36953     i = i%p->iDivisor;
36954     p = p->u.apSub[bin];
36955     if (!p) {
36956       return 0;
36957     }
36958   }
36959   if( p->iSize<=BITVEC_NBIT ){
36960     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
36961   } else{
36962     u32 h = BITVEC_HASH(i++);
36963     while( p->u.aHash[h] ){
36964       if( p->u.aHash[h]==i ) return 1;
36965       h = (h+1) % BITVEC_NINT;
36966     }
36967     return 0;
36968   }
36969 }
36970
36971 /*
36972 ** Set the i-th bit.  Return 0 on success and an error code if
36973 ** anything goes wrong.
36974 **
36975 ** This routine might cause sub-bitmaps to be allocated.  Failing
36976 ** to get the memory needed to hold the sub-bitmap is the only
36977 ** that can go wrong with an insert, assuming p and i are valid.
36978 **
36979 ** The calling function must ensure that p is a valid Bitvec object
36980 ** and that the value for "i" is within range of the Bitvec object.
36981 ** Otherwise the behavior is undefined.
36982 */
36983 SQLCIPHER_PRIVATE int sqlcipher3BitvecSet(Bitvec *p, u32 i){
36984   u32 h;
36985   if( p==0 ) return SQLCIPHER_OK;
36986   assert( i>0 );
36987   assert( i<=p->iSize );
36988   i--;
36989   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
36990     u32 bin = i/p->iDivisor;
36991     i = i%p->iDivisor;
36992     if( p->u.apSub[bin]==0 ){
36993       p->u.apSub[bin] = sqlcipher3BitvecCreate( p->iDivisor );
36994       if( p->u.apSub[bin]==0 ) return SQLCIPHER_NOMEM;
36995     }
36996     p = p->u.apSub[bin];
36997   }
36998   if( p->iSize<=BITVEC_NBIT ){
36999     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
37000     return SQLCIPHER_OK;
37001   }
37002   h = BITVEC_HASH(i++);
37003   /* if there wasn't a hash collision, and this doesn't */
37004   /* completely fill the hash, then just add it without */
37005   /* worring about sub-dividing and re-hashing. */
37006   if( !p->u.aHash[h] ){
37007     if (p->nSet<(BITVEC_NINT-1)) {
37008       goto bitvec_set_end;
37009     } else {
37010       goto bitvec_set_rehash;
37011     }
37012   }
37013   /* there was a collision, check to see if it's already */
37014   /* in hash, if not, try to find a spot for it */
37015   do {
37016     if( p->u.aHash[h]==i ) return SQLCIPHER_OK;
37017     h++;
37018     if( h>=BITVEC_NINT ) h = 0;
37019   } while( p->u.aHash[h] );
37020   /* we didn't find it in the hash.  h points to the first */
37021   /* available free spot. check to see if this is going to */
37022   /* make our hash too "full".  */
37023 bitvec_set_rehash:
37024   if( p->nSet>=BITVEC_MXHASH ){
37025     unsigned int j;
37026     int rc;
37027     u32 *aiValues = sqlcipher3StackAllocRaw(0, sizeof(p->u.aHash));
37028     if( aiValues==0 ){
37029       return SQLCIPHER_NOMEM;
37030     }else{
37031       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
37032       memset(p->u.apSub, 0, sizeof(p->u.apSub));
37033       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
37034       rc = sqlcipher3BitvecSet(p, i);
37035       for(j=0; j<BITVEC_NINT; j++){
37036         if( aiValues[j] ) rc |= sqlcipher3BitvecSet(p, aiValues[j]);
37037       }
37038       sqlcipher3StackFree(0, aiValues);
37039       return rc;
37040     }
37041   }
37042 bitvec_set_end:
37043   p->nSet++;
37044   p->u.aHash[h] = i;
37045   return SQLCIPHER_OK;
37046 }
37047
37048 /*
37049 ** Clear the i-th bit.
37050 **
37051 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
37052 ** that BitvecClear can use to rebuilt its hash table.
37053 */
37054 SQLCIPHER_PRIVATE void sqlcipher3BitvecClear(Bitvec *p, u32 i, void *pBuf){
37055   if( p==0 ) return;
37056   assert( i>0 );
37057   i--;
37058   while( p->iDivisor ){
37059     u32 bin = i/p->iDivisor;
37060     i = i%p->iDivisor;
37061     p = p->u.apSub[bin];
37062     if (!p) {
37063       return;
37064     }
37065   }
37066   if( p->iSize<=BITVEC_NBIT ){
37067     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
37068   }else{
37069     unsigned int j;
37070     u32 *aiValues = pBuf;
37071     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
37072     memset(p->u.aHash, 0, sizeof(p->u.aHash));
37073     p->nSet = 0;
37074     for(j=0; j<BITVEC_NINT; j++){
37075       if( aiValues[j] && aiValues[j]!=(i+1) ){
37076         u32 h = BITVEC_HASH(aiValues[j]-1);
37077         p->nSet++;
37078         while( p->u.aHash[h] ){
37079           h++;
37080           if( h>=BITVEC_NINT ) h = 0;
37081         }
37082         p->u.aHash[h] = aiValues[j];
37083       }
37084     }
37085   }
37086 }
37087
37088 /*
37089 ** Destroy a bitmap object.  Reclaim all memory used.
37090 */
37091 SQLCIPHER_PRIVATE void sqlcipher3BitvecDestroy(Bitvec *p){
37092   if( p==0 ) return;
37093   if( p->iDivisor ){
37094     unsigned int i;
37095     for(i=0; i<BITVEC_NPTR; i++){
37096       sqlcipher3BitvecDestroy(p->u.apSub[i]);
37097     }
37098   }
37099   sqlcipher3_free(p);
37100 }
37101
37102 /*
37103 ** Return the value of the iSize parameter specified when Bitvec *p
37104 ** was created.
37105 */
37106 SQLCIPHER_PRIVATE u32 sqlcipher3BitvecSize(Bitvec *p){
37107   return p->iSize;
37108 }
37109
37110 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
37111 /*
37112 ** Let V[] be an array of unsigned characters sufficient to hold
37113 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
37114 ** Then the following macros can be used to set, clear, or test
37115 ** individual bits within V.
37116 */
37117 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
37118 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
37119 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
37120
37121 /*
37122 ** This routine runs an extensive test of the Bitvec code.
37123 **
37124 ** The input is an array of integers that acts as a program
37125 ** to test the Bitvec.  The integers are opcodes followed
37126 ** by 0, 1, or 3 operands, depending on the opcode.  Another
37127 ** opcode follows immediately after the last operand.
37128 **
37129 ** There are 6 opcodes numbered from 0 through 5.  0 is the
37130 ** "halt" opcode and causes the test to end.
37131 **
37132 **    0          Halt and return the number of errors
37133 **    1 N S X    Set N bits beginning with S and incrementing by X
37134 **    2 N S X    Clear N bits beginning with S and incrementing by X
37135 **    3 N        Set N randomly chosen bits
37136 **    4 N        Clear N randomly chosen bits
37137 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
37138 **
37139 ** The opcodes 1 through 4 perform set and clear operations are performed
37140 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
37141 ** Opcode 5 works on the linear array only, not on the Bitvec.
37142 ** Opcode 5 is used to deliberately induce a fault in order to
37143 ** confirm that error detection works.
37144 **
37145 ** At the conclusion of the test the linear array is compared
37146 ** against the Bitvec object.  If there are any differences,
37147 ** an error is returned.  If they are the same, zero is returned.
37148 **
37149 ** If a memory allocation error occurs, return -1.
37150 */
37151 SQLCIPHER_PRIVATE int sqlcipher3BitvecBuiltinTest(int sz, int *aOp){
37152   Bitvec *pBitvec = 0;
37153   unsigned char *pV = 0;
37154   int rc = -1;
37155   int i, nx, pc, op;
37156   void *pTmpSpace;
37157
37158   /* Allocate the Bitvec to be tested and a linear array of
37159   ** bits to act as the reference */
37160   pBitvec = sqlcipher3BitvecCreate( sz );
37161   pV = sqlcipher3_malloc( (sz+7)/8 + 1 );
37162   pTmpSpace = sqlcipher3_malloc(BITVEC_SZ);
37163   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
37164   memset(pV, 0, (sz+7)/8 + 1);
37165
37166   /* NULL pBitvec tests */
37167   sqlcipher3BitvecSet(0, 1);
37168   sqlcipher3BitvecClear(0, 1, pTmpSpace);
37169
37170   /* Run the program */
37171   pc = 0;
37172   while( (op = aOp[pc])!=0 ){
37173     switch( op ){
37174       case 1:
37175       case 2:
37176       case 5: {
37177         nx = 4;
37178         i = aOp[pc+2] - 1;
37179         aOp[pc+2] += aOp[pc+3];
37180         break;
37181       }
37182       case 3:
37183       case 4: 
37184       default: {
37185         nx = 2;
37186         sqlcipher3_randomness(sizeof(i), &i);
37187         break;
37188       }
37189     }
37190     if( (--aOp[pc+1]) > 0 ) nx = 0;
37191     pc += nx;
37192     i = (i & 0x7fffffff)%sz;
37193     if( (op & 1)!=0 ){
37194       SETBIT(pV, (i+1));
37195       if( op!=5 ){
37196         if( sqlcipher3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
37197       }
37198     }else{
37199       CLEARBIT(pV, (i+1));
37200       sqlcipher3BitvecClear(pBitvec, i+1, pTmpSpace);
37201     }
37202   }
37203
37204   /* Test to make sure the linear array exactly matches the
37205   ** Bitvec object.  Start with the assumption that they do
37206   ** match (rc==0).  Change rc to non-zero if a discrepancy
37207   ** is found.
37208   */
37209   rc = sqlcipher3BitvecTest(0,0) + sqlcipher3BitvecTest(pBitvec, sz+1)
37210           + sqlcipher3BitvecTest(pBitvec, 0)
37211           + (sqlcipher3BitvecSize(pBitvec) - sz);
37212   for(i=1; i<=sz; i++){
37213     if(  (TESTBIT(pV,i))!=sqlcipher3BitvecTest(pBitvec,i) ){
37214       rc = i;
37215       break;
37216     }
37217   }
37218
37219   /* Free allocated structure */
37220 bitvec_end:
37221   sqlcipher3_free(pTmpSpace);
37222   sqlcipher3_free(pV);
37223   sqlcipher3BitvecDestroy(pBitvec);
37224   return rc;
37225 }
37226 #endif /* SQLCIPHER_OMIT_BUILTIN_TEST */
37227
37228 /************** End of bitvec.c **********************************************/
37229 /************** Begin file pcache.c ******************************************/
37230 /*
37231 ** 2008 August 05
37232 **
37233 ** The author disclaims copyright to this source code.  In place of
37234 ** a legal notice, here is a blessing:
37235 **
37236 **    May you do good and not evil.
37237 **    May you find forgiveness for yourself and forgive others.
37238 **    May you share freely, never taking more than you give.
37239 **
37240 *************************************************************************
37241 ** This file implements that page cache.
37242 */
37243
37244 /*
37245 ** A complete page cache is an instance of this structure.
37246 */
37247 struct PCache {
37248   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
37249   PgHdr *pSynced;                     /* Last synced page in dirty page list */
37250   int nRef;                           /* Number of referenced pages */
37251   int nMax;                           /* Configured cache size */
37252   int szPage;                         /* Size of every page in this cache */
37253   int szExtra;                        /* Size of extra space for each page */
37254   int bPurgeable;                     /* True if pages are on backing store */
37255   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
37256   void *pStress;                      /* Argument to xStress */
37257   sqlcipher3_pcache *pCache;             /* Pluggable cache module */
37258   PgHdr *pPage1;                      /* Reference to page 1 */
37259 };
37260
37261 /*
37262 ** Some of the assert() macros in this code are too expensive to run
37263 ** even during normal debugging.  Use them only rarely on long-running
37264 ** tests.  Enable the expensive asserts using the
37265 ** -DSQLCIPHER_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
37266 */
37267 #ifdef SQLCIPHER_ENABLE_EXPENSIVE_ASSERT
37268 # define expensive_assert(X)  assert(X)
37269 #else
37270 # define expensive_assert(X)
37271 #endif
37272
37273 /********************************** Linked List Management ********************/
37274
37275 #if !defined(NDEBUG) && defined(SQLCIPHER_ENABLE_EXPENSIVE_ASSERT)
37276 /*
37277 ** Check that the pCache->pSynced variable is set correctly. If it
37278 ** is not, either fail an assert or return zero. Otherwise, return
37279 ** non-zero. This is only used in debugging builds, as follows:
37280 **
37281 **   expensive_assert( pcacheCheckSynced(pCache) );
37282 */
37283 static int pcacheCheckSynced(PCache *pCache){
37284   PgHdr *p;
37285   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
37286     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
37287   }
37288   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
37289 }
37290 #endif /* !NDEBUG && SQLCIPHER_ENABLE_EXPENSIVE_ASSERT */
37291
37292 /*
37293 ** Remove page pPage from the list of dirty pages.
37294 */
37295 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
37296   PCache *p = pPage->pCache;
37297
37298   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
37299   assert( pPage->pDirtyPrev || pPage==p->pDirty );
37300
37301   /* Update the PCache1.pSynced variable if necessary. */
37302   if( p->pSynced==pPage ){
37303     PgHdr *pSynced = pPage->pDirtyPrev;
37304     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
37305       pSynced = pSynced->pDirtyPrev;
37306     }
37307     p->pSynced = pSynced;
37308   }
37309
37310   if( pPage->pDirtyNext ){
37311     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
37312   }else{
37313     assert( pPage==p->pDirtyTail );
37314     p->pDirtyTail = pPage->pDirtyPrev;
37315   }
37316   if( pPage->pDirtyPrev ){
37317     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
37318   }else{
37319     assert( pPage==p->pDirty );
37320     p->pDirty = pPage->pDirtyNext;
37321   }
37322   pPage->pDirtyNext = 0;
37323   pPage->pDirtyPrev = 0;
37324
37325   expensive_assert( pcacheCheckSynced(p) );
37326 }
37327
37328 /*
37329 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
37330 ** pPage).
37331 */
37332 static void pcacheAddToDirtyList(PgHdr *pPage){
37333   PCache *p = pPage->pCache;
37334
37335   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
37336
37337   pPage->pDirtyNext = p->pDirty;
37338   if( pPage->pDirtyNext ){
37339     assert( pPage->pDirtyNext->pDirtyPrev==0 );
37340     pPage->pDirtyNext->pDirtyPrev = pPage;
37341   }
37342   p->pDirty = pPage;
37343   if( !p->pDirtyTail ){
37344     p->pDirtyTail = pPage;
37345   }
37346   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
37347     p->pSynced = pPage;
37348   }
37349   expensive_assert( pcacheCheckSynced(p) );
37350 }
37351
37352 /*
37353 ** Wrapper around the pluggable caches xUnpin method. If the cache is
37354 ** being used for an in-memory database, this function is a no-op.
37355 */
37356 static void pcacheUnpin(PgHdr *p){
37357   PCache *pCache = p->pCache;
37358   if( pCache->bPurgeable ){
37359     if( p->pgno==1 ){
37360       pCache->pPage1 = 0;
37361     }
37362     sqlcipher3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
37363   }
37364 }
37365
37366 /*************************************************** General Interfaces ******
37367 **
37368 ** Initialize and shutdown the page cache subsystem. Neither of these 
37369 ** functions are threadsafe.
37370 */
37371 SQLCIPHER_PRIVATE int sqlcipher3PcacheInitialize(void){
37372   if( sqlcipher3GlobalConfig.pcache.xInit==0 ){
37373     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
37374     ** built-in default page cache is used instead of the application defined
37375     ** page cache. */
37376     sqlcipher3PCacheSetDefault();
37377   }
37378   return sqlcipher3GlobalConfig.pcache.xInit(sqlcipher3GlobalConfig.pcache.pArg);
37379 }
37380 SQLCIPHER_PRIVATE void sqlcipher3PcacheShutdown(void){
37381   if( sqlcipher3GlobalConfig.pcache.xShutdown ){
37382     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
37383     sqlcipher3GlobalConfig.pcache.xShutdown(sqlcipher3GlobalConfig.pcache.pArg);
37384   }
37385 }
37386
37387 /*
37388 ** Return the size in bytes of a PCache object.
37389 */
37390 SQLCIPHER_PRIVATE int sqlcipher3PcacheSize(void){ return sizeof(PCache); }
37391
37392 /*
37393 ** Create a new PCache object. Storage space to hold the object
37394 ** has already been allocated and is passed in as the p pointer. 
37395 ** The caller discovers how much space needs to be allocated by 
37396 ** calling sqlcipher3PcacheSize().
37397 */
37398 SQLCIPHER_PRIVATE void sqlcipher3PcacheOpen(
37399   int szPage,                  /* Size of every page */
37400   int szExtra,                 /* Extra space associated with each page */
37401   int bPurgeable,              /* True if pages are on backing store */
37402   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
37403   void *pStress,               /* Argument to xStress */
37404   PCache *p                    /* Preallocated space for the PCache */
37405 ){
37406   memset(p, 0, sizeof(PCache));
37407   p->szPage = szPage;
37408   p->szExtra = szExtra;
37409   p->bPurgeable = bPurgeable;
37410   p->xStress = xStress;
37411   p->pStress = pStress;
37412   p->nMax = 100;
37413 }
37414
37415 /*
37416 ** Change the page size for PCache object. The caller must ensure that there
37417 ** are no outstanding page references when this function is called.
37418 */
37419 SQLCIPHER_PRIVATE void sqlcipher3PcacheSetPageSize(PCache *pCache, int szPage){
37420   assert( pCache->nRef==0 && pCache->pDirty==0 );
37421   if( pCache->pCache ){
37422     sqlcipher3GlobalConfig.pcache.xDestroy(pCache->pCache);
37423     pCache->pCache = 0;
37424     pCache->pPage1 = 0;
37425   }
37426   pCache->szPage = szPage;
37427 }
37428
37429 /*
37430 ** Try to obtain a page from the cache.
37431 */
37432 SQLCIPHER_PRIVATE int sqlcipher3PcacheFetch(
37433   PCache *pCache,       /* Obtain the page from this cache */
37434   Pgno pgno,            /* Page number to obtain */
37435   int createFlag,       /* If true, create page if it does not exist already */
37436   PgHdr **ppPage        /* Write the page here */
37437 ){
37438   PgHdr *pPage = 0;
37439   int eCreate;
37440
37441   assert( pCache!=0 );
37442   assert( createFlag==1 || createFlag==0 );
37443   assert( pgno>0 );
37444
37445   /* If the pluggable cache (sqlcipher3_pcache*) has not been allocated,
37446   ** allocate it now.
37447   */
37448   if( !pCache->pCache && createFlag ){
37449     sqlcipher3_pcache *p;
37450     int nByte;
37451     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
37452     p = sqlcipher3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
37453     if( !p ){
37454       return SQLCIPHER_NOMEM;
37455     }
37456     sqlcipher3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
37457     pCache->pCache = p;
37458   }
37459
37460   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
37461   if( pCache->pCache ){
37462     pPage = sqlcipher3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
37463   }
37464
37465   if( !pPage && eCreate==1 ){
37466     PgHdr *pPg;
37467
37468     /* Find a dirty page to write-out and recycle. First try to find a 
37469     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
37470     ** cleared), but if that is not possible settle for any other 
37471     ** unreferenced dirty page.
37472     */
37473     expensive_assert( pcacheCheckSynced(pCache) );
37474     for(pPg=pCache->pSynced; 
37475         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
37476         pPg=pPg->pDirtyPrev
37477     );
37478     pCache->pSynced = pPg;
37479     if( !pPg ){
37480       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
37481     }
37482     if( pPg ){
37483       int rc;
37484 #ifdef SQLCIPHER_LOG_CACHE_SPILL
37485       sqlcipher3_log(SQLCIPHER_FULL, 
37486                   "spill page %d making room for %d - cache used: %d/%d",
37487                   pPg->pgno, pgno,
37488                   sqlcipher3GlobalConfig.pcache.xPagecount(pCache->pCache),
37489                   pCache->nMax);
37490 #endif
37491       rc = pCache->xStress(pCache->pStress, pPg);
37492       if( rc!=SQLCIPHER_OK && rc!=SQLCIPHER_BUSY ){
37493         return rc;
37494       }
37495     }
37496
37497     pPage = sqlcipher3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
37498   }
37499
37500   if( pPage ){
37501     if( !pPage->pData ){
37502       memset(pPage, 0, sizeof(PgHdr));
37503       pPage->pData = (void *)&pPage[1];
37504       pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
37505       memset(pPage->pExtra, 0, pCache->szExtra);
37506       pPage->pCache = pCache;
37507       pPage->pgno = pgno;
37508     }
37509     assert( pPage->pCache==pCache );
37510     assert( pPage->pgno==pgno );
37511     assert( pPage->pData==(void *)&pPage[1] );
37512     assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
37513
37514     if( 0==pPage->nRef ){
37515       pCache->nRef++;
37516     }
37517     pPage->nRef++;
37518     if( pgno==1 ){
37519       pCache->pPage1 = pPage;
37520     }
37521   }
37522   *ppPage = pPage;
37523   return (pPage==0 && eCreate) ? SQLCIPHER_NOMEM : SQLCIPHER_OK;
37524 }
37525
37526 /*
37527 ** Decrement the reference count on a page. If the page is clean and the
37528 ** reference count drops to 0, then it is made elible for recycling.
37529 */
37530 SQLCIPHER_PRIVATE void sqlcipher3PcacheRelease(PgHdr *p){
37531   assert( p->nRef>0 );
37532   p->nRef--;
37533   if( p->nRef==0 ){
37534     PCache *pCache = p->pCache;
37535     pCache->nRef--;
37536     if( (p->flags&PGHDR_DIRTY)==0 ){
37537       pcacheUnpin(p);
37538     }else{
37539       /* Move the page to the head of the dirty list. */
37540       pcacheRemoveFromDirtyList(p);
37541       pcacheAddToDirtyList(p);
37542     }
37543   }
37544 }
37545
37546 /*
37547 ** Increase the reference count of a supplied page by 1.
37548 */
37549 SQLCIPHER_PRIVATE void sqlcipher3PcacheRef(PgHdr *p){
37550   assert(p->nRef>0);
37551   p->nRef++;
37552 }
37553
37554 /*
37555 ** Drop a page from the cache. There must be exactly one reference to the
37556 ** page. This function deletes that reference, so after it returns the
37557 ** page pointed to by p is invalid.
37558 */
37559 SQLCIPHER_PRIVATE void sqlcipher3PcacheDrop(PgHdr *p){
37560   PCache *pCache;
37561   assert( p->nRef==1 );
37562   if( p->flags&PGHDR_DIRTY ){
37563     pcacheRemoveFromDirtyList(p);
37564   }
37565   pCache = p->pCache;
37566   pCache->nRef--;
37567   if( p->pgno==1 ){
37568     pCache->pPage1 = 0;
37569   }
37570   sqlcipher3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
37571 }
37572
37573 /*
37574 ** Make sure the page is marked as dirty. If it isn't dirty already,
37575 ** make it so.
37576 */
37577 SQLCIPHER_PRIVATE void sqlcipher3PcacheMakeDirty(PgHdr *p){
37578   p->flags &= ~PGHDR_DONT_WRITE;
37579   assert( p->nRef>0 );
37580   if( 0==(p->flags & PGHDR_DIRTY) ){
37581     p->flags |= PGHDR_DIRTY;
37582     pcacheAddToDirtyList( p);
37583   }
37584 }
37585
37586 /*
37587 ** Make sure the page is marked as clean. If it isn't clean already,
37588 ** make it so.
37589 */
37590 SQLCIPHER_PRIVATE void sqlcipher3PcacheMakeClean(PgHdr *p){
37591   if( (p->flags & PGHDR_DIRTY) ){
37592     pcacheRemoveFromDirtyList(p);
37593     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
37594     if( p->nRef==0 ){
37595       pcacheUnpin(p);
37596     }
37597   }
37598 }
37599
37600 /*
37601 ** Make every page in the cache clean.
37602 */
37603 SQLCIPHER_PRIVATE void sqlcipher3PcacheCleanAll(PCache *pCache){
37604   PgHdr *p;
37605   while( (p = pCache->pDirty)!=0 ){
37606     sqlcipher3PcacheMakeClean(p);
37607   }
37608 }
37609
37610 /*
37611 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
37612 */
37613 SQLCIPHER_PRIVATE void sqlcipher3PcacheClearSyncFlags(PCache *pCache){
37614   PgHdr *p;
37615   for(p=pCache->pDirty; p; p=p->pDirtyNext){
37616     p->flags &= ~PGHDR_NEED_SYNC;
37617   }
37618   pCache->pSynced = pCache->pDirtyTail;
37619 }
37620
37621 /*
37622 ** Change the page number of page p to newPgno. 
37623 */
37624 SQLCIPHER_PRIVATE void sqlcipher3PcacheMove(PgHdr *p, Pgno newPgno){
37625   PCache *pCache = p->pCache;
37626   assert( p->nRef>0 );
37627   assert( newPgno>0 );
37628   sqlcipher3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
37629   p->pgno = newPgno;
37630   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
37631     pcacheRemoveFromDirtyList(p);
37632     pcacheAddToDirtyList(p);
37633   }
37634 }
37635
37636 /*
37637 ** Drop every cache entry whose page number is greater than "pgno". The
37638 ** caller must ensure that there are no outstanding references to any pages
37639 ** other than page 1 with a page number greater than pgno.
37640 **
37641 ** If there is a reference to page 1 and the pgno parameter passed to this
37642 ** function is 0, then the data area associated with page 1 is zeroed, but
37643 ** the page object is not dropped.
37644 */
37645 SQLCIPHER_PRIVATE void sqlcipher3PcacheTruncate(PCache *pCache, Pgno pgno){
37646   if( pCache->pCache ){
37647     PgHdr *p;
37648     PgHdr *pNext;
37649     for(p=pCache->pDirty; p; p=pNext){
37650       pNext = p->pDirtyNext;
37651       /* This routine never gets call with a positive pgno except right
37652       ** after sqlcipher3PcacheCleanAll().  So if there are dirty pages,
37653       ** it must be that pgno==0.
37654       */
37655       assert( p->pgno>0 );
37656       if( ALWAYS(p->pgno>pgno) ){
37657         assert( p->flags&PGHDR_DIRTY );
37658         sqlcipher3PcacheMakeClean(p);
37659       }
37660     }
37661     if( pgno==0 && pCache->pPage1 ){
37662       memset(pCache->pPage1->pData, 0, pCache->szPage);
37663       pgno = 1;
37664     }
37665     sqlcipher3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
37666   }
37667 }
37668
37669 /*
37670 ** Close a cache.
37671 */
37672 SQLCIPHER_PRIVATE void sqlcipher3PcacheClose(PCache *pCache){
37673   if( pCache->pCache ){
37674     sqlcipher3GlobalConfig.pcache.xDestroy(pCache->pCache);
37675   }
37676 }
37677
37678 /* 
37679 ** Discard the contents of the cache.
37680 */
37681 SQLCIPHER_PRIVATE void sqlcipher3PcacheClear(PCache *pCache){
37682   sqlcipher3PcacheTruncate(pCache, 0);
37683 }
37684
37685 /*
37686 ** Merge two lists of pages connected by pDirty and in pgno order.
37687 ** Do not both fixing the pDirtyPrev pointers.
37688 */
37689 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
37690   PgHdr result, *pTail;
37691   pTail = &result;
37692   while( pA && pB ){
37693     if( pA->pgno<pB->pgno ){
37694       pTail->pDirty = pA;
37695       pTail = pA;
37696       pA = pA->pDirty;
37697     }else{
37698       pTail->pDirty = pB;
37699       pTail = pB;
37700       pB = pB->pDirty;
37701     }
37702   }
37703   if( pA ){
37704     pTail->pDirty = pA;
37705   }else if( pB ){
37706     pTail->pDirty = pB;
37707   }else{
37708     pTail->pDirty = 0;
37709   }
37710   return result.pDirty;
37711 }
37712
37713 /*
37714 ** Sort the list of pages in accending order by pgno.  Pages are
37715 ** connected by pDirty pointers.  The pDirtyPrev pointers are
37716 ** corrupted by this sort.
37717 **
37718 ** Since there cannot be more than 2^31 distinct pages in a database,
37719 ** there cannot be more than 31 buckets required by the merge sorter.
37720 ** One extra bucket is added to catch overflow in case something
37721 ** ever changes to make the previous sentence incorrect.
37722 */
37723 #define N_SORT_BUCKET  32
37724 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
37725   PgHdr *a[N_SORT_BUCKET], *p;
37726   int i;
37727   memset(a, 0, sizeof(a));
37728   while( pIn ){
37729     p = pIn;
37730     pIn = p->pDirty;
37731     p->pDirty = 0;
37732     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
37733       if( a[i]==0 ){
37734         a[i] = p;
37735         break;
37736       }else{
37737         p = pcacheMergeDirtyList(a[i], p);
37738         a[i] = 0;
37739       }
37740     }
37741     if( NEVER(i==N_SORT_BUCKET-1) ){
37742       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
37743       ** the input list.  But that is impossible.
37744       */
37745       a[i] = pcacheMergeDirtyList(a[i], p);
37746     }
37747   }
37748   p = a[0];
37749   for(i=1; i<N_SORT_BUCKET; i++){
37750     p = pcacheMergeDirtyList(p, a[i]);
37751   }
37752   return p;
37753 }
37754
37755 /*
37756 ** Return a list of all dirty pages in the cache, sorted by page number.
37757 */
37758 SQLCIPHER_PRIVATE PgHdr *sqlcipher3PcacheDirtyList(PCache *pCache){
37759   PgHdr *p;
37760   for(p=pCache->pDirty; p; p=p->pDirtyNext){
37761     p->pDirty = p->pDirtyNext;
37762   }
37763   return pcacheSortDirtyList(pCache->pDirty);
37764 }
37765
37766 /* 
37767 ** Return the total number of referenced pages held by the cache.
37768 */
37769 SQLCIPHER_PRIVATE int sqlcipher3PcacheRefCount(PCache *pCache){
37770   return pCache->nRef;
37771 }
37772
37773 /*
37774 ** Return the number of references to the page supplied as an argument.
37775 */
37776 SQLCIPHER_PRIVATE int sqlcipher3PcachePageRefcount(PgHdr *p){
37777   return p->nRef;
37778 }
37779
37780 /* 
37781 ** Return the total number of pages in the cache.
37782 */
37783 SQLCIPHER_PRIVATE int sqlcipher3PcachePagecount(PCache *pCache){
37784   int nPage = 0;
37785   if( pCache->pCache ){
37786     nPage = sqlcipher3GlobalConfig.pcache.xPagecount(pCache->pCache);
37787   }
37788   return nPage;
37789 }
37790
37791 #ifdef SQLCIPHER_TEST
37792 /*
37793 ** Get the suggested cache-size value.
37794 */
37795 SQLCIPHER_PRIVATE int sqlcipher3PcacheGetCachesize(PCache *pCache){
37796   return pCache->nMax;
37797 }
37798 #endif
37799
37800 /*
37801 ** Set the suggested cache-size value.
37802 */
37803 SQLCIPHER_PRIVATE void sqlcipher3PcacheSetCachesize(PCache *pCache, int mxPage){
37804   pCache->nMax = mxPage;
37805   if( pCache->pCache ){
37806     sqlcipher3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
37807   }
37808 }
37809
37810 #if defined(SQLCIPHER_CHECK_PAGES) || defined(SQLCIPHER_DEBUG)
37811 /*
37812 ** For all dirty pages currently in the cache, invoke the specified
37813 ** callback. This is only used if the SQLCIPHER_CHECK_PAGES macro is
37814 ** defined.
37815 */
37816 SQLCIPHER_PRIVATE void sqlcipher3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
37817   PgHdr *pDirty;
37818   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
37819     xIter(pDirty);
37820   }
37821 }
37822 #endif
37823
37824 /************** End of pcache.c **********************************************/
37825 /************** Begin file pcache1.c *****************************************/
37826 /*
37827 ** 2008 November 05
37828 **
37829 ** The author disclaims copyright to this source code.  In place of
37830 ** a legal notice, here is a blessing:
37831 **
37832 **    May you do good and not evil.
37833 **    May you find forgiveness for yourself and forgive others.
37834 **    May you share freely, never taking more than you give.
37835 **
37836 *************************************************************************
37837 **
37838 ** This file implements the default page cache implementation (the
37839 ** sqlcipher3_pcache interface). It also contains part of the implementation
37840 ** of the SQLCIPHER_CONFIG_PAGECACHE and sqlcipher3_release_memory() features.
37841 ** If the default page cache implementation is overriden, then neither of
37842 ** these two features are available.
37843 */
37844
37845
37846 typedef struct PCache1 PCache1;
37847 typedef struct PgHdr1 PgHdr1;
37848 typedef struct PgFreeslot PgFreeslot;
37849 typedef struct PGroup PGroup;
37850
37851
37852 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
37853 ** of one or more PCaches that are able to recycle each others unpinned
37854 ** pages when they are under memory pressure.  A PGroup is an instance of
37855 ** the following object.
37856 **
37857 ** This page cache implementation works in one of two modes:
37858 **
37859 **   (1)  Every PCache is the sole member of its own PGroup.  There is
37860 **        one PGroup per PCache.
37861 **
37862 **   (2)  There is a single global PGroup that all PCaches are a member
37863 **        of.
37864 **
37865 ** Mode 1 uses more memory (since PCache instances are not able to rob
37866 ** unused pages from other PCaches) but it also operates without a mutex,
37867 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
37868 ** threadsafe, but is able recycle pages more efficient.
37869 **
37870 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
37871 ** PGroup which is the pcache1.grp global variable and its mutex is
37872 ** SQLCIPHER_MUTEX_STATIC_LRU.
37873 */
37874 struct PGroup {
37875   sqlcipher3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
37876   int nMaxPage;                  /* Sum of nMax for purgeable caches */
37877   int nMinPage;                  /* Sum of nMin for purgeable caches */
37878   int mxPinned;                  /* nMaxpage + 10 - nMinPage */
37879   int nCurrentPage;              /* Number of purgeable pages allocated */
37880   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
37881 };
37882
37883 /* Each page cache is an instance of the following object.  Every
37884 ** open database file (including each in-memory database and each
37885 ** temporary or transient database) has a single page cache which
37886 ** is an instance of this object.
37887 **
37888 ** Pointers to structures of this type are cast and returned as 
37889 ** opaque sqlcipher3_pcache* handles.
37890 */
37891 struct PCache1 {
37892   /* Cache configuration parameters. Page size (szPage) and the purgeable
37893   ** flag (bPurgeable) are set when the cache is created. nMax may be 
37894   ** modified at any time by a call to the pcache1CacheSize() method.
37895   ** The PGroup mutex must be held when accessing nMax.
37896   */
37897   PGroup *pGroup;                     /* PGroup this cache belongs to */
37898   int szPage;                         /* Size of allocated pages in bytes */
37899   int bPurgeable;                     /* True if cache is purgeable */
37900   unsigned int nMin;                  /* Minimum number of pages reserved */
37901   unsigned int nMax;                  /* Configured "cache_size" value */
37902   unsigned int n90pct;                /* nMax*9/10 */
37903
37904   /* Hash table of all pages. The following variables may only be accessed
37905   ** when the accessor is holding the PGroup mutex.
37906   */
37907   unsigned int nRecyclable;           /* Number of pages in the LRU list */
37908   unsigned int nPage;                 /* Total number of pages in apHash */
37909   unsigned int nHash;                 /* Number of slots in apHash[] */
37910   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
37911
37912   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
37913 };
37914
37915 /*
37916 ** Each cache entry is represented by an instance of the following 
37917 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
37918 ** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
37919 ** macro below).
37920 */
37921 struct PgHdr1 {
37922   unsigned int iKey;             /* Key value (page number) */
37923   PgHdr1 *pNext;                 /* Next in hash table chain */
37924   PCache1 *pCache;               /* Cache that currently owns this page */
37925   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
37926   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
37927 };
37928
37929 /*
37930 ** Free slots in the allocator used to divide up the buffer provided using
37931 ** the SQLCIPHER_CONFIG_PAGECACHE mechanism.
37932 */
37933 struct PgFreeslot {
37934   PgFreeslot *pNext;  /* Next free slot */
37935 };
37936
37937 /*
37938 ** Global data used by this cache.
37939 */
37940 static SQLCIPHER_WSD struct PCacheGlobal {
37941   PGroup grp;                    /* The global PGroup for mode (2) */
37942
37943   /* Variables related to SQLCIPHER_CONFIG_PAGECACHE settings.  The
37944   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
37945   ** fixed at sqlcipher3_initialize() time and do not require mutex protection.
37946   ** The nFreeSlot and pFree values do require mutex protection.
37947   */
37948   int isInit;                    /* True if initialized */
37949   int szSlot;                    /* Size of each free slot */
37950   int nSlot;                     /* The number of pcache slots */
37951   int nReserve;                  /* Try to keep nFreeSlot above this */
37952   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
37953   /* Above requires no mutex.  Use mutex below for variable that follow. */
37954   sqlcipher3_mutex *mutex;          /* Mutex for accessing the following: */
37955   int nFreeSlot;                 /* Number of unused pcache slots */
37956   PgFreeslot *pFree;             /* Free page blocks */
37957   /* The following value requires a mutex to change.  We skip the mutex on
37958   ** reading because (1) most platforms read a 32-bit integer atomically and
37959   ** (2) even if an incorrect value is read, no great harm is done since this
37960   ** is really just an optimization. */
37961   int bUnderPressure;            /* True if low on PAGECACHE memory */
37962 } pcache1_g;
37963
37964 /*
37965 ** All code in this file should access the global structure above via the
37966 ** alias "pcache1". This ensures that the WSD emulation is used when
37967 ** compiling for systems that do not support real WSD.
37968 */
37969 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
37970
37971 /*
37972 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
37973 ** bytes of data are located directly before it in memory (i.e. the total
37974 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
37975 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
37976 ** an argument and returns a pointer to the associated block of szPage
37977 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
37978 ** a pointer to a block of szPage bytes of data and the return value is
37979 ** a pointer to the associated PgHdr1 structure.
37980 **
37981 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
37982 */
37983 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
37984 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
37985
37986 /*
37987 ** Macros to enter and leave the PCache LRU mutex.
37988 */
37989 #define pcache1EnterMutex(X) sqlcipher3_mutex_enter((X)->mutex)
37990 #define pcache1LeaveMutex(X) sqlcipher3_mutex_leave((X)->mutex)
37991
37992 /******************************************************************************/
37993 /******** Page Allocation/SQLCIPHER_CONFIG_PCACHE Related Functions **************/
37994
37995 /*
37996 ** This function is called during initialization if a static buffer is 
37997 ** supplied to use for the page-cache by passing the SQLCIPHER_CONFIG_PAGECACHE
37998 ** verb to sqlcipher3_config(). Parameter pBuf points to an allocation large
37999 ** enough to contain 'n' buffers of 'sz' bytes each.
38000 **
38001 ** This routine is called from sqlcipher3_initialize() and so it is guaranteed
38002 ** to be serialized already.  There is no need for further mutexing.
38003 */
38004 SQLCIPHER_PRIVATE void sqlcipher3PCacheBufferSetup(void *pBuf, int sz, int n){
38005   if( pcache1.isInit ){
38006     PgFreeslot *p;
38007     sz = ROUNDDOWN8(sz);
38008     pcache1.szSlot = sz;
38009     pcache1.nSlot = pcache1.nFreeSlot = n;
38010     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
38011     pcache1.pStart = pBuf;
38012     pcache1.pFree = 0;
38013     pcache1.bUnderPressure = 0;
38014     while( n-- ){
38015       p = (PgFreeslot*)pBuf;
38016       p->pNext = pcache1.pFree;
38017       pcache1.pFree = p;
38018       pBuf = (void*)&((char*)pBuf)[sz];
38019     }
38020     pcache1.pEnd = pBuf;
38021   }
38022 }
38023
38024 /*
38025 ** Malloc function used within this file to allocate space from the buffer
38026 ** configured using sqlcipher3_config(SQLCIPHER_CONFIG_PAGECACHE) option. If no 
38027 ** such buffer exists or there is no space left in it, this function falls 
38028 ** back to sqlcipher3Malloc().
38029 **
38030 ** Multiple threads can run this routine at the same time.  Global variables
38031 ** in pcache1 need to be protected via mutex.
38032 */
38033 static void *pcache1Alloc(int nByte){
38034   void *p = 0;
38035   assert( sqlcipher3_mutex_notheld(pcache1.grp.mutex) );
38036   sqlcipher3StatusSet(SQLCIPHER_STATUS_PAGECACHE_SIZE, nByte);
38037   if( nByte<=pcache1.szSlot ){
38038     sqlcipher3_mutex_enter(pcache1.mutex);
38039     p = (PgHdr1 *)pcache1.pFree;
38040     if( p ){
38041       pcache1.pFree = pcache1.pFree->pNext;
38042       pcache1.nFreeSlot--;
38043       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
38044       assert( pcache1.nFreeSlot>=0 );
38045       sqlcipher3StatusAdd(SQLCIPHER_STATUS_PAGECACHE_USED, 1);
38046     }
38047     sqlcipher3_mutex_leave(pcache1.mutex);
38048   }
38049   if( p==0 ){
38050     /* Memory is not available in the SQLCIPHER_CONFIG_PAGECACHE pool.  Get
38051     ** it from sqlcipher3Malloc instead.
38052     */
38053     p = sqlcipher3Malloc(nByte);
38054     if( p ){
38055       int sz = sqlcipher3MallocSize(p);
38056       sqlcipher3_mutex_enter(pcache1.mutex);
38057       sqlcipher3StatusAdd(SQLCIPHER_STATUS_PAGECACHE_OVERFLOW, sz);
38058       sqlcipher3_mutex_leave(pcache1.mutex);
38059     }
38060     sqlcipher3MemdebugSetType(p, MEMTYPE_PCACHE);
38061   }
38062   return p;
38063 }
38064
38065 /*
38066 ** Free an allocated buffer obtained from pcache1Alloc().
38067 */
38068 static void pcache1Free(void *p){
38069   if( p==0 ) return;
38070   if( p>=pcache1.pStart && p<pcache1.pEnd ){
38071     PgFreeslot *pSlot;
38072     sqlcipher3_mutex_enter(pcache1.mutex);
38073     sqlcipher3StatusAdd(SQLCIPHER_STATUS_PAGECACHE_USED, -1);
38074     pSlot = (PgFreeslot*)p;
38075     pSlot->pNext = pcache1.pFree;
38076     pcache1.pFree = pSlot;
38077     pcache1.nFreeSlot++;
38078     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
38079     assert( pcache1.nFreeSlot<=pcache1.nSlot );
38080     sqlcipher3_mutex_leave(pcache1.mutex);
38081   }else{
38082     int iSize;
38083     assert( sqlcipher3MemdebugHasType(p, MEMTYPE_PCACHE) );
38084     sqlcipher3MemdebugSetType(p, MEMTYPE_HEAP);
38085     iSize = sqlcipher3MallocSize(p);
38086     sqlcipher3_mutex_enter(pcache1.mutex);
38087     sqlcipher3StatusAdd(SQLCIPHER_STATUS_PAGECACHE_OVERFLOW, -iSize);
38088     sqlcipher3_mutex_leave(pcache1.mutex);
38089     sqlcipher3_free(p);
38090   }
38091 }
38092
38093 #ifdef SQLCIPHER_ENABLE_MEMORY_MANAGEMENT
38094 /*
38095 ** Return the size of a pcache allocation
38096 */
38097 static int pcache1MemSize(void *p){
38098   if( p>=pcache1.pStart && p<pcache1.pEnd ){
38099     return pcache1.szSlot;
38100   }else{
38101     int iSize;
38102     assert( sqlcipher3MemdebugHasType(p, MEMTYPE_PCACHE) );
38103     sqlcipher3MemdebugSetType(p, MEMTYPE_HEAP);
38104     iSize = sqlcipher3MallocSize(p);
38105     sqlcipher3MemdebugSetType(p, MEMTYPE_PCACHE);
38106     return iSize;
38107   }
38108 }
38109 #endif /* SQLCIPHER_ENABLE_MEMORY_MANAGEMENT */
38110
38111 /*
38112 ** Allocate a new page object initially associated with cache pCache.
38113 */
38114 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
38115   int nByte = sizeof(PgHdr1) + pCache->szPage;
38116   PgHdr1 *p = 0;
38117   void *pPg;
38118
38119   /* The group mutex must be released before pcache1Alloc() is called. This
38120   ** is because it may call sqlcipher3_release_memory(), which assumes that 
38121   ** this mutex is not held. */
38122   assert( sqlcipher3_mutex_held(pCache->pGroup->mutex) );
38123   pcache1LeaveMutex(pCache->pGroup);
38124   pPg = pcache1Alloc(nByte);
38125   pcache1EnterMutex(pCache->pGroup);
38126
38127   if( pPg ){
38128     p = PAGE_TO_PGHDR1(pCache, pPg);
38129     if( pCache->bPurgeable ){
38130       pCache->pGroup->nCurrentPage++;
38131     }
38132   }
38133   return p;
38134 }
38135
38136 /*
38137 ** Free a page object allocated by pcache1AllocPage().
38138 **
38139 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
38140 ** that the current implementation happens to never call this routine
38141 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
38142 */
38143 static void pcache1FreePage(PgHdr1 *p){
38144   if( ALWAYS(p) ){
38145     PCache1 *pCache = p->pCache;
38146     assert( sqlcipher3_mutex_held(p->pCache->pGroup->mutex) );
38147     pcache1Free(PGHDR1_TO_PAGE(p));
38148     if( pCache->bPurgeable ){
38149       pCache->pGroup->nCurrentPage--;
38150     }
38151   }
38152 }
38153
38154 /*
38155 ** Malloc function used by SQLite to obtain space from the buffer configured
38156 ** using sqlcipher3_config(SQLCIPHER_CONFIG_PAGECACHE) option. If no such buffer
38157 ** exists, this function falls back to sqlcipher3Malloc().
38158 */
38159 SQLCIPHER_PRIVATE void *sqlcipher3PageMalloc(int sz){
38160   return pcache1Alloc(sz);
38161 }
38162
38163 /*
38164 ** Free an allocated buffer obtained from sqlcipher3PageMalloc().
38165 */
38166 SQLCIPHER_PRIVATE void sqlcipher3PageFree(void *p){
38167   pcache1Free(p);
38168 }
38169
38170
38171 /*
38172 ** Return true if it desirable to avoid allocating a new page cache
38173 ** entry.
38174 **
38175 ** If memory was allocated specifically to the page cache using
38176 ** SQLCIPHER_CONFIG_PAGECACHE but that memory has all been used, then
38177 ** it is desirable to avoid allocating a new page cache entry because
38178 ** presumably SQLCIPHER_CONFIG_PAGECACHE was suppose to be sufficient
38179 ** for all page cache needs and we should not need to spill the
38180 ** allocation onto the heap.
38181 **
38182 ** Or, the heap is used for all page cache memory put the heap is
38183 ** under memory pressure, then again it is desirable to avoid
38184 ** allocating a new page cache entry in order to avoid stressing
38185 ** the heap even further.
38186 */
38187 static int pcache1UnderMemoryPressure(PCache1 *pCache){
38188   if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
38189     return pcache1.bUnderPressure;
38190   }else{
38191     return sqlcipher3HeapNearlyFull();
38192   }
38193 }
38194
38195 /******************************************************************************/
38196 /******** General Implementation Functions ************************************/
38197
38198 /*
38199 ** This function is used to resize the hash table used by the cache passed
38200 ** as the first argument.
38201 **
38202 ** The PCache mutex must be held when this function is called.
38203 */
38204 static int pcache1ResizeHash(PCache1 *p){
38205   PgHdr1 **apNew;
38206   unsigned int nNew;
38207   unsigned int i;
38208
38209   assert( sqlcipher3_mutex_held(p->pGroup->mutex) );
38210
38211   nNew = p->nHash*2;
38212   if( nNew<256 ){
38213     nNew = 256;
38214   }
38215
38216   pcache1LeaveMutex(p->pGroup);
38217   if( p->nHash ){ sqlcipher3BeginBenignMalloc(); }
38218   apNew = (PgHdr1 **)sqlcipher3_malloc(sizeof(PgHdr1 *)*nNew);
38219   if( p->nHash ){ sqlcipher3EndBenignMalloc(); }
38220   pcache1EnterMutex(p->pGroup);
38221   if( apNew ){
38222     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
38223     for(i=0; i<p->nHash; i++){
38224       PgHdr1 *pPage;
38225       PgHdr1 *pNext = p->apHash[i];
38226       while( (pPage = pNext)!=0 ){
38227         unsigned int h = pPage->iKey % nNew;
38228         pNext = pPage->pNext;
38229         pPage->pNext = apNew[h];
38230         apNew[h] = pPage;
38231       }
38232     }
38233     sqlcipher3_free(p->apHash);
38234     p->apHash = apNew;
38235     p->nHash = nNew;
38236   }
38237
38238   return (p->apHash ? SQLCIPHER_OK : SQLCIPHER_NOMEM);
38239 }
38240
38241 /*
38242 ** This function is used internally to remove the page pPage from the 
38243 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
38244 ** LRU list, then this function is a no-op.
38245 **
38246 ** The PGroup mutex must be held when this function is called.
38247 **
38248 ** If pPage is NULL then this routine is a no-op.
38249 */
38250 static void pcache1PinPage(PgHdr1 *pPage){
38251   PCache1 *pCache;
38252   PGroup *pGroup;
38253
38254   if( pPage==0 ) return;
38255   pCache = pPage->pCache;
38256   pGroup = pCache->pGroup;
38257   assert( sqlcipher3_mutex_held(pGroup->mutex) );
38258   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
38259     if( pPage->pLruPrev ){
38260       pPage->pLruPrev->pLruNext = pPage->pLruNext;
38261     }
38262     if( pPage->pLruNext ){
38263       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
38264     }
38265     if( pGroup->pLruHead==pPage ){
38266       pGroup->pLruHead = pPage->pLruNext;
38267     }
38268     if( pGroup->pLruTail==pPage ){
38269       pGroup->pLruTail = pPage->pLruPrev;
38270     }
38271     pPage->pLruNext = 0;
38272     pPage->pLruPrev = 0;
38273     pPage->pCache->nRecyclable--;
38274   }
38275 }
38276
38277
38278 /*
38279 ** Remove the page supplied as an argument from the hash table 
38280 ** (PCache1.apHash structure) that it is currently stored in.
38281 **
38282 ** The PGroup mutex must be held when this function is called.
38283 */
38284 static void pcache1RemoveFromHash(PgHdr1 *pPage){
38285   unsigned int h;
38286   PCache1 *pCache = pPage->pCache;
38287   PgHdr1 **pp;
38288
38289   assert( sqlcipher3_mutex_held(pCache->pGroup->mutex) );
38290   h = pPage->iKey % pCache->nHash;
38291   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
38292   *pp = (*pp)->pNext;
38293
38294   pCache->nPage--;
38295 }
38296
38297 /*
38298 ** If there are currently more than nMaxPage pages allocated, try
38299 ** to recycle pages to reduce the number allocated to nMaxPage.
38300 */
38301 static void pcache1EnforceMaxPage(PGroup *pGroup){
38302   assert( sqlcipher3_mutex_held(pGroup->mutex) );
38303   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
38304     PgHdr1 *p = pGroup->pLruTail;
38305     assert( p->pCache->pGroup==pGroup );
38306     pcache1PinPage(p);
38307     pcache1RemoveFromHash(p);
38308     pcache1FreePage(p);
38309   }
38310 }
38311
38312 /*
38313 ** Discard all pages from cache pCache with a page number (key value) 
38314 ** greater than or equal to iLimit. Any pinned pages that meet this 
38315 ** criteria are unpinned before they are discarded.
38316 **
38317 ** The PCache mutex must be held when this function is called.
38318 */
38319 static void pcache1TruncateUnsafe(
38320   PCache1 *pCache,             /* The cache to truncate */
38321   unsigned int iLimit          /* Drop pages with this pgno or larger */
38322 ){
38323   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
38324   unsigned int h;
38325   assert( sqlcipher3_mutex_held(pCache->pGroup->mutex) );
38326   for(h=0; h<pCache->nHash; h++){
38327     PgHdr1 **pp = &pCache->apHash[h]; 
38328     PgHdr1 *pPage;
38329     while( (pPage = *pp)!=0 ){
38330       if( pPage->iKey>=iLimit ){
38331         pCache->nPage--;
38332         *pp = pPage->pNext;
38333         pcache1PinPage(pPage);
38334         pcache1FreePage(pPage);
38335       }else{
38336         pp = &pPage->pNext;
38337         TESTONLY( nPage++; )
38338       }
38339     }
38340   }
38341   assert( pCache->nPage==nPage );
38342 }
38343
38344 /******************************************************************************/
38345 /******** sqlcipher3_pcache Methods **********************************************/
38346
38347 /*
38348 ** Implementation of the sqlcipher3_pcache.xInit method.
38349 */
38350 static int pcache1Init(void *NotUsed){
38351   UNUSED_PARAMETER(NotUsed);
38352   assert( pcache1.isInit==0 );
38353   memset(&pcache1, 0, sizeof(pcache1));
38354   if( sqlcipher3GlobalConfig.bCoreMutex ){
38355     pcache1.grp.mutex = sqlcipher3_mutex_alloc(SQLCIPHER_MUTEX_STATIC_LRU);
38356     pcache1.mutex = sqlcipher3_mutex_alloc(SQLCIPHER_MUTEX_STATIC_PMEM);
38357   }
38358   pcache1.grp.mxPinned = 10;
38359   pcache1.isInit = 1;
38360   return SQLCIPHER_OK;
38361 }
38362
38363 /*
38364 ** Implementation of the sqlcipher3_pcache.xShutdown method.
38365 ** Note that the static mutex allocated in xInit does 
38366 ** not need to be freed.
38367 */
38368 static void pcache1Shutdown(void *NotUsed){
38369   UNUSED_PARAMETER(NotUsed);
38370   assert( pcache1.isInit!=0 );
38371   memset(&pcache1, 0, sizeof(pcache1));
38372 }
38373
38374 /*
38375 ** Implementation of the sqlcipher3_pcache.xCreate method.
38376 **
38377 ** Allocate a new cache.
38378 */
38379 static sqlcipher3_pcache *pcache1Create(int szPage, int bPurgeable){
38380   PCache1 *pCache;      /* The newly created page cache */
38381   PGroup *pGroup;       /* The group the new page cache will belong to */
38382   int sz;               /* Bytes of memory required to allocate the new cache */
38383
38384   /*
38385   ** The seperateCache variable is true if each PCache has its own private
38386   ** PGroup.  In other words, separateCache is true for mode (1) where no
38387   ** mutexing is required.
38388   **
38389   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
38390   **
38391   **   *  Always use a unified cache in single-threaded applications
38392   **
38393   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
38394   **      use separate caches (mode-1)
38395   */
38396 #if defined(SQLCIPHER_ENABLE_MEMORY_MANAGEMENT) || SQLCIPHER_THREADSAFE==0
38397   const int separateCache = 0;
38398 #else
38399   int separateCache = sqlcipher3GlobalConfig.bCoreMutex>0;
38400 #endif
38401
38402   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
38403   pCache = (PCache1 *)sqlcipher3_malloc(sz);
38404   if( pCache ){
38405     memset(pCache, 0, sz);
38406     if( separateCache ){
38407       pGroup = (PGroup*)&pCache[1];
38408       pGroup->mxPinned = 10;
38409     }else{
38410       pGroup = &pcache1.grp;
38411     }
38412     pCache->pGroup = pGroup;
38413     pCache->szPage = szPage;
38414     pCache->bPurgeable = (bPurgeable ? 1 : 0);
38415     if( bPurgeable ){
38416       pCache->nMin = 10;
38417       pcache1EnterMutex(pGroup);
38418       pGroup->nMinPage += pCache->nMin;
38419       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38420       pcache1LeaveMutex(pGroup);
38421     }
38422   }
38423   return (sqlcipher3_pcache *)pCache;
38424 }
38425
38426 /*
38427 ** Implementation of the sqlcipher3_pcache.xCachesize method. 
38428 **
38429 ** Configure the cache_size limit for a cache.
38430 */
38431 static void pcache1Cachesize(sqlcipher3_pcache *p, int nMax){
38432   PCache1 *pCache = (PCache1 *)p;
38433   if( pCache->bPurgeable ){
38434     PGroup *pGroup = pCache->pGroup;
38435     pcache1EnterMutex(pGroup);
38436     pGroup->nMaxPage += (nMax - pCache->nMax);
38437     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38438     pCache->nMax = nMax;
38439     pCache->n90pct = pCache->nMax*9/10;
38440     pcache1EnforceMaxPage(pGroup);
38441     pcache1LeaveMutex(pGroup);
38442   }
38443 }
38444
38445 /*
38446 ** Implementation of the sqlcipher3_pcache.xPagecount method. 
38447 */
38448 static int pcache1Pagecount(sqlcipher3_pcache *p){
38449   int n;
38450   PCache1 *pCache = (PCache1*)p;
38451   pcache1EnterMutex(pCache->pGroup);
38452   n = pCache->nPage;
38453   pcache1LeaveMutex(pCache->pGroup);
38454   return n;
38455 }
38456
38457 /*
38458 ** Implementation of the sqlcipher3_pcache.xFetch method. 
38459 **
38460 ** Fetch a page by key value.
38461 **
38462 ** Whether or not a new page may be allocated by this function depends on
38463 ** the value of the createFlag argument.  0 means do not allocate a new
38464 ** page.  1 means allocate a new page if space is easily available.  2 
38465 ** means to try really hard to allocate a new page.
38466 **
38467 ** For a non-purgeable cache (a cache used as the storage for an in-memory
38468 ** database) there is really no difference between createFlag 1 and 2.  So
38469 ** the calling function (pcache.c) will never have a createFlag of 1 on
38470 ** a non-purgable cache.
38471 **
38472 ** There are three different approaches to obtaining space for a page,
38473 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
38474 **
38475 **   1. Regardless of the value of createFlag, the cache is searched for a 
38476 **      copy of the requested page. If one is found, it is returned.
38477 **
38478 **   2. If createFlag==0 and the page is not already in the cache, NULL is
38479 **      returned.
38480 **
38481 **   3. If createFlag is 1, and the page is not already in the cache, then
38482 **      return NULL (do not allocate a new page) if any of the following
38483 **      conditions are true:
38484 **
38485 **       (a) the number of pages pinned by the cache is greater than
38486 **           PCache1.nMax, or
38487 **
38488 **       (b) the number of pages pinned by the cache is greater than
38489 **           the sum of nMax for all purgeable caches, less the sum of 
38490 **           nMin for all other purgeable caches, or
38491 **
38492 **   4. If none of the first three conditions apply and the cache is marked
38493 **      as purgeable, and if one of the following is true:
38494 **
38495 **       (a) The number of pages allocated for the cache is already 
38496 **           PCache1.nMax, or
38497 **
38498 **       (b) The number of pages allocated for all purgeable caches is
38499 **           already equal to or greater than the sum of nMax for all
38500 **           purgeable caches,
38501 **
38502 **       (c) The system is under memory pressure and wants to avoid
38503 **           unnecessary pages cache entry allocations
38504 **
38505 **      then attempt to recycle a page from the LRU list. If it is the right
38506 **      size, return the recycled buffer. Otherwise, free the buffer and
38507 **      proceed to step 5. 
38508 **
38509 **   5. Otherwise, allocate and return a new page buffer.
38510 */
38511 static void *pcache1Fetch(sqlcipher3_pcache *p, unsigned int iKey, int createFlag){
38512   int nPinned;
38513   PCache1 *pCache = (PCache1 *)p;
38514   PGroup *pGroup;
38515   PgHdr1 *pPage = 0;
38516
38517   assert( pCache->bPurgeable || createFlag!=1 );
38518   assert( pCache->bPurgeable || pCache->nMin==0 );
38519   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
38520   assert( pCache->nMin==0 || pCache->bPurgeable );
38521   pcache1EnterMutex(pGroup = pCache->pGroup);
38522
38523   /* Step 1: Search the hash table for an existing entry. */
38524   if( pCache->nHash>0 ){
38525     unsigned int h = iKey % pCache->nHash;
38526     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
38527   }
38528
38529   /* Step 2: Abort if no existing page is found and createFlag is 0 */
38530   if( pPage || createFlag==0 ){
38531     pcache1PinPage(pPage);
38532     goto fetch_out;
38533   }
38534
38535   /* The pGroup local variable will normally be initialized by the
38536   ** pcache1EnterMutex() macro above.  But if SQLCIPHER_MUTEX_OMIT is defined,
38537   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
38538   ** local variable here.  Delaying the initialization of pGroup is an
38539   ** optimization:  The common case is to exit the module before reaching
38540   ** this point.
38541   */
38542 #ifdef SQLCIPHER_MUTEX_OMIT
38543   pGroup = pCache->pGroup;
38544 #endif
38545
38546
38547   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
38548   nPinned = pCache->nPage - pCache->nRecyclable;
38549   assert( nPinned>=0 );
38550   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
38551   assert( pCache->n90pct == pCache->nMax*9/10 );
38552   if( createFlag==1 && (
38553         nPinned>=pGroup->mxPinned
38554      || nPinned>=(int)pCache->n90pct
38555      || pcache1UnderMemoryPressure(pCache)
38556   )){
38557     goto fetch_out;
38558   }
38559
38560   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
38561     goto fetch_out;
38562   }
38563
38564   /* Step 4. Try to recycle a page. */
38565   if( pCache->bPurgeable && pGroup->pLruTail && (
38566          (pCache->nPage+1>=pCache->nMax)
38567       || pGroup->nCurrentPage>=pGroup->nMaxPage
38568       || pcache1UnderMemoryPressure(pCache)
38569   )){
38570     PCache1 *pOtherCache;
38571     pPage = pGroup->pLruTail;
38572     pcache1RemoveFromHash(pPage);
38573     pcache1PinPage(pPage);
38574     if( (pOtherCache = pPage->pCache)->szPage!=pCache->szPage ){
38575       pcache1FreePage(pPage);
38576       pPage = 0;
38577     }else{
38578       pGroup->nCurrentPage -= 
38579                (pOtherCache->bPurgeable - pCache->bPurgeable);
38580     }
38581   }
38582
38583   /* Step 5. If a usable page buffer has still not been found, 
38584   ** attempt to allocate a new one. 
38585   */
38586   if( !pPage ){
38587     if( createFlag==1 ) sqlcipher3BeginBenignMalloc();
38588     pPage = pcache1AllocPage(pCache);
38589     if( createFlag==1 ) sqlcipher3EndBenignMalloc();
38590   }
38591
38592   if( pPage ){
38593     unsigned int h = iKey % pCache->nHash;
38594     pCache->nPage++;
38595     pPage->iKey = iKey;
38596     pPage->pNext = pCache->apHash[h];
38597     pPage->pCache = pCache;
38598     pPage->pLruPrev = 0;
38599     pPage->pLruNext = 0;
38600     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
38601     pCache->apHash[h] = pPage;
38602   }
38603
38604 fetch_out:
38605   if( pPage && iKey>pCache->iMaxKey ){
38606     pCache->iMaxKey = iKey;
38607   }
38608   pcache1LeaveMutex(pGroup);
38609   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
38610 }
38611
38612
38613 /*
38614 ** Implementation of the sqlcipher3_pcache.xUnpin method.
38615 **
38616 ** Mark a page as unpinned (eligible for asynchronous recycling).
38617 */
38618 static void pcache1Unpin(sqlcipher3_pcache *p, void *pPg, int reuseUnlikely){
38619   PCache1 *pCache = (PCache1 *)p;
38620   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
38621   PGroup *pGroup = pCache->pGroup;
38622  
38623   assert( pPage->pCache==pCache );
38624   pcache1EnterMutex(pGroup);
38625
38626   /* It is an error to call this function if the page is already 
38627   ** part of the PGroup LRU list.
38628   */
38629   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
38630   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
38631
38632   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
38633     pcache1RemoveFromHash(pPage);
38634     pcache1FreePage(pPage);
38635   }else{
38636     /* Add the page to the PGroup LRU list. */
38637     if( pGroup->pLruHead ){
38638       pGroup->pLruHead->pLruPrev = pPage;
38639       pPage->pLruNext = pGroup->pLruHead;
38640       pGroup->pLruHead = pPage;
38641     }else{
38642       pGroup->pLruTail = pPage;
38643       pGroup->pLruHead = pPage;
38644     }
38645     pCache->nRecyclable++;
38646   }
38647
38648   pcache1LeaveMutex(pCache->pGroup);
38649 }
38650
38651 /*
38652 ** Implementation of the sqlcipher3_pcache.xRekey method. 
38653 */
38654 static void pcache1Rekey(
38655   sqlcipher3_pcache *p,
38656   void *pPg,
38657   unsigned int iOld,
38658   unsigned int iNew
38659 ){
38660   PCache1 *pCache = (PCache1 *)p;
38661   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
38662   PgHdr1 **pp;
38663   unsigned int h; 
38664   assert( pPage->iKey==iOld );
38665   assert( pPage->pCache==pCache );
38666
38667   pcache1EnterMutex(pCache->pGroup);
38668
38669   h = iOld%pCache->nHash;
38670   pp = &pCache->apHash[h];
38671   while( (*pp)!=pPage ){
38672     pp = &(*pp)->pNext;
38673   }
38674   *pp = pPage->pNext;
38675
38676   h = iNew%pCache->nHash;
38677   pPage->iKey = iNew;
38678   pPage->pNext = pCache->apHash[h];
38679   pCache->apHash[h] = pPage;
38680   if( iNew>pCache->iMaxKey ){
38681     pCache->iMaxKey = iNew;
38682   }
38683
38684   pcache1LeaveMutex(pCache->pGroup);
38685 }
38686
38687 /*
38688 ** Implementation of the sqlcipher3_pcache.xTruncate method. 
38689 **
38690 ** Discard all unpinned pages in the cache with a page number equal to
38691 ** or greater than parameter iLimit. Any pinned pages with a page number
38692 ** equal to or greater than iLimit are implicitly unpinned.
38693 */
38694 static void pcache1Truncate(sqlcipher3_pcache *p, unsigned int iLimit){
38695   PCache1 *pCache = (PCache1 *)p;
38696   pcache1EnterMutex(pCache->pGroup);
38697   if( iLimit<=pCache->iMaxKey ){
38698     pcache1TruncateUnsafe(pCache, iLimit);
38699     pCache->iMaxKey = iLimit-1;
38700   }
38701   pcache1LeaveMutex(pCache->pGroup);
38702 }
38703
38704 /*
38705 ** Implementation of the sqlcipher3_pcache.xDestroy method. 
38706 **
38707 ** Destroy a cache allocated using pcache1Create().
38708 */
38709 static void pcache1Destroy(sqlcipher3_pcache *p){
38710   PCache1 *pCache = (PCache1 *)p;
38711   PGroup *pGroup = pCache->pGroup;
38712   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
38713   pcache1EnterMutex(pGroup);
38714   pcache1TruncateUnsafe(pCache, 0);
38715   pGroup->nMaxPage -= pCache->nMax;
38716   pGroup->nMinPage -= pCache->nMin;
38717   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38718   pcache1EnforceMaxPage(pGroup);
38719   pcache1LeaveMutex(pGroup);
38720   sqlcipher3_free(pCache->apHash);
38721   sqlcipher3_free(pCache);
38722 }
38723
38724 /*
38725 ** This function is called during initialization (sqlcipher3_initialize()) to
38726 ** install the default pluggable cache module, assuming the user has not
38727 ** already provided an alternative.
38728 */
38729 SQLCIPHER_PRIVATE void sqlcipher3PCacheSetDefault(void){
38730   static const sqlcipher3_pcache_methods defaultMethods = {
38731     0,                       /* pArg */
38732     pcache1Init,             /* xInit */
38733     pcache1Shutdown,         /* xShutdown */
38734     pcache1Create,           /* xCreate */
38735     pcache1Cachesize,        /* xCachesize */
38736     pcache1Pagecount,        /* xPagecount */
38737     pcache1Fetch,            /* xFetch */
38738     pcache1Unpin,            /* xUnpin */
38739     pcache1Rekey,            /* xRekey */
38740     pcache1Truncate,         /* xTruncate */
38741     pcache1Destroy           /* xDestroy */
38742   };
38743   sqlcipher3_config(SQLCIPHER_CONFIG_PCACHE, &defaultMethods);
38744 }
38745
38746 #ifdef SQLCIPHER_ENABLE_MEMORY_MANAGEMENT
38747 /*
38748 ** This function is called to free superfluous dynamically allocated memory
38749 ** held by the pager system. Memory in use by any SQLite pager allocated
38750 ** by the current thread may be sqlcipher3_free()ed.
38751 **
38752 ** nReq is the number of bytes of memory required. Once this much has
38753 ** been released, the function returns. The return value is the total number 
38754 ** of bytes of memory released.
38755 */
38756 SQLCIPHER_PRIVATE int sqlcipher3PcacheReleaseMemory(int nReq){
38757   int nFree = 0;
38758   assert( sqlcipher3_mutex_notheld(pcache1.grp.mutex) );
38759   assert( sqlcipher3_mutex_notheld(pcache1.mutex) );
38760   if( pcache1.pStart==0 ){
38761     PgHdr1 *p;
38762     pcache1EnterMutex(&pcache1.grp);
38763     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
38764       nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
38765       pcache1PinPage(p);
38766       pcache1RemoveFromHash(p);
38767       pcache1FreePage(p);
38768     }
38769     pcache1LeaveMutex(&pcache1.grp);
38770   }
38771   return nFree;
38772 }
38773 #endif /* SQLCIPHER_ENABLE_MEMORY_MANAGEMENT */
38774
38775 #ifdef SQLCIPHER_TEST
38776 /*
38777 ** This function is used by test procedures to inspect the internal state
38778 ** of the global cache.
38779 */
38780 SQLCIPHER_PRIVATE void sqlcipher3PcacheStats(
38781   int *pnCurrent,      /* OUT: Total number of pages cached */
38782   int *pnMax,          /* OUT: Global maximum cache size */
38783   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
38784   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
38785 ){
38786   PgHdr1 *p;
38787   int nRecyclable = 0;
38788   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
38789     nRecyclable++;
38790   }
38791   *pnCurrent = pcache1.grp.nCurrentPage;
38792   *pnMax = pcache1.grp.nMaxPage;
38793   *pnMin = pcache1.grp.nMinPage;
38794   *pnRecyclable = nRecyclable;
38795 }
38796 #endif
38797
38798 /************** End of pcache1.c *********************************************/
38799 /************** Begin file rowset.c ******************************************/
38800 /*
38801 ** 2008 December 3
38802 **
38803 ** The author disclaims copyright to this source code.  In place of
38804 ** a legal notice, here is a blessing:
38805 **
38806 **    May you do good and not evil.
38807 **    May you find forgiveness for yourself and forgive others.
38808 **    May you share freely, never taking more than you give.
38809 **
38810 *************************************************************************
38811 **
38812 ** This module implements an object we call a "RowSet".
38813 **
38814 ** The RowSet object is a collection of rowids.  Rowids
38815 ** are inserted into the RowSet in an arbitrary order.  Inserts
38816 ** can be intermixed with tests to see if a given rowid has been
38817 ** previously inserted into the RowSet.
38818 **
38819 ** After all inserts are finished, it is possible to extract the
38820 ** elements of the RowSet in sorted order.  Once this extraction
38821 ** process has started, no new elements may be inserted.
38822 **
38823 ** Hence, the primitive operations for a RowSet are:
38824 **
38825 **    CREATE
38826 **    INSERT
38827 **    TEST
38828 **    SMALLEST
38829 **    DESTROY
38830 **
38831 ** The CREATE and DESTROY primitives are the constructor and destructor,
38832 ** obviously.  The INSERT primitive adds a new element to the RowSet.
38833 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
38834 ** extracts the least value from the RowSet.
38835 **
38836 ** The INSERT primitive might allocate additional memory.  Memory is
38837 ** allocated in chunks so most INSERTs do no allocation.  There is an 
38838 ** upper bound on the size of allocated memory.  No memory is freed
38839 ** until DESTROY.
38840 **
38841 ** The TEST primitive includes a "batch" number.  The TEST primitive
38842 ** will only see elements that were inserted before the last change
38843 ** in the batch number.  In other words, if an INSERT occurs between
38844 ** two TESTs where the TESTs have the same batch nubmer, then the
38845 ** value added by the INSERT will not be visible to the second TEST.
38846 ** The initial batch number is zero, so if the very first TEST contains
38847 ** a non-zero batch number, it will see all prior INSERTs.
38848 **
38849 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
38850 ** that is attempted.
38851 **
38852 ** The cost of an INSERT is roughly constant.  (Sometime new memory
38853 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
38854 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
38855 ** The cost of a TEST using the same batch number is O(logN).  The cost
38856 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
38857 ** primitives are constant time.  The cost of DESTROY is O(N).
38858 **
38859 ** There is an added cost of O(N) when switching between TEST and
38860 ** SMALLEST primitives.
38861 */
38862
38863
38864 /*
38865 ** Target size for allocation chunks.
38866 */
38867 #define ROWSET_ALLOCATION_SIZE 1024
38868
38869 /*
38870 ** The number of rowset entries per allocation chunk.
38871 */
38872 #define ROWSET_ENTRY_PER_CHUNK  \
38873                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
38874
38875 /*
38876 ** Each entry in a RowSet is an instance of the following object.
38877 */
38878 struct RowSetEntry {            
38879   i64 v;                        /* ROWID value for this entry */
38880   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
38881   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
38882 };
38883
38884 /*
38885 ** RowSetEntry objects are allocated in large chunks (instances of the
38886 ** following structure) to reduce memory allocation overhead.  The
38887 ** chunks are kept on a linked list so that they can be deallocated
38888 ** when the RowSet is destroyed.
38889 */
38890 struct RowSetChunk {
38891   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
38892   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
38893 };
38894
38895 /*
38896 ** A RowSet in an instance of the following structure.
38897 **
38898 ** A typedef of this structure if found in sqlcipherInt.h.
38899 */
38900 struct RowSet {
38901   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
38902   sqlcipher3 *db;                   /* The database connection */
38903   struct RowSetEntry *pEntry;    /* List of entries using pRight */
38904   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
38905   struct RowSetEntry *pFresh;    /* Source of new entry objects */
38906   struct RowSetEntry *pTree;     /* Binary tree of entries */
38907   u16 nFresh;                    /* Number of objects on pFresh */
38908   u8 isSorted;                   /* True if pEntry is sorted */
38909   u8 iBatch;                     /* Current insert batch */
38910 };
38911
38912 /*
38913 ** Turn bulk memory into a RowSet object.  N bytes of memory
38914 ** are available at pSpace.  The db pointer is used as a memory context
38915 ** for any subsequent allocations that need to occur.
38916 ** Return a pointer to the new RowSet object.
38917 **
38918 ** It must be the case that N is sufficient to make a Rowset.  If not
38919 ** an assertion fault occurs.
38920 ** 
38921 ** If N is larger than the minimum, use the surplus as an initial
38922 ** allocation of entries available to be filled.
38923 */
38924 SQLCIPHER_PRIVATE RowSet *sqlcipher3RowSetInit(sqlcipher3 *db, void *pSpace, unsigned int N){
38925   RowSet *p;
38926   assert( N >= ROUND8(sizeof(*p)) );
38927   p = pSpace;
38928   p->pChunk = 0;
38929   p->db = db;
38930   p->pEntry = 0;
38931   p->pLast = 0;
38932   p->pTree = 0;
38933   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
38934   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
38935   p->isSorted = 1;
38936   p->iBatch = 0;
38937   return p;
38938 }
38939
38940 /*
38941 ** Deallocate all chunks from a RowSet.  This frees all memory that
38942 ** the RowSet has allocated over its lifetime.  This routine is
38943 ** the destructor for the RowSet.
38944 */
38945 SQLCIPHER_PRIVATE void sqlcipher3RowSetClear(RowSet *p){
38946   struct RowSetChunk *pChunk, *pNextChunk;
38947   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
38948     pNextChunk = pChunk->pNextChunk;
38949     sqlcipher3DbFree(p->db, pChunk);
38950   }
38951   p->pChunk = 0;
38952   p->nFresh = 0;
38953   p->pEntry = 0;
38954   p->pLast = 0;
38955   p->pTree = 0;
38956   p->isSorted = 1;
38957 }
38958
38959 /*
38960 ** Insert a new value into a RowSet.
38961 **
38962 ** The mallocFailed flag of the database connection is set if a
38963 ** memory allocation fails.
38964 */
38965 SQLCIPHER_PRIVATE void sqlcipher3RowSetInsert(RowSet *p, i64 rowid){
38966   struct RowSetEntry *pEntry;  /* The new entry */
38967   struct RowSetEntry *pLast;   /* The last prior entry */
38968   assert( p!=0 );
38969   if( p->nFresh==0 ){
38970     struct RowSetChunk *pNew;
38971     pNew = sqlcipher3DbMallocRaw(p->db, sizeof(*pNew));
38972     if( pNew==0 ){
38973       return;
38974     }
38975     pNew->pNextChunk = p->pChunk;
38976     p->pChunk = pNew;
38977     p->pFresh = pNew->aEntry;
38978     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
38979   }
38980   pEntry = p->pFresh++;
38981   p->nFresh--;
38982   pEntry->v = rowid;
38983   pEntry->pRight = 0;
38984   pLast = p->pLast;
38985   if( pLast ){
38986     if( p->isSorted && rowid<=pLast->v ){
38987       p->isSorted = 0;
38988     }
38989     pLast->pRight = pEntry;
38990   }else{
38991     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
38992     p->pEntry = pEntry;
38993   }
38994   p->pLast = pEntry;
38995 }
38996
38997 /*
38998 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
38999 **
39000 ** The input lists are connected via pRight pointers and are 
39001 ** assumed to each already be in sorted order.
39002 */
39003 static struct RowSetEntry *rowSetMerge(
39004   struct RowSetEntry *pA,    /* First sorted list to be merged */
39005   struct RowSetEntry *pB     /* Second sorted list to be merged */
39006 ){
39007   struct RowSetEntry head;
39008   struct RowSetEntry *pTail;
39009
39010   pTail = &head;
39011   while( pA && pB ){
39012     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
39013     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
39014     if( pA->v<pB->v ){
39015       pTail->pRight = pA;
39016       pA = pA->pRight;
39017       pTail = pTail->pRight;
39018     }else if( pB->v<pA->v ){
39019       pTail->pRight = pB;
39020       pB = pB->pRight;
39021       pTail = pTail->pRight;
39022     }else{
39023       pA = pA->pRight;
39024     }
39025   }
39026   if( pA ){
39027     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
39028     pTail->pRight = pA;
39029   }else{
39030     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
39031     pTail->pRight = pB;
39032   }
39033   return head.pRight;
39034 }
39035
39036 /*
39037 ** Sort all elements on the pEntry list of the RowSet into ascending order.
39038 */ 
39039 static void rowSetSort(RowSet *p){
39040   unsigned int i;
39041   struct RowSetEntry *pEntry;
39042   struct RowSetEntry *aBucket[40];
39043
39044   assert( p->isSorted==0 );
39045   memset(aBucket, 0, sizeof(aBucket));
39046   while( p->pEntry ){
39047     pEntry = p->pEntry;
39048     p->pEntry = pEntry->pRight;
39049     pEntry->pRight = 0;
39050     for(i=0; aBucket[i]; i++){
39051       pEntry = rowSetMerge(aBucket[i], pEntry);
39052       aBucket[i] = 0;
39053     }
39054     aBucket[i] = pEntry;
39055   }
39056   pEntry = 0;
39057   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
39058     pEntry = rowSetMerge(pEntry, aBucket[i]);
39059   }
39060   p->pEntry = pEntry;
39061   p->pLast = 0;
39062   p->isSorted = 1;
39063 }
39064
39065
39066 /*
39067 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
39068 ** Convert this tree into a linked list connected by the pRight pointers
39069 ** and return pointers to the first and last elements of the new list.
39070 */
39071 static void rowSetTreeToList(
39072   struct RowSetEntry *pIn,         /* Root of the input tree */
39073   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
39074   struct RowSetEntry **ppLast      /* Write tail of the output list here */
39075 ){
39076   assert( pIn!=0 );
39077   if( pIn->pLeft ){
39078     struct RowSetEntry *p;
39079     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
39080     p->pRight = pIn;
39081   }else{
39082     *ppFirst = pIn;
39083   }
39084   if( pIn->pRight ){
39085     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
39086   }else{
39087     *ppLast = pIn;
39088   }
39089   assert( (*ppLast)->pRight==0 );
39090 }
39091
39092
39093 /*
39094 ** Convert a sorted list of elements (connected by pRight) into a binary
39095 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
39096 ** node taken from the head of *ppList.  A depth of 2 means a tree with
39097 ** three nodes.  And so forth.
39098 **
39099 ** Use as many entries from the input list as required and update the
39100 ** *ppList to point to the unused elements of the list.  If the input
39101 ** list contains too few elements, then construct an incomplete tree
39102 ** and leave *ppList set to NULL.
39103 **
39104 ** Return a pointer to the root of the constructed binary tree.
39105 */
39106 static struct RowSetEntry *rowSetNDeepTree(
39107   struct RowSetEntry **ppList,
39108   int iDepth
39109 ){
39110   struct RowSetEntry *p;         /* Root of the new tree */
39111   struct RowSetEntry *pLeft;     /* Left subtree */
39112   if( *ppList==0 ){
39113     return 0;
39114   }
39115   if( iDepth==1 ){
39116     p = *ppList;
39117     *ppList = p->pRight;
39118     p->pLeft = p->pRight = 0;
39119     return p;
39120   }
39121   pLeft = rowSetNDeepTree(ppList, iDepth-1);
39122   p = *ppList;
39123   if( p==0 ){
39124     return pLeft;
39125   }
39126   p->pLeft = pLeft;
39127   *ppList = p->pRight;
39128   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
39129   return p;
39130 }
39131
39132 /*
39133 ** Convert a sorted list of elements into a binary tree. Make the tree
39134 ** as deep as it needs to be in order to contain the entire list.
39135 */
39136 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
39137   int iDepth;           /* Depth of the tree so far */
39138   struct RowSetEntry *p;       /* Current tree root */
39139   struct RowSetEntry *pLeft;   /* Left subtree */
39140
39141   assert( pList!=0 );
39142   p = pList;
39143   pList = p->pRight;
39144   p->pLeft = p->pRight = 0;
39145   for(iDepth=1; pList; iDepth++){
39146     pLeft = p;
39147     p = pList;
39148     pList = p->pRight;
39149     p->pLeft = pLeft;
39150     p->pRight = rowSetNDeepTree(&pList, iDepth);
39151   }
39152   return p;
39153 }
39154
39155 /*
39156 ** Convert the list in p->pEntry into a sorted list if it is not
39157 ** sorted already.  If there is a binary tree on p->pTree, then
39158 ** convert it into a list too and merge it into the p->pEntry list.
39159 */
39160 static void rowSetToList(RowSet *p){
39161   if( !p->isSorted ){
39162     rowSetSort(p);
39163   }
39164   if( p->pTree ){
39165     struct RowSetEntry *pHead, *pTail;
39166     rowSetTreeToList(p->pTree, &pHead, &pTail);
39167     p->pTree = 0;
39168     p->pEntry = rowSetMerge(p->pEntry, pHead);
39169   }
39170 }
39171
39172 /*
39173 ** Extract the smallest element from the RowSet.
39174 ** Write the element into *pRowid.  Return 1 on success.  Return
39175 ** 0 if the RowSet is already empty.
39176 **
39177 ** After this routine has been called, the sqlcipher3RowSetInsert()
39178 ** routine may not be called again.  
39179 */
39180 SQLCIPHER_PRIVATE int sqlcipher3RowSetNext(RowSet *p, i64 *pRowid){
39181   rowSetToList(p);
39182   if( p->pEntry ){
39183     *pRowid = p->pEntry->v;
39184     p->pEntry = p->pEntry->pRight;
39185     if( p->pEntry==0 ){
39186       sqlcipher3RowSetClear(p);
39187     }
39188     return 1;
39189   }else{
39190     return 0;
39191   }
39192 }
39193
39194 /*
39195 ** Check to see if element iRowid was inserted into the the rowset as
39196 ** part of any insert batch prior to iBatch.  Return 1 or 0.
39197 */
39198 SQLCIPHER_PRIVATE int sqlcipher3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlcipher3_int64 iRowid){
39199   struct RowSetEntry *p;
39200   if( iBatch!=pRowSet->iBatch ){
39201     if( pRowSet->pEntry ){
39202       rowSetToList(pRowSet);
39203       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
39204       pRowSet->pEntry = 0;
39205       pRowSet->pLast = 0;
39206     }
39207     pRowSet->iBatch = iBatch;
39208   }
39209   p = pRowSet->pTree;
39210   while( p ){
39211     if( p->v<iRowid ){
39212       p = p->pRight;
39213     }else if( p->v>iRowid ){
39214       p = p->pLeft;
39215     }else{
39216       return 1;
39217     }
39218   }
39219   return 0;
39220 }
39221
39222 /************** End of rowset.c **********************************************/
39223 /************** Begin file pager.c *******************************************/
39224 /*
39225 ** 2001 September 15
39226 **
39227 ** The author disclaims copyright to this source code.  In place of
39228 ** a legal notice, here is a blessing:
39229 **
39230 **    May you do good and not evil.
39231 **    May you find forgiveness for yourself and forgive others.
39232 **    May you share freely, never taking more than you give.
39233 **
39234 *************************************************************************
39235 ** This is the implementation of the page cache subsystem or "pager".
39236 ** 
39237 ** The pager is used to access a database disk file.  It implements
39238 ** atomic commit and rollback through the use of a journal file that
39239 ** is separate from the database file.  The pager also implements file
39240 ** locking to prevent two processes from writing the same database
39241 ** file simultaneously, or one process from reading the database while
39242 ** another is writing.
39243 */
39244 #ifndef SQLCIPHER_OMIT_DISKIO
39245 /************** Include wal.h in the middle of pager.c ***********************/
39246 /************** Begin file wal.h *********************************************/
39247 /*
39248 ** 2010 February 1
39249 **
39250 ** The author disclaims copyright to this source code.  In place of
39251 ** a legal notice, here is a blessing:
39252 **
39253 **    May you do good and not evil.
39254 **    May you find forgiveness for yourself and forgive others.
39255 **    May you share freely, never taking more than you give.
39256 **
39257 *************************************************************************
39258 ** This header file defines the interface to the write-ahead logging 
39259 ** system. Refer to the comments below and the header comment attached to 
39260 ** the implementation of each function in log.c for further details.
39261 */
39262
39263 #ifndef _WAL_H_
39264 #define _WAL_H_
39265
39266
39267 #ifdef SQLCIPHER_OMIT_WAL
39268 # define sqlcipher3WalOpen(x,y,z)                   0
39269 # define sqlcipher3WalLimit(x,y)
39270 # define sqlcipher3WalClose(w,x,y,z)                0
39271 # define sqlcipher3WalBeginReadTransaction(y,z)     0
39272 # define sqlcipher3WalEndReadTransaction(z)
39273 # define sqlcipher3WalRead(v,w,x,y,z)               0
39274 # define sqlcipher3WalDbsize(y)                     0
39275 # define sqlcipher3WalBeginWriteTransaction(y)      0
39276 # define sqlcipher3WalEndWriteTransaction(x)        0
39277 # define sqlcipher3WalUndo(x,y,z)                   0
39278 # define sqlcipher3WalSavepoint(y,z)
39279 # define sqlcipher3WalSavepointUndo(y,z)            0
39280 # define sqlcipher3WalFrames(u,v,w,x,y,z)           0
39281 # define sqlcipher3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
39282 # define sqlcipher3WalCallback(z)                   0
39283 # define sqlcipher3WalExclusiveMode(y,z)            0
39284 # define sqlcipher3WalHeapMemory(z)                 0
39285 #else
39286
39287 #define WAL_SAVEPOINT_NDATA 4
39288
39289 /* Connection to a write-ahead log (WAL) file. 
39290 ** There is one object of this type for each pager. 
39291 */
39292 typedef struct Wal Wal;
39293
39294 /* Open and close a connection to a write-ahead log. */
39295 SQLCIPHER_PRIVATE int sqlcipher3WalOpen(sqlcipher3_vfs*, sqlcipher3_file*, const char *, int, i64, Wal**);
39296 SQLCIPHER_PRIVATE int sqlcipher3WalClose(Wal *pWal, int sync_flags, int, u8 *);
39297
39298 /* Set the limiting size of a WAL file. */
39299 SQLCIPHER_PRIVATE void sqlcipher3WalLimit(Wal*, i64);
39300
39301 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
39302 ** snapshot is like a read-transaction.  It is the state of the database
39303 ** at an instant in time.  sqlcipher3WalOpenSnapshot gets a read lock and
39304 ** preserves the current state even if the other threads or processes
39305 ** write to or checkpoint the WAL.  sqlcipher3WalCloseSnapshot() closes the
39306 ** transaction and releases the lock.
39307 */
39308 SQLCIPHER_PRIVATE int sqlcipher3WalBeginReadTransaction(Wal *pWal, int *);
39309 SQLCIPHER_PRIVATE void sqlcipher3WalEndReadTransaction(Wal *pWal);
39310
39311 /* Read a page from the write-ahead log, if it is present. */
39312 SQLCIPHER_PRIVATE int sqlcipher3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
39313
39314 /* If the WAL is not empty, return the size of the database. */
39315 SQLCIPHER_PRIVATE Pgno sqlcipher3WalDbsize(Wal *pWal);
39316
39317 /* Obtain or release the WRITER lock. */
39318 SQLCIPHER_PRIVATE int sqlcipher3WalBeginWriteTransaction(Wal *pWal);
39319 SQLCIPHER_PRIVATE int sqlcipher3WalEndWriteTransaction(Wal *pWal);
39320
39321 /* Undo any frames written (but not committed) to the log */
39322 SQLCIPHER_PRIVATE int sqlcipher3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
39323
39324 /* Return an integer that records the current (uncommitted) write
39325 ** position in the WAL */
39326 SQLCIPHER_PRIVATE void sqlcipher3WalSavepoint(Wal *pWal, u32 *aWalData);
39327
39328 /* Move the write position of the WAL back to iFrame.  Called in
39329 ** response to a ROLLBACK TO command. */
39330 SQLCIPHER_PRIVATE int sqlcipher3WalSavepointUndo(Wal *pWal, u32 *aWalData);
39331
39332 /* Write a frame or frames to the log. */
39333 SQLCIPHER_PRIVATE int sqlcipher3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
39334
39335 /* Copy pages from the log to the database file */ 
39336 SQLCIPHER_PRIVATE int sqlcipher3WalCheckpoint(
39337   Wal *pWal,                      /* Write-ahead log connection */
39338   int eMode,                      /* One of PASSIVE, FULL and RESTART */
39339   int (*xBusy)(void*),            /* Function to call when busy */
39340   void *pBusyArg,                 /* Context argument for xBusyHandler */
39341   int sync_flags,                 /* Flags to sync db file with (or 0) */
39342   int nBuf,                       /* Size of buffer nBuf */
39343   u8 *zBuf,                       /* Temporary buffer to use */
39344   int *pnLog,                     /* OUT: Number of frames in WAL */
39345   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
39346 );
39347
39348 /* Return the value to pass to a sqlcipher3_wal_hook callback, the
39349 ** number of frames in the WAL at the point of the last commit since
39350 ** sqlcipher3WalCallback() was called.  If no commits have occurred since
39351 ** the last call, then return 0.
39352 */
39353 SQLCIPHER_PRIVATE int sqlcipher3WalCallback(Wal *pWal);
39354
39355 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
39356 ** by the pager layer on the database file.
39357 */
39358 SQLCIPHER_PRIVATE int sqlcipher3WalExclusiveMode(Wal *pWal, int op);
39359
39360 /* Return true if the argument is non-NULL and the WAL module is using
39361 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
39362 ** WAL module is using shared-memory, return false. 
39363 */
39364 SQLCIPHER_PRIVATE int sqlcipher3WalHeapMemory(Wal *pWal);
39365
39366 #endif /* ifndef SQLCIPHER_OMIT_WAL */
39367 #endif /* _WAL_H_ */
39368
39369 /************** End of wal.h *************************************************/
39370 /************** Continuing where we left off in pager.c **********************/
39371
39372
39373 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
39374 **
39375 ** This comment block describes invariants that hold when using a rollback
39376 ** journal.  These invariants do not apply for journal_mode=WAL,
39377 ** journal_mode=MEMORY, or journal_mode=OFF.
39378 **
39379 ** Within this comment block, a page is deemed to have been synced
39380 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
39381 ** Otherwise, the page is not synced until the xSync method of the VFS
39382 ** is called successfully on the file containing the page.
39383 **
39384 ** Definition:  A page of the database file is said to be "overwriteable" if
39385 ** one or more of the following are true about the page:
39386 ** 
39387 **     (a)  The original content of the page as it was at the beginning of
39388 **          the transaction has been written into the rollback journal and
39389 **          synced.
39390 ** 
39391 **     (b)  The page was a freelist leaf page at the start of the transaction.
39392 ** 
39393 **     (c)  The page number is greater than the largest page that existed in
39394 **          the database file at the start of the transaction.
39395 ** 
39396 ** (1) A page of the database file is never overwritten unless one of the
39397 **     following are true:
39398 ** 
39399 **     (a) The page and all other pages on the same sector are overwriteable.
39400 ** 
39401 **     (b) The atomic page write optimization is enabled, and the entire
39402 **         transaction other than the update of the transaction sequence
39403 **         number consists of a single page change.
39404 ** 
39405 ** (2) The content of a page written into the rollback journal exactly matches
39406 **     both the content in the database when the rollback journal was written
39407 **     and the content in the database at the beginning of the current
39408 **     transaction.
39409 ** 
39410 ** (3) Writes to the database file are an integer multiple of the page size
39411 **     in length and are aligned on a page boundary.
39412 ** 
39413 ** (4) Reads from the database file are either aligned on a page boundary and
39414 **     an integer multiple of the page size in length or are taken from the
39415 **     first 100 bytes of the database file.
39416 ** 
39417 ** (5) All writes to the database file are synced prior to the rollback journal
39418 **     being deleted, truncated, or zeroed.
39419 ** 
39420 ** (6) If a master journal file is used, then all writes to the database file
39421 **     are synced prior to the master journal being deleted.
39422 ** 
39423 ** Definition: Two databases (or the same database at two points it time)
39424 ** are said to be "logically equivalent" if they give the same answer to
39425 ** all queries.  Note in particular the the content of freelist leaf
39426 ** pages can be changed arbitarily without effecting the logical equivalence
39427 ** of the database.
39428 ** 
39429 ** (7) At any time, if any subset, including the empty set and the total set,
39430 **     of the unsynced changes to a rollback journal are removed and the 
39431 **     journal is rolled back, the resulting database file will be logical
39432 **     equivalent to the database file at the beginning of the transaction.
39433 ** 
39434 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
39435 **     is called to restore the database file to the same size it was at
39436 **     the beginning of the transaction.  (In some VFSes, the xTruncate
39437 **     method is a no-op, but that does not change the fact the SQLite will
39438 **     invoke it.)
39439 ** 
39440 ** (9) Whenever the database file is modified, at least one bit in the range
39441 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
39442 **     the EXCLUSIVE lock, thus signaling other connections on the same
39443 **     database to flush their caches.
39444 **
39445 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
39446 **      than one billion transactions.
39447 **
39448 ** (11) A database file is well-formed at the beginning and at the conclusion
39449 **      of every transaction.
39450 **
39451 ** (12) An EXCLUSIVE lock is held on the database file when writing to
39452 **      the database file.
39453 **
39454 ** (13) A SHARED lock is held on the database file while reading any
39455 **      content out of the database file.
39456 **
39457 ******************************************************************************/
39458
39459 /*
39460 ** Macros for troubleshooting.  Normally turned off
39461 */
39462 #if 0
39463 int sqlcipher3PagerTrace=1;  /* True to enable tracing */
39464 #define sqlcipher3DebugPrintf printf
39465 #define PAGERTRACE(X)     if( sqlcipher3PagerTrace ){ sqlcipher3DebugPrintf X; }
39466 #else
39467 #define PAGERTRACE(X)
39468 #endif
39469
39470 /*
39471 ** The following two macros are used within the PAGERTRACE() macros above
39472 ** to print out file-descriptors. 
39473 **
39474 ** PAGERID() takes a pointer to a Pager struct as its argument. The
39475 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlcipher3_file
39476 ** struct as its argument.
39477 */
39478 #define PAGERID(p) ((int)(p->fd))
39479 #define FILEHANDLEID(fd) ((int)fd)
39480
39481 /*
39482 ** The Pager.eState variable stores the current 'state' of a pager. A
39483 ** pager may be in any one of the seven states shown in the following
39484 ** state diagram.
39485 **
39486 **                            OPEN <------+------+
39487 **                              |         |      |
39488 **                              V         |      |
39489 **               +---------> READER-------+      |
39490 **               |              |                |
39491 **               |              V                |
39492 **               |<-------WRITER_LOCKED------> ERROR
39493 **               |              |                ^  
39494 **               |              V                |
39495 **               |<------WRITER_CACHEMOD-------->|
39496 **               |              |                |
39497 **               |              V                |
39498 **               |<-------WRITER_DBMOD---------->|
39499 **               |              |                |
39500 **               |              V                |
39501 **               +<------WRITER_FINISHED-------->+
39502 **
39503 **
39504 ** List of state transitions and the C [function] that performs each:
39505 ** 
39506 **   OPEN              -> READER              [sqlcipher3PagerSharedLock]
39507 **   READER            -> OPEN                [pager_unlock]
39508 **
39509 **   READER            -> WRITER_LOCKED       [sqlcipher3PagerBegin]
39510 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
39511 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
39512 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlcipher3PagerCommitPhaseOne]
39513 **   WRITER_***        -> READER              [pager_end_transaction]
39514 **
39515 **   WRITER_***        -> ERROR               [pager_error]
39516 **   ERROR             -> OPEN                [pager_unlock]
39517 ** 
39518 **
39519 **  OPEN:
39520 **
39521 **    The pager starts up in this state. Nothing is guaranteed in this
39522 **    state - the file may or may not be locked and the database size is
39523 **    unknown. The database may not be read or written.
39524 **
39525 **    * No read or write transaction is active.
39526 **    * Any lock, or no lock at all, may be held on the database file.
39527 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
39528 **
39529 **  READER:
39530 **
39531 **    In this state all the requirements for reading the database in 
39532 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
39533 **    was) in exclusive-locking mode, a user-level read transaction is 
39534 **    open. The database size is known in this state.
39535 **
39536 **    A connection running with locking_mode=normal enters this state when
39537 **    it opens a read-transaction on the database and returns to state
39538 **    OPEN after the read-transaction is completed. However a connection
39539 **    running in locking_mode=exclusive (including temp databases) remains in
39540 **    this state even after the read-transaction is closed. The only way
39541 **    a locking_mode=exclusive connection can transition from READER to OPEN
39542 **    is via the ERROR state (see below).
39543 ** 
39544 **    * A read transaction may be active (but a write-transaction cannot).
39545 **    * A SHARED or greater lock is held on the database file.
39546 **    * The dbSize variable may be trusted (even if a user-level read 
39547 **      transaction is not active). The dbOrigSize and dbFileSize variables
39548 **      may not be trusted at this point.
39549 **    * If the database is a WAL database, then the WAL connection is open.
39550 **    * Even if a read-transaction is not open, it is guaranteed that 
39551 **      there is no hot-journal in the file-system.
39552 **
39553 **  WRITER_LOCKED:
39554 **
39555 **    The pager moves to this state from READER when a write-transaction
39556 **    is first opened on the database. In WRITER_LOCKED state, all locks 
39557 **    required to start a write-transaction are held, but no actual 
39558 **    modifications to the cache or database have taken place.
39559 **
39560 **    In rollback mode, a RESERVED or (if the transaction was opened with 
39561 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
39562 **    moving to this state, but the journal file is not written to or opened 
39563 **    to in this state. If the transaction is committed or rolled back while 
39564 **    in WRITER_LOCKED state, all that is required is to unlock the database 
39565 **    file.
39566 **
39567 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
39568 **    If the connection is running with locking_mode=exclusive, an attempt
39569 **    is made to obtain an EXCLUSIVE lock on the database file.
39570 **
39571 **    * A write transaction is active.
39572 **    * If the connection is open in rollback-mode, a RESERVED or greater 
39573 **      lock is held on the database file.
39574 **    * If the connection is open in WAL-mode, a WAL write transaction
39575 **      is open (i.e. sqlcipher3WalBeginWriteTransaction() has been successfully
39576 **      called).
39577 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
39578 **    * The contents of the pager cache have not been modified.
39579 **    * The journal file may or may not be open.
39580 **    * Nothing (not even the first header) has been written to the journal.
39581 **
39582 **  WRITER_CACHEMOD:
39583 **
39584 **    A pager moves from WRITER_LOCKED state to this state when a page is
39585 **    first modified by the upper layer. In rollback mode the journal file
39586 **    is opened (if it is not already open) and a header written to the
39587 **    start of it. The database file on disk has not been modified.
39588 **
39589 **    * A write transaction is active.
39590 **    * A RESERVED or greater lock is held on the database file.
39591 **    * The journal file is open and the first header has been written 
39592 **      to it, but the header has not been synced to disk.
39593 **    * The contents of the page cache have been modified.
39594 **
39595 **  WRITER_DBMOD:
39596 **
39597 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
39598 **    when it modifies the contents of the database file. WAL connections
39599 **    never enter this state (since they do not modify the database file,
39600 **    just the log file).
39601 **
39602 **    * A write transaction is active.
39603 **    * An EXCLUSIVE or greater lock is held on the database file.
39604 **    * The journal file is open and the first header has been written 
39605 **      and synced to disk.
39606 **    * The contents of the page cache have been modified (and possibly
39607 **      written to disk).
39608 **
39609 **  WRITER_FINISHED:
39610 **
39611 **    It is not possible for a WAL connection to enter this state.
39612 **
39613 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
39614 **    state after the entire transaction has been successfully written into the
39615 **    database file. In this state the transaction may be committed simply
39616 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
39617 **    not possible to modify the database further. At this point, the upper 
39618 **    layer must either commit or rollback the transaction.
39619 **
39620 **    * A write transaction is active.
39621 **    * An EXCLUSIVE or greater lock is held on the database file.
39622 **    * All writing and syncing of journal and database data has finished.
39623 **      If no error occured, all that remains is to finalize the journal to
39624 **      commit the transaction. If an error did occur, the caller will need
39625 **      to rollback the transaction. 
39626 **
39627 **  ERROR:
39628 **
39629 **    The ERROR state is entered when an IO or disk-full error (including
39630 **    SQLCIPHER_IOERR_NOMEM) occurs at a point in the code that makes it 
39631 **    difficult to be sure that the in-memory pager state (cache contents, 
39632 **    db size etc.) are consistent with the contents of the file-system.
39633 **
39634 **    Temporary pager files may enter the ERROR state, but in-memory pagers
39635 **    cannot.
39636 **
39637 **    For example, if an IO error occurs while performing a rollback, 
39638 **    the contents of the page-cache may be left in an inconsistent state.
39639 **    At this point it would be dangerous to change back to READER state
39640 **    (as usually happens after a rollback). Any subsequent readers might
39641 **    report database corruption (due to the inconsistent cache), and if
39642 **    they upgrade to writers, they may inadvertently corrupt the database
39643 **    file. To avoid this hazard, the pager switches into the ERROR state
39644 **    instead of READER following such an error.
39645 **
39646 **    Once it has entered the ERROR state, any attempt to use the pager
39647 **    to read or write data returns an error. Eventually, once all 
39648 **    outstanding transactions have been abandoned, the pager is able to
39649 **    transition back to OPEN state, discarding the contents of the 
39650 **    page-cache and any other in-memory state at the same time. Everything
39651 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
39652 **    when a read-transaction is next opened on the pager (transitioning
39653 **    the pager into READER state). At that point the system has recovered 
39654 **    from the error.
39655 **
39656 **    Specifically, the pager jumps into the ERROR state if:
39657 **
39658 **      1. An error occurs while attempting a rollback. This happens in
39659 **         function sqlcipher3PagerRollback().
39660 **
39661 **      2. An error occurs while attempting to finalize a journal file
39662 **         following a commit in function sqlcipher3PagerCommitPhaseTwo().
39663 **
39664 **      3. An error occurs while attempting to write to the journal or
39665 **         database file in function pagerStress() in order to free up
39666 **         memory.
39667 **
39668 **    In other cases, the error is returned to the b-tree layer. The b-tree
39669 **    layer then attempts a rollback operation. If the error condition 
39670 **    persists, the pager enters the ERROR state via condition (1) above.
39671 **
39672 **    Condition (3) is necessary because it can be triggered by a read-only
39673 **    statement executed within a transaction. In this case, if the error
39674 **    code were simply returned to the user, the b-tree layer would not
39675 **    automatically attempt a rollback, as it assumes that an error in a
39676 **    read-only statement cannot leave the pager in an internally inconsistent 
39677 **    state.
39678 **
39679 **    * The Pager.errCode variable is set to something other than SQLCIPHER_OK.
39680 **    * There are one or more outstanding references to pages (after the
39681 **      last reference is dropped the pager should move back to OPEN state).
39682 **    * The pager is not an in-memory pager.
39683 **    
39684 **
39685 ** Notes:
39686 **
39687 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
39688 **     connection is open in WAL mode. A WAL connection is always in one
39689 **     of the first four states.
39690 **
39691 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
39692 **     state. There are two exceptions: immediately after exclusive-mode has
39693 **     been turned on (and before any read or write transactions are 
39694 **     executed), and when the pager is leaving the "error state".
39695 **
39696 **   * See also: assert_pager_state().
39697 */
39698 #define PAGER_OPEN                  0
39699 #define PAGER_READER                1
39700 #define PAGER_WRITER_LOCKED         2
39701 #define PAGER_WRITER_CACHEMOD       3
39702 #define PAGER_WRITER_DBMOD          4
39703 #define PAGER_WRITER_FINISHED       5
39704 #define PAGER_ERROR                 6
39705
39706 /*
39707 ** The Pager.eLock variable is almost always set to one of the 
39708 ** following locking-states, according to the lock currently held on
39709 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
39710 ** This variable is kept up to date as locks are taken and released by
39711 ** the pagerLockDb() and pagerUnlockDb() wrappers.
39712 **
39713 ** If the VFS xLock() or xUnlock() returns an error other than SQLCIPHER_BUSY
39714 ** (i.e. one of the SQLCIPHER_IOERR subtypes), it is not clear whether or not
39715 ** the operation was successful. In these circumstances pagerLockDb() and
39716 ** pagerUnlockDb() take a conservative approach - eLock is always updated
39717 ** when unlocking the file, and only updated when locking the file if the
39718 ** VFS call is successful. This way, the Pager.eLock variable may be set
39719 ** to a less exclusive (lower) value than the lock that is actually held
39720 ** at the system level, but it is never set to a more exclusive value.
39721 **
39722 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
39723 ** be a few redundant xLock() calls or a lock may be held for longer than
39724 ** required, but nothing really goes wrong.
39725 **
39726 ** The exception is when the database file is unlocked as the pager moves
39727 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
39728 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
39729 ** transition, by the same pager or any other). If the call to xUnlock()
39730 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
39731 ** can confuse the call to xCheckReservedLock() call made later as part
39732 ** of hot-journal detection.
39733 **
39734 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
39735 ** lock held by this process or any others". So xCheckReservedLock may 
39736 ** return true because the caller itself is holding an EXCLUSIVE lock (but
39737 ** doesn't know it because of a previous error in xUnlock). If this happens
39738 ** a hot-journal may be mistaken for a journal being created by an active
39739 ** transaction in another process, causing SQLite to read from the database
39740 ** without rolling it back.
39741 **
39742 ** To work around this, if a call to xUnlock() fails when unlocking the
39743 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
39744 ** is only changed back to a real locking state after a successful call
39745 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
39746 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
39747 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
39748 ** lock on the database file before attempting to roll it back. See function
39749 ** PagerSharedLock() for more detail.
39750 **
39751 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
39752 ** PAGER_OPEN state.
39753 */
39754 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
39755
39756 /*
39757 ** A macro used for invoking the codec if there is one
39758 */
39759 #ifdef SQLCIPHER_HAS_CODEC
39760 # define CODEC1(P,D,N,X,E) \
39761     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
39762 # define CODEC2(P,D,N,X,E,O) \
39763     if( P->xCodec==0 ){ O=(char*)D; }else \
39764     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
39765 #else
39766 # define CODEC1(P,D,N,X,E)   /* NO-OP */
39767 # define CODEC2(P,D,N,X,E,O) O=(char*)D
39768 #endif
39769
39770 /*
39771 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
39772 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
39773 ** This could conceivably cause corruption following a power failure on
39774 ** such a system. This is currently an undocumented limit.
39775 */
39776 #define MAX_SECTOR_SIZE 0x10000
39777
39778 /*
39779 ** An instance of the following structure is allocated for each active
39780 ** savepoint and statement transaction in the system. All such structures
39781 ** are stored in the Pager.aSavepoint[] array, which is allocated and
39782 ** resized using sqlcipher3Realloc().
39783 **
39784 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
39785 ** set to 0. If a journal-header is written into the main journal while
39786 ** the savepoint is active, then iHdrOffset is set to the byte offset 
39787 ** immediately following the last journal record written into the main
39788 ** journal before the journal-header. This is required during savepoint
39789 ** rollback (see pagerPlaybackSavepoint()).
39790 */
39791 typedef struct PagerSavepoint PagerSavepoint;
39792 struct PagerSavepoint {
39793   i64 iOffset;                 /* Starting offset in main journal */
39794   i64 iHdrOffset;              /* See above */
39795   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
39796   Pgno nOrig;                  /* Original number of pages in file */
39797   Pgno iSubRec;                /* Index of first record in sub-journal */
39798 #ifndef SQLCIPHER_OMIT_WAL
39799   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
39800 #endif
39801 };
39802
39803 /*
39804 ** A open page cache is an instance of struct Pager. A description of
39805 ** some of the more important member variables follows:
39806 **
39807 ** eState
39808 **
39809 **   The current 'state' of the pager object. See the comment and state
39810 **   diagram above for a description of the pager state.
39811 **
39812 ** eLock
39813 **
39814 **   For a real on-disk database, the current lock held on the database file -
39815 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
39816 **
39817 **   For a temporary or in-memory database (neither of which require any
39818 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
39819 **   databases always have Pager.exclusiveMode==1, this tricks the pager
39820 **   logic into thinking that it already has all the locks it will ever
39821 **   need (and no reason to release them).
39822 **
39823 **   In some (obscure) circumstances, this variable may also be set to
39824 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
39825 **   details.
39826 **
39827 ** changeCountDone
39828 **
39829 **   This boolean variable is used to make sure that the change-counter 
39830 **   (the 4-byte header field at byte offset 24 of the database file) is 
39831 **   not updated more often than necessary. 
39832 **
39833 **   It is set to true when the change-counter field is updated, which 
39834 **   can only happen if an exclusive lock is held on the database file.
39835 **   It is cleared (set to false) whenever an exclusive lock is 
39836 **   relinquished on the database file. Each time a transaction is committed,
39837 **   The changeCountDone flag is inspected. If it is true, the work of
39838 **   updating the change-counter is omitted for the current transaction.
39839 **
39840 **   This mechanism means that when running in exclusive mode, a connection 
39841 **   need only update the change-counter once, for the first transaction
39842 **   committed.
39843 **
39844 ** setMaster
39845 **
39846 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
39847 **   (or may not) specify a master-journal name to be written into the 
39848 **   journal file before it is synced to disk.
39849 **
39850 **   Whether or not a journal file contains a master-journal pointer affects 
39851 **   the way in which the journal file is finalized after the transaction is 
39852 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
39853 **   If a journal file does not contain a master-journal pointer, it is
39854 **   finalized by overwriting the first journal header with zeroes. If
39855 **   it does contain a master-journal pointer the journal file is finalized 
39856 **   by truncating it to zero bytes, just as if the connection were 
39857 **   running in "journal_mode=truncate" mode.
39858 **
39859 **   Journal files that contain master journal pointers cannot be finalized
39860 **   simply by overwriting the first journal-header with zeroes, as the
39861 **   master journal pointer could interfere with hot-journal rollback of any
39862 **   subsequently interrupted transaction that reuses the journal file.
39863 **
39864 **   The flag is cleared as soon as the journal file is finalized (either
39865 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
39866 **   journal file from being successfully finalized, the setMaster flag
39867 **   is cleared anyway (and the pager will move to ERROR state).
39868 **
39869 ** doNotSpill, doNotSyncSpill
39870 **
39871 **   These two boolean variables control the behaviour of cache-spills
39872 **   (calls made by the pcache module to the pagerStress() routine to
39873 **   write cached data to the file-system in order to free up memory).
39874 **
39875 **   When doNotSpill is non-zero, writing to the database from pagerStress()
39876 **   is disabled altogether. This is done in a very obscure case that
39877 **   comes up during savepoint rollback that requires the pcache module
39878 **   to allocate a new page to prevent the journal file from being written
39879 **   while it is being traversed by code in pager_playback().
39880 ** 
39881 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
39882 **   is permitted, but syncing the journal file is not. This flag is set
39883 **   by sqlcipher3PagerWrite() when the file-system sector-size is larger than
39884 **   the database page-size in order to prevent a journal sync from happening 
39885 **   in between the journalling of two pages on the same sector. 
39886 **
39887 ** subjInMemory
39888 **
39889 **   This is a boolean variable. If true, then any required sub-journal
39890 **   is opened as an in-memory journal file. If false, then in-memory
39891 **   sub-journals are only used for in-memory pager files.
39892 **
39893 **   This variable is updated by the upper layer each time a new 
39894 **   write-transaction is opened.
39895 **
39896 ** dbSize, dbOrigSize, dbFileSize
39897 **
39898 **   Variable dbSize is set to the number of pages in the database file.
39899 **   It is valid in PAGER_READER and higher states (all states except for
39900 **   OPEN and ERROR). 
39901 **
39902 **   dbSize is set based on the size of the database file, which may be 
39903 **   larger than the size of the database (the value stored at offset
39904 **   28 of the database header by the btree). If the size of the file
39905 **   is not an integer multiple of the page-size, the value stored in
39906 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
39907 **   Except, any file that is greater than 0 bytes in size is considered
39908 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
39909 **   to dbSize==1).
39910 **
39911 **   During a write-transaction, if pages with page-numbers greater than
39912 **   dbSize are modified in the cache, dbSize is updated accordingly.
39913 **   Similarly, if the database is truncated using PagerTruncateImage(), 
39914 **   dbSize is updated.
39915 **
39916 **   Variables dbOrigSize and dbFileSize are valid in states 
39917 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
39918 **   variable at the start of the transaction. It is used during rollback,
39919 **   and to determine whether or not pages need to be journalled before
39920 **   being modified.
39921 **
39922 **   Throughout a write-transaction, dbFileSize contains the size of
39923 **   the file on disk in pages. It is set to a copy of dbSize when the
39924 **   write-transaction is first opened, and updated when VFS calls are made
39925 **   to write or truncate the database file on disk. 
39926 **
39927 **   The only reason the dbFileSize variable is required is to suppress 
39928 **   unnecessary calls to xTruncate() after committing a transaction. If, 
39929 **   when a transaction is committed, the dbFileSize variable indicates 
39930 **   that the database file is larger than the database image (Pager.dbSize), 
39931 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
39932 **   to measure the database file on disk, and then truncates it if required.
39933 **   dbFileSize is not used when rolling back a transaction. In this case
39934 **   pager_truncate() is called unconditionally (which means there may be
39935 **   a call to xFilesize() that is not strictly required). In either case,
39936 **   pager_truncate() may cause the file to become smaller or larger.
39937 **
39938 ** dbHintSize
39939 **
39940 **   The dbHintSize variable is used to limit the number of calls made to
39941 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
39942 **
39943 **   dbHintSize is set to a copy of the dbSize variable when a
39944 **   write-transaction is opened (at the same time as dbFileSize and
39945 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
39946 **   dbHintSize is increased to the number of pages that correspond to the
39947 **   size-hint passed to the method call. See pager_write_pagelist() for 
39948 **   details.
39949 **
39950 ** errCode
39951 **
39952 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
39953 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
39954 **   is always set to SQLCIPHER_FULL, SQLCIPHER_IOERR or one of the SQLCIPHER_IOERR_XXX 
39955 **   sub-codes.
39956 */
39957 struct Pager {
39958   sqlcipher3_vfs *pVfs;          /* OS functions to use for IO */
39959   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
39960   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
39961   u8 useJournal;              /* Use a rollback journal on this file */
39962   u8 noReadlock;              /* Do not bother to obtain readlocks */
39963   u8 noSync;                  /* Do not sync the journal if true */
39964   u8 fullSync;                /* Do extra syncs of the journal for robustness */
39965   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
39966   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
39967   u8 tempFile;                /* zFilename is a temporary file */
39968   u8 readOnly;                /* True for a read-only database */
39969   u8 memDb;                   /* True to inhibit all file I/O */
39970
39971   /**************************************************************************
39972   ** The following block contains those class members that change during
39973   ** routine opertion.  Class members not in this block are either fixed
39974   ** when the pager is first created or else only change when there is a
39975   ** significant mode change (such as changing the page_size, locking_mode,
39976   ** or the journal_mode).  From another view, these class members describe
39977   ** the "state" of the pager, while other class members describe the
39978   ** "configuration" of the pager.
39979   */
39980   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
39981   u8 eLock;                   /* Current lock held on database file */
39982   u8 changeCountDone;         /* Set after incrementing the change-counter */
39983   u8 setMaster;               /* True if a m-j name has been written to jrnl */
39984   u8 doNotSpill;              /* Do not spill the cache when non-zero */
39985   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
39986   u8 subjInMemory;            /* True to use in-memory sub-journals */
39987   Pgno dbSize;                /* Number of pages in the database */
39988   Pgno dbOrigSize;            /* dbSize before the current transaction */
39989   Pgno dbFileSize;            /* Number of pages in the database file */
39990   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
39991   int errCode;                /* One of several kinds of errors */
39992   int nRec;                   /* Pages journalled since last j-header written */
39993   u32 cksumInit;              /* Quasi-random value added to every checksum */
39994   u32 nSubRec;                /* Number of records written to sub-journal */
39995   Bitvec *pInJournal;         /* One bit for each page in the database file */
39996   sqlcipher3_file *fd;           /* File descriptor for database */
39997   sqlcipher3_file *jfd;          /* File descriptor for main journal */
39998   sqlcipher3_file *sjfd;         /* File descriptor for sub-journal */
39999   i64 journalOff;             /* Current write offset in the journal file */
40000   i64 journalHdr;             /* Byte offset to previous journal header */
40001   sqlcipher3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
40002   PagerSavepoint *aSavepoint; /* Array of active savepoints */
40003   int nSavepoint;             /* Number of elements in aSavepoint[] */
40004   char dbFileVers[16];        /* Changes whenever database file changes */
40005   /*
40006   ** End of the routinely-changing class members
40007   ***************************************************************************/
40008
40009   u16 nExtra;                 /* Add this many bytes to each in-memory page */
40010   i16 nReserve;               /* Number of unused bytes at end of each page */
40011   u32 vfsFlags;               /* Flags for sqlcipher3_vfs.xOpen() */
40012   u32 sectorSize;             /* Assumed sector size during rollback */
40013   int pageSize;               /* Number of bytes in a page */
40014   Pgno mxPgno;                /* Maximum allowed size of the database */
40015   i64 journalSizeLimit;       /* Size limit for persistent journal files */
40016   char *zFilename;            /* Name of the database file */
40017   char *zJournal;             /* Name of the journal file */
40018   int (*xBusyHandler)(void*); /* Function to call when busy */
40019   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
40020   int nHit, nMiss;            /* Total cache hits and misses */
40021 #ifdef SQLCIPHER_TEST
40022   int nRead, nWrite;          /* Database pages read/written */
40023 #endif
40024   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
40025 #ifdef SQLCIPHER_HAS_CODEC
40026   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
40027   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
40028   void (*xCodecFree)(void*);             /* Destructor for the codec */
40029   void *pCodec;               /* First argument to xCodec... methods */
40030 #endif
40031   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
40032   PCache *pPCache;            /* Pointer to page cache object */
40033 #ifndef SQLCIPHER_OMIT_WAL
40034   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
40035   char *zWal;                 /* File name for write-ahead log */
40036 #endif
40037 };
40038
40039 /*
40040 ** The following global variables hold counters used for
40041 ** testing purposes only.  These variables do not exist in
40042 ** a non-testing build.  These variables are not thread-safe.
40043 */
40044 #ifdef SQLCIPHER_TEST
40045 SQLCIPHER_API int sqlcipher3_pager_readdb_count = 0;    /* Number of full pages read from DB */
40046 SQLCIPHER_API int sqlcipher3_pager_writedb_count = 0;   /* Number of full pages written to DB */
40047 SQLCIPHER_API int sqlcipher3_pager_writej_count = 0;    /* Number of pages written to journal */
40048 # define PAGER_INCR(v)  v++
40049 #else
40050 # define PAGER_INCR(v)
40051 #endif
40052
40053
40054
40055 /*
40056 ** Journal files begin with the following magic string.  The data
40057 ** was obtained from /dev/random.  It is used only as a sanity check.
40058 **
40059 ** Since version 2.8.0, the journal format contains additional sanity
40060 ** checking information.  If the power fails while the journal is being
40061 ** written, semi-random garbage data might appear in the journal
40062 ** file after power is restored.  If an attempt is then made
40063 ** to roll the journal back, the database could be corrupted.  The additional
40064 ** sanity checking data is an attempt to discover the garbage in the
40065 ** journal and ignore it.
40066 **
40067 ** The sanity checking information for the new journal format consists
40068 ** of a 32-bit checksum on each page of data.  The checksum covers both
40069 ** the page number and the pPager->pageSize bytes of data for the page.
40070 ** This cksum is initialized to a 32-bit random value that appears in the
40071 ** journal file right after the header.  The random initializer is important,
40072 ** because garbage data that appears at the end of a journal is likely
40073 ** data that was once in other files that have now been deleted.  If the
40074 ** garbage data came from an obsolete journal file, the checksums might
40075 ** be correct.  But by initializing the checksum to random value which
40076 ** is different for every journal, we minimize that risk.
40077 */
40078 static const unsigned char aJournalMagic[] = {
40079   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
40080 };
40081
40082 /*
40083 ** The size of the of each page record in the journal is given by
40084 ** the following macro.
40085 */
40086 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
40087
40088 /*
40089 ** The journal header size for this pager. This is usually the same 
40090 ** size as a single disk sector. See also setSectorSize().
40091 */
40092 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
40093
40094 /*
40095 ** The macro MEMDB is true if we are dealing with an in-memory database.
40096 ** We do this as a macro so that if the SQLCIPHER_OMIT_MEMORYDB macro is set,
40097 ** the value of MEMDB will be a constant and the compiler will optimize
40098 ** out code that would never execute.
40099 */
40100 #ifdef SQLCIPHER_OMIT_MEMORYDB
40101 # define MEMDB 0
40102 #else
40103 # define MEMDB pPager->memDb
40104 #endif
40105
40106 /*
40107 ** The maximum legal page number is (2^31 - 1).
40108 */
40109 #define PAGER_MAX_PGNO 2147483647
40110
40111 /*
40112 ** The argument to this macro is a file descriptor (type sqlcipher3_file*).
40113 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
40114 **
40115 ** This is so that expressions can be written as:
40116 **
40117 **   if( isOpen(pPager->jfd) ){ ...
40118 **
40119 ** instead of
40120 **
40121 **   if( pPager->jfd->pMethods ){ ...
40122 */
40123 #define isOpen(pFd) ((pFd)->pMethods)
40124
40125 /*
40126 ** Return true if this pager uses a write-ahead log instead of the usual
40127 ** rollback journal. Otherwise false.
40128 */
40129 #ifndef SQLCIPHER_OMIT_WAL
40130 static int pagerUseWal(Pager *pPager){
40131   return (pPager->pWal!=0);
40132 }
40133 #else
40134 # define pagerUseWal(x) 0
40135 # define pagerRollbackWal(x) 0
40136 # define pagerWalFrames(v,w,x,y,z) 0
40137 # define pagerOpenWalIfPresent(z) SQLCIPHER_OK
40138 # define pagerBeginReadTransaction(z) SQLCIPHER_OK
40139 #endif
40140
40141 #ifndef NDEBUG 
40142 /*
40143 ** Usage:
40144 **
40145 **   assert( assert_pager_state(pPager) );
40146 **
40147 ** This function runs many asserts to try to find inconsistencies in
40148 ** the internal state of the Pager object.
40149 */
40150 static int assert_pager_state(Pager *p){
40151   Pager *pPager = p;
40152
40153   /* State must be valid. */
40154   assert( p->eState==PAGER_OPEN
40155        || p->eState==PAGER_READER
40156        || p->eState==PAGER_WRITER_LOCKED
40157        || p->eState==PAGER_WRITER_CACHEMOD
40158        || p->eState==PAGER_WRITER_DBMOD
40159        || p->eState==PAGER_WRITER_FINISHED
40160        || p->eState==PAGER_ERROR
40161   );
40162
40163   /* Regardless of the current state, a temp-file connection always behaves
40164   ** as if it has an exclusive lock on the database file. It never updates
40165   ** the change-counter field, so the changeCountDone flag is always set.
40166   */
40167   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
40168   assert( p->tempFile==0 || pPager->changeCountDone );
40169
40170   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
40171   ** And if the journal-mode is "OFF", the journal file must not be open.
40172   */
40173   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
40174   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
40175
40176   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
40177   ** this means an in-memory pager performs no IO at all, it cannot encounter 
40178   ** either SQLCIPHER_IOERR or SQLCIPHER_FULL during rollback or while finalizing 
40179   ** a journal file. (although the in-memory journal implementation may 
40180   ** return SQLCIPHER_IOERR_NOMEM while the journal file is being written). It 
40181   ** is therefore not possible for an in-memory pager to enter the ERROR 
40182   ** state.
40183   */
40184   if( MEMDB ){
40185     assert( p->noSync );
40186     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
40187          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
40188     );
40189     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
40190     assert( pagerUseWal(p)==0 );
40191   }
40192
40193   /* If changeCountDone is set, a RESERVED lock or greater must be held
40194   ** on the file.
40195   */
40196   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
40197   assert( p->eLock!=PENDING_LOCK );
40198
40199   switch( p->eState ){
40200     case PAGER_OPEN:
40201       assert( !MEMDB );
40202       assert( pPager->errCode==SQLCIPHER_OK );
40203       assert( sqlcipher3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
40204       break;
40205
40206     case PAGER_READER:
40207       assert( pPager->errCode==SQLCIPHER_OK );
40208       assert( p->eLock!=UNKNOWN_LOCK );
40209       assert( p->eLock>=SHARED_LOCK || p->noReadlock );
40210       break;
40211
40212     case PAGER_WRITER_LOCKED:
40213       assert( p->eLock!=UNKNOWN_LOCK );
40214       assert( pPager->errCode==SQLCIPHER_OK );
40215       if( !pagerUseWal(pPager) ){
40216         assert( p->eLock>=RESERVED_LOCK );
40217       }
40218       assert( pPager->dbSize==pPager->dbOrigSize );
40219       assert( pPager->dbOrigSize==pPager->dbFileSize );
40220       assert( pPager->dbOrigSize==pPager->dbHintSize );
40221       assert( pPager->setMaster==0 );
40222       break;
40223
40224     case PAGER_WRITER_CACHEMOD:
40225       assert( p->eLock!=UNKNOWN_LOCK );
40226       assert( pPager->errCode==SQLCIPHER_OK );
40227       if( !pagerUseWal(pPager) ){
40228         /* It is possible that if journal_mode=wal here that neither the
40229         ** journal file nor the WAL file are open. This happens during
40230         ** a rollback transaction that switches from journal_mode=off
40231         ** to journal_mode=wal.
40232         */
40233         assert( p->eLock>=RESERVED_LOCK );
40234         assert( isOpen(p->jfd) 
40235              || p->journalMode==PAGER_JOURNALMODE_OFF 
40236              || p->journalMode==PAGER_JOURNALMODE_WAL 
40237         );
40238       }
40239       assert( pPager->dbOrigSize==pPager->dbFileSize );
40240       assert( pPager->dbOrigSize==pPager->dbHintSize );
40241       break;
40242
40243     case PAGER_WRITER_DBMOD:
40244       assert( p->eLock==EXCLUSIVE_LOCK );
40245       assert( pPager->errCode==SQLCIPHER_OK );
40246       assert( !pagerUseWal(pPager) );
40247       assert( p->eLock>=EXCLUSIVE_LOCK );
40248       assert( isOpen(p->jfd) 
40249            || p->journalMode==PAGER_JOURNALMODE_OFF 
40250            || p->journalMode==PAGER_JOURNALMODE_WAL 
40251       );
40252       assert( pPager->dbOrigSize<=pPager->dbHintSize );
40253       break;
40254
40255     case PAGER_WRITER_FINISHED:
40256       assert( p->eLock==EXCLUSIVE_LOCK );
40257       assert( pPager->errCode==SQLCIPHER_OK );
40258       assert( !pagerUseWal(pPager) );
40259       assert( isOpen(p->jfd) 
40260            || p->journalMode==PAGER_JOURNALMODE_OFF 
40261            || p->journalMode==PAGER_JOURNALMODE_WAL 
40262       );
40263       break;
40264
40265     case PAGER_ERROR:
40266       /* There must be at least one outstanding reference to the pager if
40267       ** in ERROR state. Otherwise the pager should have already dropped
40268       ** back to OPEN state.
40269       */
40270       assert( pPager->errCode!=SQLCIPHER_OK );
40271       assert( sqlcipher3PcacheRefCount(pPager->pPCache)>0 );
40272       break;
40273   }
40274
40275   return 1;
40276 }
40277 #endif /* ifndef NDEBUG */
40278
40279 #ifdef SQLCIPHER_DEBUG 
40280 /*
40281 ** Return a pointer to a human readable string in a static buffer
40282 ** containing the state of the Pager object passed as an argument. This
40283 ** is intended to be used within debuggers. For example, as an alternative
40284 ** to "print *pPager" in gdb:
40285 **
40286 ** (gdb) printf "%s", print_pager_state(pPager)
40287 */
40288 static char *print_pager_state(Pager *p){
40289   static char zRet[1024];
40290
40291   sqlcipher3_snprintf(1024, zRet,
40292       "Filename:      %s\n"
40293       "State:         %s errCode=%d\n"
40294       "Lock:          %s\n"
40295       "Locking mode:  locking_mode=%s\n"
40296       "Journal mode:  journal_mode=%s\n"
40297       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
40298       "Journal:       journalOff=%lld journalHdr=%lld\n"
40299       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
40300       , p->zFilename
40301       , p->eState==PAGER_OPEN            ? "OPEN" :
40302         p->eState==PAGER_READER          ? "READER" :
40303         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
40304         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
40305         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
40306         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
40307         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
40308       , (int)p->errCode
40309       , p->eLock==NO_LOCK         ? "NO_LOCK" :
40310         p->eLock==RESERVED_LOCK   ? "RESERVED" :
40311         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
40312         p->eLock==SHARED_LOCK     ? "SHARED" :
40313         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
40314       , p->exclusiveMode ? "exclusive" : "normal"
40315       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
40316         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
40317         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
40318         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
40319         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
40320         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
40321       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
40322       , p->journalOff, p->journalHdr
40323       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
40324   );
40325
40326   return zRet;
40327 }
40328 #endif
40329
40330 /*
40331 ** Return true if it is necessary to write page *pPg into the sub-journal.
40332 ** A page needs to be written into the sub-journal if there exists one
40333 ** or more open savepoints for which:
40334 **
40335 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
40336 **   * The bit corresponding to the page-number is not set in
40337 **     PagerSavepoint.pInSavepoint.
40338 */
40339 static int subjRequiresPage(PgHdr *pPg){
40340   Pgno pgno = pPg->pgno;
40341   Pager *pPager = pPg->pPager;
40342   int i;
40343   for(i=0; i<pPager->nSavepoint; i++){
40344     PagerSavepoint *p = &pPager->aSavepoint[i];
40345     if( p->nOrig>=pgno && 0==sqlcipher3BitvecTest(p->pInSavepoint, pgno) ){
40346       return 1;
40347     }
40348   }
40349   return 0;
40350 }
40351
40352 /*
40353 ** Return true if the page is already in the journal file.
40354 */
40355 static int pageInJournal(PgHdr *pPg){
40356   return sqlcipher3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
40357 }
40358
40359 /*
40360 ** Read a 32-bit integer from the given file descriptor.  Store the integer
40361 ** that is read in *pRes.  Return SQLCIPHER_OK if everything worked, or an
40362 ** error code is something goes wrong.
40363 **
40364 ** All values are stored on disk as big-endian.
40365 */
40366 static int read32bits(sqlcipher3_file *fd, i64 offset, u32 *pRes){
40367   unsigned char ac[4];
40368   int rc = sqlcipher3OsRead(fd, ac, sizeof(ac), offset);
40369   if( rc==SQLCIPHER_OK ){
40370     *pRes = sqlcipher3Get4byte(ac);
40371   }
40372   return rc;
40373 }
40374
40375 /*
40376 ** Write a 32-bit integer into a string buffer in big-endian byte order.
40377 */
40378 #define put32bits(A,B)  sqlcipher3Put4byte((u8*)A,B)
40379
40380
40381 /*
40382 ** Write a 32-bit integer into the given file descriptor.  Return SQLCIPHER_OK
40383 ** on success or an error code is something goes wrong.
40384 */
40385 static int write32bits(sqlcipher3_file *fd, i64 offset, u32 val){
40386   char ac[4];
40387   put32bits(ac, val);
40388   return sqlcipher3OsWrite(fd, ac, 4, offset);
40389 }
40390
40391 /*
40392 ** Unlock the database file to level eLock, which must be either NO_LOCK
40393 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
40394 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
40395 **
40396 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
40397 ** called, do not modify it. See the comment above the #define of 
40398 ** UNKNOWN_LOCK for an explanation of this.
40399 */
40400 static int pagerUnlockDb(Pager *pPager, int eLock){
40401   int rc = SQLCIPHER_OK;
40402
40403   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
40404   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
40405   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
40406   if( isOpen(pPager->fd) ){
40407     assert( pPager->eLock>=eLock );
40408     rc = sqlcipher3OsUnlock(pPager->fd, eLock);
40409     if( pPager->eLock!=UNKNOWN_LOCK ){
40410       pPager->eLock = (u8)eLock;
40411     }
40412     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
40413   }
40414   return rc;
40415 }
40416
40417 /*
40418 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
40419 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
40420 ** Pager.eLock variable to the new locking state. 
40421 **
40422 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
40423 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
40424 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
40425 ** of this.
40426 */
40427 static int pagerLockDb(Pager *pPager, int eLock){
40428   int rc = SQLCIPHER_OK;
40429
40430   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
40431   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
40432     rc = sqlcipher3OsLock(pPager->fd, eLock);
40433     if( rc==SQLCIPHER_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
40434       pPager->eLock = (u8)eLock;
40435       IOTRACE(("LOCK %p %d\n", pPager, eLock))
40436     }
40437   }
40438   return rc;
40439 }
40440
40441 /*
40442 ** This function determines whether or not the atomic-write optimization
40443 ** can be used with this pager. The optimization can be used if:
40444 **
40445 **  (a) the value returned by OsDeviceCharacteristics() indicates that
40446 **      a database page may be written atomically, and
40447 **  (b) the value returned by OsSectorSize() is less than or equal
40448 **      to the page size.
40449 **
40450 ** The optimization is also always enabled for temporary files. It is
40451 ** an error to call this function if pPager is opened on an in-memory
40452 ** database.
40453 **
40454 ** If the optimization cannot be used, 0 is returned. If it can be used,
40455 ** then the value returned is the size of the journal file when it
40456 ** contains rollback data for exactly one page.
40457 */
40458 #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
40459 static int jrnlBufferSize(Pager *pPager){
40460   assert( !MEMDB );
40461   if( !pPager->tempFile ){
40462     int dc;                           /* Device characteristics */
40463     int nSector;                      /* Sector size */
40464     int szPage;                       /* Page size */
40465
40466     assert( isOpen(pPager->fd) );
40467     dc = sqlcipher3OsDeviceCharacteristics(pPager->fd);
40468     nSector = pPager->sectorSize;
40469     szPage = pPager->pageSize;
40470
40471     assert(SQLCIPHER_IOCAP_ATOMIC512==(512>>8));
40472     assert(SQLCIPHER_IOCAP_ATOMIC64K==(65536>>8));
40473     if( 0==(dc&(SQLCIPHER_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
40474       return 0;
40475     }
40476   }
40477
40478   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
40479 }
40480 #endif
40481
40482 /*
40483 ** If SQLCIPHER_CHECK_PAGES is defined then we do some sanity checking
40484 ** on the cache using a hash function.  This is used for testing
40485 ** and debugging only.
40486 */
40487 #ifdef SQLCIPHER_CHECK_PAGES
40488 /*
40489 ** Return a 32-bit hash of the page data for pPage.
40490 */
40491 static u32 pager_datahash(int nByte, unsigned char *pData){
40492   u32 hash = 0;
40493   int i;
40494   for(i=0; i<nByte; i++){
40495     hash = (hash*1039) + pData[i];
40496   }
40497   return hash;
40498 }
40499 static u32 pager_pagehash(PgHdr *pPage){
40500   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
40501 }
40502 static void pager_set_pagehash(PgHdr *pPage){
40503   pPage->pageHash = pager_pagehash(pPage);
40504 }
40505
40506 /*
40507 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLCIPHER_CHECK_PAGES
40508 ** is defined, and NDEBUG is not defined, an assert() statement checks
40509 ** that the page is either dirty or still matches the calculated page-hash.
40510 */
40511 #define CHECK_PAGE(x) checkPage(x)
40512 static void checkPage(PgHdr *pPg){
40513   Pager *pPager = pPg->pPager;
40514   assert( pPager->eState!=PAGER_ERROR );
40515   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
40516 }
40517
40518 #else
40519 #define pager_datahash(X,Y)  0
40520 #define pager_pagehash(X)  0
40521 #define pager_set_pagehash(X)
40522 #define CHECK_PAGE(x)
40523 #endif  /* SQLCIPHER_CHECK_PAGES */
40524
40525 /*
40526 ** When this is called the journal file for pager pPager must be open.
40527 ** This function attempts to read a master journal file name from the 
40528 ** end of the file and, if successful, copies it into memory supplied 
40529 ** by the caller. See comments above writeMasterJournal() for the format
40530 ** used to store a master journal file name at the end of a journal file.
40531 **
40532 ** zMaster must point to a buffer of at least nMaster bytes allocated by
40533 ** the caller. This should be sqlcipher3_vfs.mxPathname+1 (to ensure there is
40534 ** enough space to write the master journal name). If the master journal
40535 ** name in the journal is longer than nMaster bytes (including a
40536 ** nul-terminator), then this is handled as if no master journal name
40537 ** were present in the journal.
40538 **
40539 ** If a master journal file name is present at the end of the journal
40540 ** file, then it is copied into the buffer pointed to by zMaster. A
40541 ** nul-terminator byte is appended to the buffer following the master
40542 ** journal file name.
40543 **
40544 ** If it is determined that no master journal file name is present 
40545 ** zMaster[0] is set to 0 and SQLCIPHER_OK returned.
40546 **
40547 ** If an error occurs while reading from the journal file, an SQLite
40548 ** error code is returned.
40549 */
40550 static int readMasterJournal(sqlcipher3_file *pJrnl, char *zMaster, u32 nMaster){
40551   int rc;                    /* Return code */
40552   u32 len;                   /* Length in bytes of master journal name */
40553   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
40554   u32 cksum;                 /* MJ checksum value read from journal */
40555   u32 u;                     /* Unsigned loop counter */
40556   unsigned char aMagic[8];   /* A buffer to hold the magic header */
40557   zMaster[0] = '\0';
40558
40559   if( SQLCIPHER_OK!=(rc = sqlcipher3OsFileSize(pJrnl, &szJ))
40560    || szJ<16
40561    || SQLCIPHER_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
40562    || len>=nMaster 
40563    || SQLCIPHER_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
40564    || SQLCIPHER_OK!=(rc = sqlcipher3OsRead(pJrnl, aMagic, 8, szJ-8))
40565    || memcmp(aMagic, aJournalMagic, 8)
40566    || SQLCIPHER_OK!=(rc = sqlcipher3OsRead(pJrnl, zMaster, len, szJ-16-len))
40567   ){
40568     return rc;
40569   }
40570
40571   /* See if the checksum matches the master journal name */
40572   for(u=0; u<len; u++){
40573     cksum -= zMaster[u];
40574   }
40575   if( cksum ){
40576     /* If the checksum doesn't add up, then one or more of the disk sectors
40577     ** containing the master journal filename is corrupted. This means
40578     ** definitely roll back, so just return SQLCIPHER_OK and report a (nul)
40579     ** master-journal filename.
40580     */
40581     len = 0;
40582   }
40583   zMaster[len] = '\0';
40584    
40585   return SQLCIPHER_OK;
40586 }
40587
40588 /*
40589 ** Return the offset of the sector boundary at or immediately 
40590 ** following the value in pPager->journalOff, assuming a sector 
40591 ** size of pPager->sectorSize bytes.
40592 **
40593 ** i.e for a sector size of 512:
40594 **
40595 **   Pager.journalOff          Return value
40596 **   ---------------------------------------
40597 **   0                         0
40598 **   512                       512
40599 **   100                       512
40600 **   2000                      2048
40601 ** 
40602 */
40603 static i64 journalHdrOffset(Pager *pPager){
40604   i64 offset = 0;
40605   i64 c = pPager->journalOff;
40606   if( c ){
40607     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
40608   }
40609   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
40610   assert( offset>=c );
40611   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
40612   return offset;
40613 }
40614
40615 /*
40616 ** The journal file must be open when this function is called.
40617 **
40618 ** This function is a no-op if the journal file has not been written to
40619 ** within the current transaction (i.e. if Pager.journalOff==0).
40620 **
40621 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
40622 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
40623 ** zero the 28-byte header at the start of the journal file. In either case, 
40624 ** if the pager is not in no-sync mode, sync the journal file immediately 
40625 ** after writing or truncating it.
40626 **
40627 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
40628 ** following the truncation or zeroing described above the size of the 
40629 ** journal file in bytes is larger than this value, then truncate the
40630 ** journal file to Pager.journalSizeLimit bytes. The journal file does
40631 ** not need to be synced following this operation.
40632 **
40633 ** If an IO error occurs, abandon processing and return the IO error code.
40634 ** Otherwise, return SQLCIPHER_OK.
40635 */
40636 static int zeroJournalHdr(Pager *pPager, int doTruncate){
40637   int rc = SQLCIPHER_OK;                               /* Return code */
40638   assert( isOpen(pPager->jfd) );
40639   if( pPager->journalOff ){
40640     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
40641
40642     IOTRACE(("JZEROHDR %p\n", pPager))
40643     if( doTruncate || iLimit==0 ){
40644       rc = sqlcipher3OsTruncate(pPager->jfd, 0);
40645     }else{
40646       static const char zeroHdr[28] = {0};
40647       rc = sqlcipher3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
40648     }
40649     if( rc==SQLCIPHER_OK && !pPager->noSync ){
40650       rc = sqlcipher3OsSync(pPager->jfd, SQLCIPHER_SYNC_DATAONLY|pPager->syncFlags);
40651     }
40652
40653     /* At this point the transaction is committed but the write lock 
40654     ** is still held on the file. If there is a size limit configured for 
40655     ** the persistent journal and the journal file currently consumes more
40656     ** space than that limit allows for, truncate it now. There is no need
40657     ** to sync the file following this operation.
40658     */
40659     if( rc==SQLCIPHER_OK && iLimit>0 ){
40660       i64 sz;
40661       rc = sqlcipher3OsFileSize(pPager->jfd, &sz);
40662       if( rc==SQLCIPHER_OK && sz>iLimit ){
40663         rc = sqlcipher3OsTruncate(pPager->jfd, iLimit);
40664       }
40665     }
40666   }
40667   return rc;
40668 }
40669
40670 /*
40671 ** The journal file must be open when this routine is called. A journal
40672 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
40673 ** current location.
40674 **
40675 ** The format for the journal header is as follows:
40676 ** - 8 bytes: Magic identifying journal format.
40677 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
40678 ** - 4 bytes: Random number used for page hash.
40679 ** - 4 bytes: Initial database page count.
40680 ** - 4 bytes: Sector size used by the process that wrote this journal.
40681 ** - 4 bytes: Database page size.
40682 ** 
40683 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
40684 */
40685 static int writeJournalHdr(Pager *pPager){
40686   int rc = SQLCIPHER_OK;                 /* Return code */
40687   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
40688   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
40689   u32 nWrite;                         /* Bytes of header sector written */
40690   int ii;                             /* Loop counter */
40691
40692   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
40693
40694   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
40695     nHeader = JOURNAL_HDR_SZ(pPager);
40696   }
40697
40698   /* If there are active savepoints and any of them were created 
40699   ** since the most recent journal header was written, update the 
40700   ** PagerSavepoint.iHdrOffset fields now.
40701   */
40702   for(ii=0; ii<pPager->nSavepoint; ii++){
40703     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
40704       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
40705     }
40706   }
40707
40708   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
40709
40710   /* 
40711   ** Write the nRec Field - the number of page records that follow this
40712   ** journal header. Normally, zero is written to this value at this time.
40713   ** After the records are added to the journal (and the journal synced, 
40714   ** if in full-sync mode), the zero is overwritten with the true number
40715   ** of records (see syncJournal()).
40716   **
40717   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
40718   ** reading the journal this value tells SQLite to assume that the
40719   ** rest of the journal file contains valid page records. This assumption
40720   ** is dangerous, as if a failure occurred whilst writing to the journal
40721   ** file it may contain some garbage data. There are two scenarios
40722   ** where this risk can be ignored:
40723   **
40724   **   * When the pager is in no-sync mode. Corruption can follow a
40725   **     power failure in this case anyway.
40726   **
40727   **   * When the SQLCIPHER_IOCAP_SAFE_APPEND flag is set. This guarantees
40728   **     that garbage data is never appended to the journal file.
40729   */
40730   assert( isOpen(pPager->fd) || pPager->noSync );
40731   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
40732    || (sqlcipher3OsDeviceCharacteristics(pPager->fd)&SQLCIPHER_IOCAP_SAFE_APPEND) 
40733   ){
40734     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
40735     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
40736   }else{
40737     memset(zHeader, 0, sizeof(aJournalMagic)+4);
40738   }
40739
40740   /* The random check-hash initialiser */ 
40741   sqlcipher3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
40742   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
40743   /* The initial database size */
40744   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
40745   /* The assumed sector size for this process */
40746   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
40747
40748   /* The page size */
40749   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
40750
40751   /* Initializing the tail of the buffer is not necessary.  Everything
40752   ** works find if the following memset() is omitted.  But initializing
40753   ** the memory prevents valgrind from complaining, so we are willing to
40754   ** take the performance hit.
40755   */
40756   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
40757          nHeader-(sizeof(aJournalMagic)+20));
40758
40759   /* In theory, it is only necessary to write the 28 bytes that the 
40760   ** journal header consumes to the journal file here. Then increment the 
40761   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
40762   ** record is written to the following sector (leaving a gap in the file
40763   ** that will be implicitly filled in by the OS).
40764   **
40765   ** However it has been discovered that on some systems this pattern can 
40766   ** be significantly slower than contiguously writing data to the file,
40767   ** even if that means explicitly writing data to the block of 
40768   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
40769   ** is done. 
40770   **
40771   ** The loop is required here in case the sector-size is larger than the 
40772   ** database page size. Since the zHeader buffer is only Pager.pageSize
40773   ** bytes in size, more than one call to sqlcipher3OsWrite() may be required
40774   ** to populate the entire journal header sector.
40775   */ 
40776   for(nWrite=0; rc==SQLCIPHER_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
40777     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
40778     rc = sqlcipher3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
40779     assert( pPager->journalHdr <= pPager->journalOff );
40780     pPager->journalOff += nHeader;
40781   }
40782
40783   return rc;
40784 }
40785
40786 /*
40787 ** The journal file must be open when this is called. A journal header file
40788 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
40789 ** file. The current location in the journal file is given by
40790 ** pPager->journalOff. See comments above function writeJournalHdr() for
40791 ** a description of the journal header format.
40792 **
40793 ** If the header is read successfully, *pNRec is set to the number of
40794 ** page records following this header and *pDbSize is set to the size of the
40795 ** database before the transaction began, in pages. Also, pPager->cksumInit
40796 ** is set to the value read from the journal header. SQLCIPHER_OK is returned
40797 ** in this case.
40798 **
40799 ** If the journal header file appears to be corrupted, SQLCIPHER_DONE is
40800 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
40801 ** cannot be read from the journal file an error code is returned.
40802 */
40803 static int readJournalHdr(
40804   Pager *pPager,               /* Pager object */
40805   int isHot,
40806   i64 journalSize,             /* Size of the open journal file in bytes */
40807   u32 *pNRec,                  /* OUT: Value read from the nRec field */
40808   u32 *pDbSize                 /* OUT: Value of original database size field */
40809 ){
40810   int rc;                      /* Return code */
40811   unsigned char aMagic[8];     /* A buffer to hold the magic header */
40812   i64 iHdrOff;                 /* Offset of journal header being read */
40813
40814   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
40815
40816   /* Advance Pager.journalOff to the start of the next sector. If the
40817   ** journal file is too small for there to be a header stored at this
40818   ** point, return SQLCIPHER_DONE.
40819   */
40820   pPager->journalOff = journalHdrOffset(pPager);
40821   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
40822     return SQLCIPHER_DONE;
40823   }
40824   iHdrOff = pPager->journalOff;
40825
40826   /* Read in the first 8 bytes of the journal header. If they do not match
40827   ** the  magic string found at the start of each journal header, return
40828   ** SQLCIPHER_DONE. If an IO error occurs, return an error code. Otherwise,
40829   ** proceed.
40830   */
40831   if( isHot || iHdrOff!=pPager->journalHdr ){
40832     rc = sqlcipher3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
40833     if( rc ){
40834       return rc;
40835     }
40836     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
40837       return SQLCIPHER_DONE;
40838     }
40839   }
40840
40841   /* Read the first three 32-bit fields of the journal header: The nRec
40842   ** field, the checksum-initializer and the database size at the start
40843   ** of the transaction. Return an error code if anything goes wrong.
40844   */
40845   if( SQLCIPHER_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
40846    || SQLCIPHER_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
40847    || SQLCIPHER_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
40848   ){
40849     return rc;
40850   }
40851
40852   if( pPager->journalOff==0 ){
40853     u32 iPageSize;               /* Page-size field of journal header */
40854     u32 iSectorSize;             /* Sector-size field of journal header */
40855
40856     /* Read the page-size and sector-size journal header fields. */
40857     if( SQLCIPHER_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
40858      || SQLCIPHER_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
40859     ){
40860       return rc;
40861     }
40862
40863     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
40864     ** journal header to zero. In this case, assume that the Pager.pageSize
40865     ** variable is already set to the correct page size.
40866     */
40867     if( iPageSize==0 ){
40868       iPageSize = pPager->pageSize;
40869     }
40870
40871     /* Check that the values read from the page-size and sector-size fields
40872     ** are within range. To be 'in range', both values need to be a power
40873     ** of two greater than or equal to 512 or 32, and not greater than their 
40874     ** respective compile time maximum limits.
40875     */
40876     if( iPageSize<512                  || iSectorSize<32
40877      || iPageSize>SQLCIPHER_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
40878      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
40879     ){
40880       /* If the either the page-size or sector-size in the journal-header is 
40881       ** invalid, then the process that wrote the journal-header must have 
40882       ** crashed before the header was synced. In this case stop reading 
40883       ** the journal file here.
40884       */
40885       return SQLCIPHER_DONE;
40886     }
40887
40888     /* Update the page-size to match the value read from the journal. 
40889     ** Use a testcase() macro to make sure that malloc failure within 
40890     ** PagerSetPagesize() is tested.
40891     */
40892     rc = sqlcipher3PagerSetPagesize(pPager, &iPageSize, -1);
40893     testcase( rc!=SQLCIPHER_OK );
40894
40895     /* Update the assumed sector-size to match the value used by 
40896     ** the process that created this journal. If this journal was
40897     ** created by a process other than this one, then this routine
40898     ** is being called from within pager_playback(). The local value
40899     ** of Pager.sectorSize is restored at the end of that routine.
40900     */
40901     pPager->sectorSize = iSectorSize;
40902   }
40903
40904   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
40905   return rc;
40906 }
40907
40908
40909 /*
40910 ** Write the supplied master journal name into the journal file for pager
40911 ** pPager at the current location. The master journal name must be the last
40912 ** thing written to a journal file. If the pager is in full-sync mode, the
40913 ** journal file descriptor is advanced to the next sector boundary before
40914 ** anything is written. The format is:
40915 **
40916 **   + 4 bytes: PAGER_MJ_PGNO.
40917 **   + N bytes: Master journal filename in utf-8.
40918 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
40919 **   + 4 bytes: Master journal name checksum.
40920 **   + 8 bytes: aJournalMagic[].
40921 **
40922 ** The master journal page checksum is the sum of the bytes in the master
40923 ** journal name, where each byte is interpreted as a signed 8-bit integer.
40924 **
40925 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
40926 ** this call is a no-op.
40927 */
40928 static int writeMasterJournal(Pager *pPager, const char *zMaster){
40929   int rc;                          /* Return code */
40930   int nMaster;                     /* Length of string zMaster */
40931   i64 iHdrOff;                     /* Offset of header in journal file */
40932   i64 jrnlSize;                    /* Size of journal file on disk */
40933   u32 cksum = 0;                   /* Checksum of string zMaster */
40934
40935   assert( pPager->setMaster==0 );
40936   assert( !pagerUseWal(pPager) );
40937
40938   if( !zMaster 
40939    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
40940    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
40941   ){
40942     return SQLCIPHER_OK;
40943   }
40944   pPager->setMaster = 1;
40945   assert( isOpen(pPager->jfd) );
40946   assert( pPager->journalHdr <= pPager->journalOff );
40947
40948   /* Calculate the length in bytes and the checksum of zMaster */
40949   for(nMaster=0; zMaster[nMaster]; nMaster++){
40950     cksum += zMaster[nMaster];
40951   }
40952
40953   /* If in full-sync mode, advance to the next disk sector before writing
40954   ** the master journal name. This is in case the previous page written to
40955   ** the journal has already been synced.
40956   */
40957   if( pPager->fullSync ){
40958     pPager->journalOff = journalHdrOffset(pPager);
40959   }
40960   iHdrOff = pPager->journalOff;
40961
40962   /* Write the master journal data to the end of the journal file. If
40963   ** an error occurs, return the error code to the caller.
40964   */
40965   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
40966    || (0 != (rc = sqlcipher3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
40967    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
40968    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
40969    || (0 != (rc = sqlcipher3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
40970   ){
40971     return rc;
40972   }
40973   pPager->journalOff += (nMaster+20);
40974
40975   /* If the pager is in peristent-journal mode, then the physical 
40976   ** journal-file may extend past the end of the master-journal name
40977   ** and 8 bytes of magic data just written to the file. This is 
40978   ** dangerous because the code to rollback a hot-journal file
40979   ** will not be able to find the master-journal name to determine 
40980   ** whether or not the journal is hot. 
40981   **
40982   ** Easiest thing to do in this scenario is to truncate the journal 
40983   ** file to the required size.
40984   */ 
40985   if( SQLCIPHER_OK==(rc = sqlcipher3OsFileSize(pPager->jfd, &jrnlSize))
40986    && jrnlSize>pPager->journalOff
40987   ){
40988     rc = sqlcipher3OsTruncate(pPager->jfd, pPager->journalOff);
40989   }
40990   return rc;
40991 }
40992
40993 /*
40994 ** Find a page in the hash table given its page number. Return
40995 ** a pointer to the page or NULL if the requested page is not 
40996 ** already in memory.
40997 */
40998 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
40999   PgHdr *p;                         /* Return value */
41000
41001   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
41002   ** fail, since no attempt to allocate dynamic memory will be made.
41003   */
41004   (void)sqlcipher3PcacheFetch(pPager->pPCache, pgno, 0, &p);
41005   return p;
41006 }
41007
41008 /*
41009 ** Discard the entire contents of the in-memory page-cache.
41010 */
41011 static void pager_reset(Pager *pPager){
41012   sqlcipher3BackupRestart(pPager->pBackup);
41013   sqlcipher3PcacheClear(pPager->pPCache);
41014 }
41015
41016 /*
41017 ** Free all structures in the Pager.aSavepoint[] array and set both
41018 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
41019 ** if it is open and the pager is not in exclusive mode.
41020 */
41021 static void releaseAllSavepoints(Pager *pPager){
41022   int ii;               /* Iterator for looping through Pager.aSavepoint */
41023   for(ii=0; ii<pPager->nSavepoint; ii++){
41024     sqlcipher3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
41025   }
41026   if( !pPager->exclusiveMode || sqlcipher3IsMemJournal(pPager->sjfd) ){
41027     sqlcipher3OsClose(pPager->sjfd);
41028   }
41029   sqlcipher3_free(pPager->aSavepoint);
41030   pPager->aSavepoint = 0;
41031   pPager->nSavepoint = 0;
41032   pPager->nSubRec = 0;
41033 }
41034
41035 /*
41036 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
41037 ** bitvecs of all open savepoints. Return SQLCIPHER_OK if successful
41038 ** or SQLCIPHER_NOMEM if a malloc failure occurs.
41039 */
41040 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
41041   int ii;                   /* Loop counter */
41042   int rc = SQLCIPHER_OK;       /* Result code */
41043
41044   for(ii=0; ii<pPager->nSavepoint; ii++){
41045     PagerSavepoint *p = &pPager->aSavepoint[ii];
41046     if( pgno<=p->nOrig ){
41047       rc |= sqlcipher3BitvecSet(p->pInSavepoint, pgno);
41048       testcase( rc==SQLCIPHER_NOMEM );
41049       assert( rc==SQLCIPHER_OK || rc==SQLCIPHER_NOMEM );
41050     }
41051   }
41052   return rc;
41053 }
41054
41055 /*
41056 ** This function is a no-op if the pager is in exclusive mode and not
41057 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
41058 ** state.
41059 **
41060 ** If the pager is not in exclusive-access mode, the database file is
41061 ** completely unlocked. If the file is unlocked and the file-system does
41062 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
41063 ** closed (if it is open).
41064 **
41065 ** If the pager is in ERROR state when this function is called, the 
41066 ** contents of the pager cache are discarded before switching back to 
41067 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
41068 ** or not, any journal file left in the file-system will be treated
41069 ** as a hot-journal and rolled back the next time a read-transaction
41070 ** is opened (by this or by any other connection).
41071 */
41072 static void pager_unlock(Pager *pPager){
41073
41074   assert( pPager->eState==PAGER_READER 
41075        || pPager->eState==PAGER_OPEN 
41076        || pPager->eState==PAGER_ERROR 
41077   );
41078
41079   sqlcipher3BitvecDestroy(pPager->pInJournal);
41080   pPager->pInJournal = 0;
41081   releaseAllSavepoints(pPager);
41082
41083   if( pagerUseWal(pPager) ){
41084     assert( !isOpen(pPager->jfd) );
41085     sqlcipher3WalEndReadTransaction(pPager->pWal);
41086     pPager->eState = PAGER_OPEN;
41087   }else if( !pPager->exclusiveMode ){
41088     int rc;                       /* Error code returned by pagerUnlockDb() */
41089     int iDc = isOpen(pPager->fd)?sqlcipher3OsDeviceCharacteristics(pPager->fd):0;
41090
41091     /* If the operating system support deletion of open files, then
41092     ** close the journal file when dropping the database lock.  Otherwise
41093     ** another connection with journal_mode=delete might delete the file
41094     ** out from under us.
41095     */
41096     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
41097     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
41098     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
41099     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
41100     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
41101     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
41102     if( 0==(iDc & SQLCIPHER_IOCAP_UNDELETABLE_WHEN_OPEN)
41103      || 1!=(pPager->journalMode & 5)
41104     ){
41105       sqlcipher3OsClose(pPager->jfd);
41106     }
41107
41108     /* If the pager is in the ERROR state and the call to unlock the database
41109     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
41110     ** above the #define for UNKNOWN_LOCK for an explanation of why this
41111     ** is necessary.
41112     */
41113     rc = pagerUnlockDb(pPager, NO_LOCK);
41114     if( rc!=SQLCIPHER_OK && pPager->eState==PAGER_ERROR ){
41115       pPager->eLock = UNKNOWN_LOCK;
41116     }
41117
41118     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
41119     ** without clearing the error code. This is intentional - the error
41120     ** code is cleared and the cache reset in the block below.
41121     */
41122     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
41123     pPager->changeCountDone = 0;
41124     pPager->eState = PAGER_OPEN;
41125   }
41126
41127   /* If Pager.errCode is set, the contents of the pager cache cannot be
41128   ** trusted. Now that there are no outstanding references to the pager,
41129   ** it can safely move back to PAGER_OPEN state. This happens in both
41130   ** normal and exclusive-locking mode.
41131   */
41132   if( pPager->errCode ){
41133     assert( !MEMDB );
41134     pager_reset(pPager);
41135     pPager->changeCountDone = pPager->tempFile;
41136     pPager->eState = PAGER_OPEN;
41137     pPager->errCode = SQLCIPHER_OK;
41138   }
41139
41140   pPager->journalOff = 0;
41141   pPager->journalHdr = 0;
41142   pPager->setMaster = 0;
41143 }
41144
41145 /*
41146 ** This function is called whenever an IOERR or FULL error that requires
41147 ** the pager to transition into the ERROR state may ahve occurred.
41148 ** The first argument is a pointer to the pager structure, the second 
41149 ** the error-code about to be returned by a pager API function. The 
41150 ** value returned is a copy of the second argument to this function. 
41151 **
41152 ** If the second argument is SQLCIPHER_FULL, SQLCIPHER_IOERR or one of the
41153 ** IOERR sub-codes, the pager enters the ERROR state and the error code
41154 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
41155 ** all major API calls on the Pager will immediately return Pager.errCode.
41156 **
41157 ** The ERROR state indicates that the contents of the pager-cache 
41158 ** cannot be trusted. This state can be cleared by completely discarding 
41159 ** the contents of the pager-cache. If a transaction was active when
41160 ** the persistent error occurred, then the rollback journal may need
41161 ** to be replayed to restore the contents of the database file (as if
41162 ** it were a hot-journal).
41163 */
41164 static int pager_error(Pager *pPager, int rc){
41165   int rc2 = rc & 0xff;
41166   assert( rc==SQLCIPHER_OK || !MEMDB );
41167   assert(
41168        pPager->errCode==SQLCIPHER_FULL ||
41169        pPager->errCode==SQLCIPHER_OK ||
41170        (pPager->errCode & 0xff)==SQLCIPHER_IOERR
41171   );
41172   if( rc2==SQLCIPHER_FULL || rc2==SQLCIPHER_IOERR ){
41173     pPager->errCode = rc;
41174     pPager->eState = PAGER_ERROR;
41175   }
41176   return rc;
41177 }
41178
41179 /*
41180 ** This routine ends a transaction. A transaction is usually ended by 
41181 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
41182 ** after rollback of a hot-journal, or if an error occurs while opening
41183 ** the journal file or writing the very first journal-header of a
41184 ** database transaction.
41185 ** 
41186 ** This routine is never called in PAGER_ERROR state. If it is called
41187 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
41188 ** exclusive than a RESERVED lock, it is a no-op.
41189 **
41190 ** Otherwise, any active savepoints are released.
41191 **
41192 ** If the journal file is open, then it is "finalized". Once a journal 
41193 ** file has been finalized it is not possible to use it to roll back a 
41194 ** transaction. Nor will it be considered to be a hot-journal by this
41195 ** or any other database connection. Exactly how a journal is finalized
41196 ** depends on whether or not the pager is running in exclusive mode and
41197 ** the current journal-mode (Pager.journalMode value), as follows:
41198 **
41199 **   journalMode==MEMORY
41200 **     Journal file descriptor is simply closed. This destroys an 
41201 **     in-memory journal.
41202 **
41203 **   journalMode==TRUNCATE
41204 **     Journal file is truncated to zero bytes in size.
41205 **
41206 **   journalMode==PERSIST
41207 **     The first 28 bytes of the journal file are zeroed. This invalidates
41208 **     the first journal header in the file, and hence the entire journal
41209 **     file. An invalid journal file cannot be rolled back.
41210 **
41211 **   journalMode==DELETE
41212 **     The journal file is closed and deleted using sqlcipher3OsDelete().
41213 **
41214 **     If the pager is running in exclusive mode, this method of finalizing
41215 **     the journal file is never used. Instead, if the journalMode is
41216 **     DELETE and the pager is in exclusive mode, the method described under
41217 **     journalMode==PERSIST is used instead.
41218 **
41219 ** After the journal is finalized, the pager moves to PAGER_READER state.
41220 ** If running in non-exclusive rollback mode, the lock on the file is 
41221 ** downgraded to a SHARED_LOCK.
41222 **
41223 ** SQLCIPHER_OK is returned if no error occurs. If an error occurs during
41224 ** any of the IO operations to finalize the journal file or unlock the
41225 ** database then the IO error code is returned to the user. If the 
41226 ** operation to finalize the journal file fails, then the code still
41227 ** tries to unlock the database file if not in exclusive mode. If the
41228 ** unlock operation fails as well, then the first error code related
41229 ** to the first error encountered (the journal finalization one) is
41230 ** returned.
41231 */
41232 static int pager_end_transaction(Pager *pPager, int hasMaster){
41233   int rc = SQLCIPHER_OK;      /* Error code from journal finalization operation */
41234   int rc2 = SQLCIPHER_OK;     /* Error code from db file unlock operation */
41235
41236   /* Do nothing if the pager does not have an open write transaction
41237   ** or at least a RESERVED lock. This function may be called when there
41238   ** is no write-transaction active but a RESERVED or greater lock is
41239   ** held under two circumstances:
41240   **
41241   **   1. After a successful hot-journal rollback, it is called with
41242   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
41243   **
41244   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
41245   **      lock switches back to locking_mode=normal and then executes a
41246   **      read-transaction, this function is called with eState==PAGER_READER 
41247   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
41248   */
41249   assert( assert_pager_state(pPager) );
41250   assert( pPager->eState!=PAGER_ERROR );
41251   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
41252     return SQLCIPHER_OK;
41253   }
41254
41255   releaseAllSavepoints(pPager);
41256   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
41257   if( isOpen(pPager->jfd) ){
41258     assert( !pagerUseWal(pPager) );
41259
41260     /* Finalize the journal file. */
41261     if( sqlcipher3IsMemJournal(pPager->jfd) ){
41262       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
41263       sqlcipher3OsClose(pPager->jfd);
41264     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
41265       if( pPager->journalOff==0 ){
41266         rc = SQLCIPHER_OK;
41267       }else{
41268         rc = sqlcipher3OsTruncate(pPager->jfd, 0);
41269       }
41270       pPager->journalOff = 0;
41271     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
41272       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
41273     ){
41274       rc = zeroJournalHdr(pPager, hasMaster);
41275       pPager->journalOff = 0;
41276     }else{
41277       /* This branch may be executed with Pager.journalMode==MEMORY if
41278       ** a hot-journal was just rolled back. In this case the journal
41279       ** file should be closed and deleted. If this connection writes to
41280       ** the database file, it will do so using an in-memory journal. 
41281       */
41282       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
41283            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
41284            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
41285       );
41286       sqlcipher3OsClose(pPager->jfd);
41287       if( !pPager->tempFile ){
41288         rc = sqlcipher3OsDelete(pPager->pVfs, pPager->zJournal, 0);
41289       }
41290     }
41291   }
41292
41293 #ifdef SQLCIPHER_CHECK_PAGES
41294   sqlcipher3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
41295   if( pPager->dbSize==0 && sqlcipher3PcacheRefCount(pPager->pPCache)>0 ){
41296     PgHdr *p = pager_lookup(pPager, 1);
41297     if( p ){
41298       p->pageHash = 0;
41299       sqlcipher3PagerUnref(p);
41300     }
41301   }
41302 #endif
41303
41304   sqlcipher3BitvecDestroy(pPager->pInJournal);
41305   pPager->pInJournal = 0;
41306   pPager->nRec = 0;
41307   sqlcipher3PcacheCleanAll(pPager->pPCache);
41308   sqlcipher3PcacheTruncate(pPager->pPCache, pPager->dbSize);
41309
41310   if( pagerUseWal(pPager) ){
41311     /* Drop the WAL write-lock, if any. Also, if the connection was in 
41312     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
41313     ** lock held on the database file.
41314     */
41315     rc2 = sqlcipher3WalEndWriteTransaction(pPager->pWal);
41316     assert( rc2==SQLCIPHER_OK );
41317   }
41318   if( !pPager->exclusiveMode 
41319    && (!pagerUseWal(pPager) || sqlcipher3WalExclusiveMode(pPager->pWal, 0))
41320   ){
41321     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
41322     pPager->changeCountDone = 0;
41323   }
41324   pPager->eState = PAGER_READER;
41325   pPager->setMaster = 0;
41326
41327   return (rc==SQLCIPHER_OK?rc2:rc);
41328 }
41329
41330 /*
41331 ** Execute a rollback if a transaction is active and unlock the 
41332 ** database file. 
41333 **
41334 ** If the pager has already entered the ERROR state, do not attempt 
41335 ** the rollback at this time. Instead, pager_unlock() is called. The
41336 ** call to pager_unlock() will discard all in-memory pages, unlock
41337 ** the database file and move the pager back to OPEN state. If this 
41338 ** means that there is a hot-journal left in the file-system, the next 
41339 ** connection to obtain a shared lock on the pager (which may be this one) 
41340 ** will roll it back.
41341 **
41342 ** If the pager has not already entered the ERROR state, but an IO or
41343 ** malloc error occurs during a rollback, then this will itself cause 
41344 ** the pager to enter the ERROR state. Which will be cleared by the
41345 ** call to pager_unlock(), as described above.
41346 */
41347 static void pagerUnlockAndRollback(Pager *pPager){
41348   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
41349     assert( assert_pager_state(pPager) );
41350     if( pPager->eState>=PAGER_WRITER_LOCKED ){
41351       sqlcipher3BeginBenignMalloc();
41352       sqlcipher3PagerRollback(pPager);
41353       sqlcipher3EndBenignMalloc();
41354     }else if( !pPager->exclusiveMode ){
41355       assert( pPager->eState==PAGER_READER );
41356       pager_end_transaction(pPager, 0);
41357     }
41358   }
41359   pager_unlock(pPager);
41360 }
41361
41362 /*
41363 ** Parameter aData must point to a buffer of pPager->pageSize bytes
41364 ** of data. Compute and return a checksum based ont the contents of the 
41365 ** page of data and the current value of pPager->cksumInit.
41366 **
41367 ** This is not a real checksum. It is really just the sum of the 
41368 ** random initial value (pPager->cksumInit) and every 200th byte
41369 ** of the page data, starting with byte offset (pPager->pageSize%200).
41370 ** Each byte is interpreted as an 8-bit unsigned integer.
41371 **
41372 ** Changing the formula used to compute this checksum results in an
41373 ** incompatible journal file format.
41374 **
41375 ** If journal corruption occurs due to a power failure, the most likely 
41376 ** scenario is that one end or the other of the record will be changed. 
41377 ** It is much less likely that the two ends of the journal record will be
41378 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
41379 ** though fast and simple, catches the mostly likely kind of corruption.
41380 */
41381 static u32 pager_cksum(Pager *pPager, const u8 *aData){
41382   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
41383   int i = pPager->pageSize-200;          /* Loop counter */
41384   while( i>0 ){
41385     cksum += aData[i];
41386     i -= 200;
41387   }
41388   return cksum;
41389 }
41390
41391 /*
41392 ** Report the current page size and number of reserved bytes back
41393 ** to the codec.
41394 */
41395 #ifdef SQLCIPHER_HAS_CODEC
41396 static void pagerReportSize(Pager *pPager){
41397   if( pPager->xCodecSizeChng ){
41398     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
41399                            (int)pPager->nReserve);
41400   }
41401 }
41402 #else
41403 # define pagerReportSize(X)     /* No-op if we do not support a codec */
41404 #endif
41405
41406 /*
41407 ** Read a single page from either the journal file (if isMainJrnl==1) or
41408 ** from the sub-journal (if isMainJrnl==0) and playback that page.
41409 ** The page begins at offset *pOffset into the file. The *pOffset
41410 ** value is increased to the start of the next page in the journal.
41411 **
41412 ** The main rollback journal uses checksums - the statement journal does 
41413 ** not.
41414 **
41415 ** If the page number of the page record read from the (sub-)journal file
41416 ** is greater than the current value of Pager.dbSize, then playback is
41417 ** skipped and SQLCIPHER_OK is returned.
41418 **
41419 ** If pDone is not NULL, then it is a record of pages that have already
41420 ** been played back.  If the page at *pOffset has already been played back
41421 ** (if the corresponding pDone bit is set) then skip the playback.
41422 ** Make sure the pDone bit corresponding to the *pOffset page is set
41423 ** prior to returning.
41424 **
41425 ** If the page record is successfully read from the (sub-)journal file
41426 ** and played back, then SQLCIPHER_OK is returned. If an IO error occurs
41427 ** while reading the record from the (sub-)journal file or while writing
41428 ** to the database file, then the IO error code is returned. If data
41429 ** is successfully read from the (sub-)journal file but appears to be
41430 ** corrupted, SQLCIPHER_DONE is returned. Data is considered corrupted in
41431 ** two circumstances:
41432 ** 
41433 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
41434 **   * If the record is being rolled back from the main journal file
41435 **     and the checksum field does not match the record content.
41436 **
41437 ** Neither of these two scenarios are possible during a savepoint rollback.
41438 **
41439 ** If this is a savepoint rollback, then memory may have to be dynamically
41440 ** allocated by this function. If this is the case and an allocation fails,
41441 ** SQLCIPHER_NOMEM is returned.
41442 */
41443 static int pager_playback_one_page(
41444   Pager *pPager,                /* The pager being played back */
41445   i64 *pOffset,                 /* Offset of record to playback */
41446   Bitvec *pDone,                /* Bitvec of pages already played back */
41447   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
41448   int isSavepnt                 /* True for a savepoint rollback */
41449 ){
41450   int rc;
41451   PgHdr *pPg;                   /* An existing page in the cache */
41452   Pgno pgno;                    /* The page number of a page in journal */
41453   u32 cksum;                    /* Checksum used for sanity checking */
41454   char *aData;                  /* Temporary storage for the page */
41455   sqlcipher3_file *jfd;            /* The file descriptor for the journal file */
41456   int isSynced;                 /* True if journal page is synced */
41457
41458   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
41459   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
41460   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
41461   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
41462
41463   aData = pPager->pTmpSpace;
41464   assert( aData );         /* Temp storage must have already been allocated */
41465   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
41466
41467   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
41468   ** or savepoint rollback done at the request of the caller) or this is
41469   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
41470   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
41471   ** only reads from the main journal, not the sub-journal.
41472   */
41473   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
41474        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
41475   );
41476   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
41477
41478   /* Read the page number and page data from the journal or sub-journal
41479   ** file. Return an error code to the caller if an IO error occurs.
41480   */
41481   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
41482   rc = read32bits(jfd, *pOffset, &pgno);
41483   if( rc!=SQLCIPHER_OK ) return rc;
41484   rc = sqlcipher3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
41485   if( rc!=SQLCIPHER_OK ) return rc;
41486   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
41487
41488   /* Sanity checking on the page.  This is more important that I originally
41489   ** thought.  If a power failure occurs while the journal is being written,
41490   ** it could cause invalid data to be written into the journal.  We need to
41491   ** detect this invalid data (with high probability) and ignore it.
41492   */
41493   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
41494     assert( !isSavepnt );
41495     return SQLCIPHER_DONE;
41496   }
41497   if( pgno>(Pgno)pPager->dbSize || sqlcipher3BitvecTest(pDone, pgno) ){
41498     return SQLCIPHER_OK;
41499   }
41500   if( isMainJrnl ){
41501     rc = read32bits(jfd, (*pOffset)-4, &cksum);
41502     if( rc ) return rc;
41503     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
41504       return SQLCIPHER_DONE;
41505     }
41506   }
41507
41508   /* If this page has already been played by before during the current
41509   ** rollback, then don't bother to play it back again.
41510   */
41511   if( pDone && (rc = sqlcipher3BitvecSet(pDone, pgno))!=SQLCIPHER_OK ){
41512     return rc;
41513   }
41514
41515   /* When playing back page 1, restore the nReserve setting
41516   */
41517   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
41518     pPager->nReserve = ((u8*)aData)[20];
41519     pagerReportSize(pPager);
41520   }
41521
41522   /* If the pager is in CACHEMOD state, then there must be a copy of this
41523   ** page in the pager cache. In this case just update the pager cache,
41524   ** not the database file. The page is left marked dirty in this case.
41525   **
41526   ** An exception to the above rule: If the database is in no-sync mode
41527   ** and a page is moved during an incremental vacuum then the page may
41528   ** not be in the pager cache. Later: if a malloc() or IO error occurs
41529   ** during a Movepage() call, then the page may not be in the cache
41530   ** either. So the condition described in the above paragraph is not
41531   ** assert()able.
41532   **
41533   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
41534   ** pager cache if it exists and the main file. The page is then marked 
41535   ** not dirty. Since this code is only executed in PAGER_OPEN state for
41536   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
41537   ** if the pager is in OPEN state.
41538   **
41539   ** Ticket #1171:  The statement journal might contain page content that is
41540   ** different from the page content at the start of the transaction.
41541   ** This occurs when a page is changed prior to the start of a statement
41542   ** then changed again within the statement.  When rolling back such a
41543   ** statement we must not write to the original database unless we know
41544   ** for certain that original page contents are synced into the main rollback
41545   ** journal.  Otherwise, a power loss might leave modified data in the
41546   ** database file without an entry in the rollback journal that can
41547   ** restore the database to its original form.  Two conditions must be
41548   ** met before writing to the database files. (1) the database must be
41549   ** locked.  (2) we know that the original page content is fully synced
41550   ** in the main journal either because the page is not in cache or else
41551   ** the page is marked as needSync==0.
41552   **
41553   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
41554   ** is possible to fail a statement on a database that does not yet exist.
41555   ** Do not attempt to write if database file has never been opened.
41556   */
41557   if( pagerUseWal(pPager) ){
41558     pPg = 0;
41559   }else{
41560     pPg = pager_lookup(pPager, pgno);
41561   }
41562   assert( pPg || !MEMDB );
41563   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
41564   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
41565            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
41566            (isMainJrnl?"main-journal":"sub-journal")
41567   ));
41568   if( isMainJrnl ){
41569     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
41570   }else{
41571     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
41572   }
41573   if( isOpen(pPager->fd)
41574    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
41575    && isSynced
41576   ){
41577     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
41578     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
41579     assert( !pagerUseWal(pPager) );
41580     rc = sqlcipher3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
41581     if( pgno>pPager->dbFileSize ){
41582       pPager->dbFileSize = pgno;
41583     }
41584     if( pPager->pBackup ){
41585       CODEC1(pPager, aData, pgno, 3, rc=SQLCIPHER_NOMEM);
41586       sqlcipher3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
41587       CODEC2(pPager, aData, pgno, 7, rc=SQLCIPHER_NOMEM, aData);
41588     }
41589   }else if( !isMainJrnl && pPg==0 ){
41590     /* If this is a rollback of a savepoint and data was not written to
41591     ** the database and the page is not in-memory, there is a potential
41592     ** problem. When the page is next fetched by the b-tree layer, it 
41593     ** will be read from the database file, which may or may not be 
41594     ** current. 
41595     **
41596     ** There are a couple of different ways this can happen. All are quite
41597     ** obscure. When running in synchronous mode, this can only happen 
41598     ** if the page is on the free-list at the start of the transaction, then
41599     ** populated, then moved using sqlcipher3PagerMovepage().
41600     **
41601     ** The solution is to add an in-memory page to the cache containing
41602     ** the data just read from the sub-journal. Mark the page as dirty 
41603     ** and if the pager requires a journal-sync, then mark the page as 
41604     ** requiring a journal-sync before it is written.
41605     */
41606     assert( isSavepnt );
41607     assert( pPager->doNotSpill==0 );
41608     pPager->doNotSpill++;
41609     rc = sqlcipher3PagerAcquire(pPager, pgno, &pPg, 1);
41610     assert( pPager->doNotSpill==1 );
41611     pPager->doNotSpill--;
41612     if( rc!=SQLCIPHER_OK ) return rc;
41613     pPg->flags &= ~PGHDR_NEED_READ;
41614     sqlcipher3PcacheMakeDirty(pPg);
41615   }
41616   if( pPg ){
41617     /* No page should ever be explicitly rolled back that is in use, except
41618     ** for page 1 which is held in use in order to keep the lock on the
41619     ** database active. However such a page may be rolled back as a result
41620     ** of an internal error resulting in an automatic call to
41621     ** sqlcipher3PagerRollback().
41622     */
41623     void *pData;
41624     pData = pPg->pData;
41625     memcpy(pData, (u8*)aData, pPager->pageSize);
41626     pPager->xReiniter(pPg);
41627     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
41628       /* If the contents of this page were just restored from the main 
41629       ** journal file, then its content must be as they were when the 
41630       ** transaction was first opened. In this case we can mark the page
41631       ** as clean, since there will be no need to write it out to the
41632       ** database.
41633       **
41634       ** There is one exception to this rule. If the page is being rolled
41635       ** back as part of a savepoint (or statement) rollback from an 
41636       ** unsynced portion of the main journal file, then it is not safe
41637       ** to mark the page as clean. This is because marking the page as
41638       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
41639       ** already in the journal file (recorded in Pager.pInJournal) and
41640       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
41641       ** again within this transaction, it will be marked as dirty but
41642       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
41643       ** be written out into the database file before its journal file
41644       ** segment is synced. If a crash occurs during or following this,
41645       ** database corruption may ensue.
41646       */
41647       assert( !pagerUseWal(pPager) );
41648       sqlcipher3PcacheMakeClean(pPg);
41649     }
41650     pager_set_pagehash(pPg);
41651
41652     /* If this was page 1, then restore the value of Pager.dbFileVers.
41653     ** Do this before any decoding. */
41654     if( pgno==1 ){
41655       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
41656     }
41657
41658     /* Decode the page just read from disk */
41659     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLCIPHER_NOMEM);
41660     sqlcipher3PcacheRelease(pPg);
41661   }
41662   return rc;
41663 }
41664
41665 /*
41666 ** Parameter zMaster is the name of a master journal file. A single journal
41667 ** file that referred to the master journal file has just been rolled back.
41668 ** This routine checks if it is possible to delete the master journal file,
41669 ** and does so if it is.
41670 **
41671 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
41672 ** available for use within this function.
41673 **
41674 ** When a master journal file is created, it is populated with the names 
41675 ** of all of its child journals, one after another, formatted as utf-8 
41676 ** encoded text. The end of each child journal file is marked with a 
41677 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
41678 ** file for a transaction involving two databases might be:
41679 **
41680 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
41681 **
41682 ** A master journal file may only be deleted once all of its child 
41683 ** journals have been rolled back.
41684 **
41685 ** This function reads the contents of the master-journal file into 
41686 ** memory and loops through each of the child journal names. For
41687 ** each child journal, it checks if:
41688 **
41689 **   * if the child journal exists, and if so
41690 **   * if the child journal contains a reference to master journal 
41691 **     file zMaster
41692 **
41693 ** If a child journal can be found that matches both of the criteria
41694 ** above, this function returns without doing anything. Otherwise, if
41695 ** no such child journal can be found, file zMaster is deleted from
41696 ** the file-system using sqlcipher3OsDelete().
41697 **
41698 ** If an IO error within this function, an error code is returned. This
41699 ** function allocates memory by calling sqlcipher3Malloc(). If an allocation
41700 ** fails, SQLCIPHER_NOMEM is returned. Otherwise, if no IO or malloc errors 
41701 ** occur, SQLCIPHER_OK is returned.
41702 **
41703 ** TODO: This function allocates a single block of memory to load
41704 ** the entire contents of the master journal file. This could be
41705 ** a couple of kilobytes or so - potentially larger than the page 
41706 ** size.
41707 */
41708 static int pager_delmaster(Pager *pPager, const char *zMaster){
41709   sqlcipher3_vfs *pVfs = pPager->pVfs;
41710   int rc;                   /* Return code */
41711   sqlcipher3_file *pMaster;    /* Malloc'd master-journal file descriptor */
41712   sqlcipher3_file *pJournal;   /* Malloc'd child-journal file descriptor */
41713   char *zMasterJournal = 0; /* Contents of master journal file */
41714   i64 nMasterJournal;       /* Size of master journal file */
41715   char *zJournal;           /* Pointer to one journal within MJ file */
41716   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
41717   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
41718
41719   /* Allocate space for both the pJournal and pMaster file descriptors.
41720   ** If successful, open the master journal file for reading.
41721   */
41722   pMaster = (sqlcipher3_file *)sqlcipher3MallocZero(pVfs->szOsFile * 2);
41723   pJournal = (sqlcipher3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
41724   if( !pMaster ){
41725     rc = SQLCIPHER_NOMEM;
41726   }else{
41727     const int flags = (SQLCIPHER_OPEN_READONLY|SQLCIPHER_OPEN_MASTER_JOURNAL);
41728     rc = sqlcipher3OsOpen(pVfs, zMaster, pMaster, flags, 0);
41729   }
41730   if( rc!=SQLCIPHER_OK ) goto delmaster_out;
41731
41732   /* Load the entire master journal file into space obtained from
41733   ** sqlcipher3_malloc() and pointed to by zMasterJournal.   Also obtain
41734   ** sufficient space (in zMasterPtr) to hold the names of master
41735   ** journal files extracted from regular rollback-journals.
41736   */
41737   rc = sqlcipher3OsFileSize(pMaster, &nMasterJournal);
41738   if( rc!=SQLCIPHER_OK ) goto delmaster_out;
41739   nMasterPtr = pVfs->mxPathname+1;
41740   zMasterJournal = sqlcipher3Malloc((int)nMasterJournal + nMasterPtr + 1);
41741   if( !zMasterJournal ){
41742     rc = SQLCIPHER_NOMEM;
41743     goto delmaster_out;
41744   }
41745   zMasterPtr = &zMasterJournal[nMasterJournal+1];
41746   rc = sqlcipher3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
41747   if( rc!=SQLCIPHER_OK ) goto delmaster_out;
41748   zMasterJournal[nMasterJournal] = 0;
41749
41750   zJournal = zMasterJournal;
41751   while( (zJournal-zMasterJournal)<nMasterJournal ){
41752     int exists;
41753     rc = sqlcipher3OsAccess(pVfs, zJournal, SQLCIPHER_ACCESS_EXISTS, &exists);
41754     if( rc!=SQLCIPHER_OK ){
41755       goto delmaster_out;
41756     }
41757     if( exists ){
41758       /* One of the journals pointed to by the master journal exists.
41759       ** Open it and check if it points at the master journal. If
41760       ** so, return without deleting the master journal file.
41761       */
41762       int c;
41763       int flags = (SQLCIPHER_OPEN_READONLY|SQLCIPHER_OPEN_MAIN_JOURNAL);
41764       rc = sqlcipher3OsOpen(pVfs, zJournal, pJournal, flags, 0);
41765       if( rc!=SQLCIPHER_OK ){
41766         goto delmaster_out;
41767       }
41768
41769       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
41770       sqlcipher3OsClose(pJournal);
41771       if( rc!=SQLCIPHER_OK ){
41772         goto delmaster_out;
41773       }
41774
41775       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
41776       if( c ){
41777         /* We have a match. Do not delete the master journal file. */
41778         goto delmaster_out;
41779       }
41780     }
41781     zJournal += (sqlcipher3Strlen30(zJournal)+1);
41782   }
41783  
41784   sqlcipher3OsClose(pMaster);
41785   rc = sqlcipher3OsDelete(pVfs, zMaster, 0);
41786
41787 delmaster_out:
41788   sqlcipher3_free(zMasterJournal);
41789   if( pMaster ){
41790     sqlcipher3OsClose(pMaster);
41791     assert( !isOpen(pJournal) );
41792     sqlcipher3_free(pMaster);
41793   }
41794   return rc;
41795 }
41796
41797
41798 /*
41799 ** This function is used to change the actual size of the database 
41800 ** file in the file-system. This only happens when committing a transaction,
41801 ** or rolling back a transaction (including rolling back a hot-journal).
41802 **
41803 ** If the main database file is not open, or the pager is not in either
41804 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
41805 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
41806 ** If the file on disk is currently larger than nPage pages, then use the VFS
41807 ** xTruncate() method to truncate it.
41808 **
41809 ** Or, it might might be the case that the file on disk is smaller than 
41810 ** nPage pages. Some operating system implementations can get confused if 
41811 ** you try to truncate a file to some size that is larger than it 
41812 ** currently is, so detect this case and write a single zero byte to 
41813 ** the end of the new file instead.
41814 **
41815 ** If successful, return SQLCIPHER_OK. If an IO error occurs while modifying
41816 ** the database file, return the error code to the caller.
41817 */
41818 static int pager_truncate(Pager *pPager, Pgno nPage){
41819   int rc = SQLCIPHER_OK;
41820   assert( pPager->eState!=PAGER_ERROR );
41821   assert( pPager->eState!=PAGER_READER );
41822   
41823   if( isOpen(pPager->fd) 
41824    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
41825   ){
41826     i64 currentSize, newSize;
41827     int szPage = pPager->pageSize;
41828     assert( pPager->eLock==EXCLUSIVE_LOCK );
41829     /* TODO: Is it safe to use Pager.dbFileSize here? */
41830     rc = sqlcipher3OsFileSize(pPager->fd, &currentSize);
41831     newSize = szPage*(i64)nPage;
41832     if( rc==SQLCIPHER_OK && currentSize!=newSize ){
41833       if( currentSize>newSize ){
41834         rc = sqlcipher3OsTruncate(pPager->fd, newSize);
41835       }else{
41836         char *pTmp = pPager->pTmpSpace;
41837         memset(pTmp, 0, szPage);
41838         testcase( (newSize-szPage) <  currentSize );
41839         testcase( (newSize-szPage) == currentSize );
41840         testcase( (newSize-szPage) >  currentSize );
41841         rc = sqlcipher3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
41842       }
41843       if( rc==SQLCIPHER_OK ){
41844         pPager->dbFileSize = nPage;
41845       }
41846     }
41847   }
41848   return rc;
41849 }
41850
41851 /*
41852 ** Set the value of the Pager.sectorSize variable for the given
41853 ** pager based on the value returned by the xSectorSize method
41854 ** of the open database file. The sector size will be used used 
41855 ** to determine the size and alignment of journal header and 
41856 ** master journal pointers within created journal files.
41857 **
41858 ** For temporary files the effective sector size is always 512 bytes.
41859 **
41860 ** Otherwise, for non-temporary files, the effective sector size is
41861 ** the value returned by the xSectorSize() method rounded up to 32 if
41862 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
41863 ** is greater than MAX_SECTOR_SIZE.
41864 */
41865 static void setSectorSize(Pager *pPager){
41866   assert( isOpen(pPager->fd) || pPager->tempFile );
41867
41868   if( !pPager->tempFile ){
41869     /* Sector size doesn't matter for temporary files. Also, the file
41870     ** may not have been opened yet, in which case the OsSectorSize()
41871     ** call will segfault.
41872     */
41873     pPager->sectorSize = sqlcipher3OsSectorSize(pPager->fd);
41874   }
41875   if( pPager->sectorSize<32 ){
41876     pPager->sectorSize = 512;
41877   }
41878   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
41879     assert( MAX_SECTOR_SIZE>=512 );
41880     pPager->sectorSize = MAX_SECTOR_SIZE;
41881   }
41882 }
41883
41884 /*
41885 ** Playback the journal and thus restore the database file to
41886 ** the state it was in before we started making changes.  
41887 **
41888 ** The journal file format is as follows: 
41889 **
41890 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
41891 **  (2)  4 byte big-endian integer which is the number of valid page records
41892 **       in the journal.  If this value is 0xffffffff, then compute the
41893 **       number of page records from the journal size.
41894 **  (3)  4 byte big-endian integer which is the initial value for the 
41895 **       sanity checksum.
41896 **  (4)  4 byte integer which is the number of pages to truncate the
41897 **       database to during a rollback.
41898 **  (5)  4 byte big-endian integer which is the sector size.  The header
41899 **       is this many bytes in size.
41900 **  (6)  4 byte big-endian integer which is the page size.
41901 **  (7)  zero padding out to the next sector size.
41902 **  (8)  Zero or more pages instances, each as follows:
41903 **        +  4 byte page number.
41904 **        +  pPager->pageSize bytes of data.
41905 **        +  4 byte checksum
41906 **
41907 ** When we speak of the journal header, we mean the first 7 items above.
41908 ** Each entry in the journal is an instance of the 8th item.
41909 **
41910 ** Call the value from the second bullet "nRec".  nRec is the number of
41911 ** valid page entries in the journal.  In most cases, you can compute the
41912 ** value of nRec from the size of the journal file.  But if a power
41913 ** failure occurred while the journal was being written, it could be the
41914 ** case that the size of the journal file had already been increased but
41915 ** the extra entries had not yet made it safely to disk.  In such a case,
41916 ** the value of nRec computed from the file size would be too large.  For
41917 ** that reason, we always use the nRec value in the header.
41918 **
41919 ** If the nRec value is 0xffffffff it means that nRec should be computed
41920 ** from the file size.  This value is used when the user selects the
41921 ** no-sync option for the journal.  A power failure could lead to corruption
41922 ** in this case.  But for things like temporary table (which will be
41923 ** deleted when the power is restored) we don't care.  
41924 **
41925 ** If the file opened as the journal file is not a well-formed
41926 ** journal file then all pages up to the first corrupted page are rolled
41927 ** back (or no pages if the journal header is corrupted). The journal file
41928 ** is then deleted and SQLCIPHER_OK returned, just as if no corruption had
41929 ** been encountered.
41930 **
41931 ** If an I/O or malloc() error occurs, the journal-file is not deleted
41932 ** and an error code is returned.
41933 **
41934 ** The isHot parameter indicates that we are trying to rollback a journal
41935 ** that might be a hot journal.  Or, it could be that the journal is 
41936 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
41937 ** If the journal really is hot, reset the pager cache prior rolling
41938 ** back any content.  If the journal is merely persistent, no reset is
41939 ** needed.
41940 */
41941 static int pager_playback(Pager *pPager, int isHot){
41942   sqlcipher3_vfs *pVfs = pPager->pVfs;
41943   i64 szJ;                 /* Size of the journal file in bytes */
41944   u32 nRec;                /* Number of Records in the journal */
41945   u32 u;                   /* Unsigned loop counter */
41946   Pgno mxPg = 0;           /* Size of the original file in pages */
41947   int rc;                  /* Result code of a subroutine */
41948   int res = 1;             /* Value returned by sqlcipher3OsAccess() */
41949   char *zMaster = 0;       /* Name of master journal file if any */
41950   int needPagerReset;      /* True to reset page prior to first page rollback */
41951
41952   /* Figure out how many records are in the journal.  Abort early if
41953   ** the journal is empty.
41954   */
41955   assert( isOpen(pPager->jfd) );
41956   rc = sqlcipher3OsFileSize(pPager->jfd, &szJ);
41957   if( rc!=SQLCIPHER_OK ){
41958     goto end_playback;
41959   }
41960
41961   /* Read the master journal name from the journal, if it is present.
41962   ** If a master journal file name is specified, but the file is not
41963   ** present on disk, then the journal is not hot and does not need to be
41964   ** played back.
41965   **
41966   ** TODO: Technically the following is an error because it assumes that
41967   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
41968   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
41969   **  mxPathname is 512, which is the same as the minimum allowable value
41970   ** for pageSize.
41971   */
41972   zMaster = pPager->pTmpSpace;
41973   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41974   if( rc==SQLCIPHER_OK && zMaster[0] ){
41975     rc = sqlcipher3OsAccess(pVfs, zMaster, SQLCIPHER_ACCESS_EXISTS, &res);
41976   }
41977   zMaster = 0;
41978   if( rc!=SQLCIPHER_OK || !res ){
41979     goto end_playback;
41980   }
41981   pPager->journalOff = 0;
41982   needPagerReset = isHot;
41983
41984   /* This loop terminates either when a readJournalHdr() or 
41985   ** pager_playback_one_page() call returns SQLCIPHER_DONE or an IO error 
41986   ** occurs. 
41987   */
41988   while( 1 ){
41989     /* Read the next journal header from the journal file.  If there are
41990     ** not enough bytes left in the journal file for a complete header, or
41991     ** it is corrupted, then a process must have failed while writing it.
41992     ** This indicates nothing more needs to be rolled back.
41993     */
41994     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
41995     if( rc!=SQLCIPHER_OK ){ 
41996       if( rc==SQLCIPHER_DONE ){
41997         rc = SQLCIPHER_OK;
41998       }
41999       goto end_playback;
42000     }
42001
42002     /* If nRec is 0xffffffff, then this journal was created by a process
42003     ** working in no-sync mode. This means that the rest of the journal
42004     ** file consists of pages, there are no more journal headers. Compute
42005     ** the value of nRec based on this assumption.
42006     */
42007     if( nRec==0xffffffff ){
42008       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
42009       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
42010     }
42011
42012     /* If nRec is 0 and this rollback is of a transaction created by this
42013     ** process and if this is the final header in the journal, then it means
42014     ** that this part of the journal was being filled but has not yet been
42015     ** synced to disk.  Compute the number of pages based on the remaining
42016     ** size of the file.
42017     **
42018     ** The third term of the test was added to fix ticket #2565.
42019     ** When rolling back a hot journal, nRec==0 always means that the next
42020     ** chunk of the journal contains zero pages to be rolled back.  But
42021     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
42022     ** the journal, it means that the journal might contain additional
42023     ** pages that need to be rolled back and that the number of pages 
42024     ** should be computed based on the journal file size.
42025     */
42026     if( nRec==0 && !isHot &&
42027         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
42028       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
42029     }
42030
42031     /* If this is the first header read from the journal, truncate the
42032     ** database file back to its original size.
42033     */
42034     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
42035       rc = pager_truncate(pPager, mxPg);
42036       if( rc!=SQLCIPHER_OK ){
42037         goto end_playback;
42038       }
42039       pPager->dbSize = mxPg;
42040     }
42041
42042     /* Copy original pages out of the journal and back into the 
42043     ** database file and/or page cache.
42044     */
42045     for(u=0; u<nRec; u++){
42046       if( needPagerReset ){
42047         pager_reset(pPager);
42048         needPagerReset = 0;
42049       }
42050       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
42051       if( rc!=SQLCIPHER_OK ){
42052         if( rc==SQLCIPHER_DONE ){
42053           pPager->journalOff = szJ;
42054           break;
42055         }else if( rc==SQLCIPHER_IOERR_SHORT_READ ){
42056           /* If the journal has been truncated, simply stop reading and
42057           ** processing the journal. This might happen if the journal was
42058           ** not completely written and synced prior to a crash.  In that
42059           ** case, the database should have never been written in the
42060           ** first place so it is OK to simply abandon the rollback. */
42061           rc = SQLCIPHER_OK;
42062           goto end_playback;
42063         }else{
42064           /* If we are unable to rollback, quit and return the error
42065           ** code.  This will cause the pager to enter the error state
42066           ** so that no further harm will be done.  Perhaps the next
42067           ** process to come along will be able to rollback the database.
42068           */
42069           goto end_playback;
42070         }
42071       }
42072     }
42073   }
42074   /*NOTREACHED*/
42075   assert( 0 );
42076
42077 end_playback:
42078   /* Following a rollback, the database file should be back in its original
42079   ** state prior to the start of the transaction, so invoke the
42080   ** SQLCIPHER_FCNTL_DB_UNCHANGED file-control method to disable the
42081   ** assertion that the transaction counter was modified.
42082   */
42083   assert(
42084     pPager->fd->pMethods==0 ||
42085     sqlcipher3OsFileControl(pPager->fd,SQLCIPHER_FCNTL_DB_UNCHANGED,0)>=SQLCIPHER_OK
42086   );
42087
42088   /* If this playback is happening automatically as a result of an IO or 
42089   ** malloc error that occurred after the change-counter was updated but 
42090   ** before the transaction was committed, then the change-counter 
42091   ** modification may just have been reverted. If this happens in exclusive 
42092   ** mode, then subsequent transactions performed by the connection will not
42093   ** update the change-counter at all. This may lead to cache inconsistency
42094   ** problems for other processes at some point in the future. So, just
42095   ** in case this has happened, clear the changeCountDone flag now.
42096   */
42097   pPager->changeCountDone = pPager->tempFile;
42098
42099   if( rc==SQLCIPHER_OK ){
42100     zMaster = pPager->pTmpSpace;
42101     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
42102     testcase( rc!=SQLCIPHER_OK );
42103   }
42104   if( rc==SQLCIPHER_OK
42105    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
42106   ){
42107     rc = sqlcipher3PagerSync(pPager);
42108   }
42109   if( rc==SQLCIPHER_OK ){
42110     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
42111     testcase( rc!=SQLCIPHER_OK );
42112   }
42113   if( rc==SQLCIPHER_OK && zMaster[0] && res ){
42114     /* If there was a master journal and this routine will return success,
42115     ** see if it is possible to delete the master journal.
42116     */
42117     rc = pager_delmaster(pPager, zMaster);
42118     testcase( rc!=SQLCIPHER_OK );
42119   }
42120
42121   /* The Pager.sectorSize variable may have been updated while rolling
42122   ** back a journal created by a process with a different sector size
42123   ** value. Reset it to the correct value for this process.
42124   */
42125   setSectorSize(pPager);
42126   return rc;
42127 }
42128
42129
42130 /*
42131 ** Read the content for page pPg out of the database file and into 
42132 ** pPg->pData. A shared lock or greater must be held on the database
42133 ** file before this function is called.
42134 **
42135 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
42136 ** the value read from the database file.
42137 **
42138 ** If an IO error occurs, then the IO error is returned to the caller.
42139 ** Otherwise, SQLCIPHER_OK is returned.
42140 */
42141 static int readDbPage(PgHdr *pPg){
42142   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
42143   Pgno pgno = pPg->pgno;       /* Page number to read */
42144   int rc = SQLCIPHER_OK;          /* Return code */
42145   int isInWal = 0;             /* True if page is in log file */
42146   int pgsz = pPager->pageSize; /* Number of bytes to read */
42147
42148   assert( pPager->eState>=PAGER_READER && !MEMDB );
42149   assert( isOpen(pPager->fd) );
42150
42151   if( NEVER(!isOpen(pPager->fd)) ){
42152     assert( pPager->tempFile );
42153     memset(pPg->pData, 0, pPager->pageSize);
42154     return SQLCIPHER_OK;
42155   }
42156
42157   if( pagerUseWal(pPager) ){
42158     /* Try to pull the page from the write-ahead log. */
42159     rc = sqlcipher3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
42160   }
42161   if( rc==SQLCIPHER_OK && !isInWal ){
42162     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
42163     rc = sqlcipher3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
42164     if( rc==SQLCIPHER_IOERR_SHORT_READ ){
42165       rc = SQLCIPHER_OK;
42166     }
42167   }
42168
42169   if( pgno==1 ){
42170     if( rc ){
42171       /* If the read is unsuccessful, set the dbFileVers[] to something
42172       ** that will never be a valid file version.  dbFileVers[] is a copy
42173       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
42174       ** zero or the size of the database in page. Bytes 32..35 and 35..39
42175       ** should be page numbers which are never 0xffffffff.  So filling
42176       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
42177       **
42178       ** For an encrypted database, the situation is more complex:  bytes
42179       ** 24..39 of the database are white noise.  But the probability of
42180       ** white noising equaling 16 bytes of 0xff is vanishingly small so
42181       ** we should still be ok.
42182       */
42183       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
42184     }else{
42185       u8 *dbFileVers = &((u8*)pPg->pData)[24];
42186       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
42187     }
42188   }
42189   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLCIPHER_NOMEM);
42190
42191   PAGER_INCR(sqlcipher3_pager_readdb_count);
42192   PAGER_INCR(pPager->nRead);
42193   IOTRACE(("PGIN %p %d\n", pPager, pgno));
42194   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
42195                PAGERID(pPager), pgno, pager_pagehash(pPg)));
42196
42197   return rc;
42198 }
42199
42200 /*
42201 ** Update the value of the change-counter at offsets 24 and 92 in
42202 ** the header and the sqlcipher version number at offset 96.
42203 **
42204 ** This is an unconditional update.  See also the pager_incr_changecounter()
42205 ** routine which only updates the change-counter if the update is actually
42206 ** needed, as determined by the pPager->changeCountDone state variable.
42207 */
42208 static void pager_write_changecounter(PgHdr *pPg){
42209   u32 change_counter;
42210
42211   /* Increment the value just read and write it back to byte 24. */
42212   change_counter = sqlcipher3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
42213   put32bits(((char*)pPg->pData)+24, change_counter);
42214
42215   /* Also store the SQLite version number in bytes 96..99 and in
42216   ** bytes 92..95 store the change counter for which the version number
42217   ** is valid. */
42218   put32bits(((char*)pPg->pData)+92, change_counter);
42219   put32bits(((char*)pPg->pData)+96, SQLCIPHER_VERSION_NUMBER);
42220 }
42221
42222 #ifndef SQLCIPHER_OMIT_WAL
42223 /*
42224 ** This function is invoked once for each page that has already been 
42225 ** written into the log file when a WAL transaction is rolled back.
42226 ** Parameter iPg is the page number of said page. The pCtx argument 
42227 ** is actually a pointer to the Pager structure.
42228 **
42229 ** If page iPg is present in the cache, and has no outstanding references,
42230 ** it is discarded. Otherwise, if there are one or more outstanding
42231 ** references, the page content is reloaded from the database. If the
42232 ** attempt to reload content from the database is required and fails, 
42233 ** return an SQLite error code. Otherwise, SQLCIPHER_OK.
42234 */
42235 static int pagerUndoCallback(void *pCtx, Pgno iPg){
42236   int rc = SQLCIPHER_OK;
42237   Pager *pPager = (Pager *)pCtx;
42238   PgHdr *pPg;
42239
42240   pPg = sqlcipher3PagerLookup(pPager, iPg);
42241   if( pPg ){
42242     if( sqlcipher3PcachePageRefcount(pPg)==1 ){
42243       sqlcipher3PcacheDrop(pPg);
42244     }else{
42245       rc = readDbPage(pPg);
42246       if( rc==SQLCIPHER_OK ){
42247         pPager->xReiniter(pPg);
42248       }
42249       sqlcipher3PagerUnref(pPg);
42250     }
42251   }
42252
42253   /* Normally, if a transaction is rolled back, any backup processes are
42254   ** updated as data is copied out of the rollback journal and into the
42255   ** database. This is not generally possible with a WAL database, as
42256   ** rollback involves simply truncating the log file. Therefore, if one
42257   ** or more frames have already been written to the log (and therefore 
42258   ** also copied into the backup databases) as part of this transaction,
42259   ** the backups must be restarted.
42260   */
42261   sqlcipher3BackupRestart(pPager->pBackup);
42262
42263   return rc;
42264 }
42265
42266 /*
42267 ** This function is called to rollback a transaction on a WAL database.
42268 */
42269 static int pagerRollbackWal(Pager *pPager){
42270   int rc;                         /* Return Code */
42271   PgHdr *pList;                   /* List of dirty pages to revert */
42272
42273   /* For all pages in the cache that are currently dirty or have already
42274   ** been written (but not committed) to the log file, do one of the 
42275   ** following:
42276   **
42277   **   + Discard the cached page (if refcount==0), or
42278   **   + Reload page content from the database (if refcount>0).
42279   */
42280   pPager->dbSize = pPager->dbOrigSize;
42281   rc = sqlcipher3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
42282   pList = sqlcipher3PcacheDirtyList(pPager->pPCache);
42283   while( pList && rc==SQLCIPHER_OK ){
42284     PgHdr *pNext = pList->pDirty;
42285     rc = pagerUndoCallback((void *)pPager, pList->pgno);
42286     pList = pNext;
42287   }
42288
42289   return rc;
42290 }
42291
42292 /*
42293 ** This function is a wrapper around sqlcipher3WalFrames(). As well as logging
42294 ** the contents of the list of pages headed by pList (connected by pDirty),
42295 ** this function notifies any active backup processes that the pages have
42296 ** changed. 
42297 **
42298 ** The list of pages passed into this routine is always sorted by page number.
42299 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
42300 */ 
42301 static int pagerWalFrames(
42302   Pager *pPager,                  /* Pager object */
42303   PgHdr *pList,                   /* List of frames to log */
42304   Pgno nTruncate,                 /* Database size after this commit */
42305   int isCommit,                   /* True if this is a commit */
42306   int syncFlags                   /* Flags to pass to OsSync() (or 0) */
42307 ){
42308   int rc;                         /* Return code */
42309 #if defined(SQLCIPHER_DEBUG) || defined(SQLCIPHER_CHECK_PAGES)
42310   PgHdr *p;                       /* For looping over pages */
42311 #endif
42312
42313   assert( pPager->pWal );
42314   assert( pList );
42315 #ifdef SQLCIPHER_DEBUG
42316   /* Verify that the page list is in accending order */
42317   for(p=pList; p && p->pDirty; p=p->pDirty){
42318     assert( p->pgno < p->pDirty->pgno );
42319   }
42320 #endif
42321
42322   if( isCommit ){
42323     /* If a WAL transaction is being committed, there is no point in writing
42324     ** any pages with page numbers greater than nTruncate into the WAL file.
42325     ** They will never be read by any client. So remove them from the pDirty
42326     ** list here. */
42327     PgHdr *p;
42328     PgHdr **ppNext = &pList;
42329     for(p=pList; (*ppNext = p); p=p->pDirty){
42330       if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
42331     }
42332     assert( pList );
42333   }
42334
42335   if( pList->pgno==1 ) pager_write_changecounter(pList);
42336   rc = sqlcipher3WalFrames(pPager->pWal, 
42337       pPager->pageSize, pList, nTruncate, isCommit, syncFlags
42338   );
42339   if( rc==SQLCIPHER_OK && pPager->pBackup ){
42340     PgHdr *p;
42341     for(p=pList; p; p=p->pDirty){
42342       sqlcipher3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
42343     }
42344   }
42345
42346 #ifdef SQLCIPHER_CHECK_PAGES
42347   pList = sqlcipher3PcacheDirtyList(pPager->pPCache);
42348   for(p=pList; p; p=p->pDirty){
42349     pager_set_pagehash(p);
42350   }
42351 #endif
42352
42353   return rc;
42354 }
42355
42356 /*
42357 ** Begin a read transaction on the WAL.
42358 **
42359 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
42360 ** makes a snapshot of the database at the current point in time and preserves
42361 ** that snapshot for use by the reader in spite of concurrently changes by
42362 ** other writers or checkpointers.
42363 */
42364 static int pagerBeginReadTransaction(Pager *pPager){
42365   int rc;                         /* Return code */
42366   int changed = 0;                /* True if cache must be reset */
42367
42368   assert( pagerUseWal(pPager) );
42369   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
42370
42371   /* sqlcipher3WalEndReadTransaction() was not called for the previous
42372   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
42373   ** are in locking_mode=NORMAL and EndRead() was previously called,
42374   ** the duplicate call is harmless.
42375   */
42376   sqlcipher3WalEndReadTransaction(pPager->pWal);
42377
42378   rc = sqlcipher3WalBeginReadTransaction(pPager->pWal, &changed);
42379   if( rc!=SQLCIPHER_OK || changed ){
42380     pager_reset(pPager);
42381   }
42382
42383   return rc;
42384 }
42385 #endif
42386
42387 /*
42388 ** This function is called as part of the transition from PAGER_OPEN
42389 ** to PAGER_READER state to determine the size of the database file
42390 ** in pages (assuming the page size currently stored in Pager.pageSize).
42391 **
42392 ** If no error occurs, SQLCIPHER_OK is returned and the size of the database
42393 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
42394 ** SQLCIPHER_IOERR_FSTAT) is returned and *pnPage is left unmodified.
42395 */
42396 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
42397   Pgno nPage;                     /* Value to return via *pnPage */
42398
42399   /* Query the WAL sub-system for the database size. The WalDbsize()
42400   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
42401   ** if the database size is not available. The database size is not
42402   ** available from the WAL sub-system if the log file is empty or
42403   ** contains no valid committed transactions.
42404   */
42405   assert( pPager->eState==PAGER_OPEN );
42406   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
42407   nPage = sqlcipher3WalDbsize(pPager->pWal);
42408
42409   /* If the database size was not available from the WAL sub-system,
42410   ** determine it based on the size of the database file. If the size
42411   ** of the database file is not an integer multiple of the page-size,
42412   ** round down to the nearest page. Except, any file larger than 0
42413   ** bytes in size is considered to contain at least one page.
42414   */
42415   if( nPage==0 ){
42416     i64 n = 0;                    /* Size of db file in bytes */
42417     assert( isOpen(pPager->fd) || pPager->tempFile );
42418     if( isOpen(pPager->fd) ){
42419       int rc = sqlcipher3OsFileSize(pPager->fd, &n);
42420       if( rc!=SQLCIPHER_OK ){
42421         return rc;
42422       }
42423     }
42424     nPage = (Pgno)(n / pPager->pageSize);
42425     if( nPage==0 && n>0 ){
42426       nPage = 1;
42427     }
42428   }
42429
42430   /* If the current number of pages in the file is greater than the
42431   ** configured maximum pager number, increase the allowed limit so
42432   ** that the file can be read.
42433   */
42434   if( nPage>pPager->mxPgno ){
42435     pPager->mxPgno = (Pgno)nPage;
42436   }
42437
42438   *pnPage = nPage;
42439   return SQLCIPHER_OK;
42440 }
42441
42442 #ifndef SQLCIPHER_OMIT_WAL
42443 /*
42444 ** Check if the *-wal file that corresponds to the database opened by pPager
42445 ** exists if the database is not empy, or verify that the *-wal file does
42446 ** not exist (by deleting it) if the database file is empty.
42447 **
42448 ** If the database is not empty and the *-wal file exists, open the pager
42449 ** in WAL mode.  If the database is empty or if no *-wal file exists and
42450 ** if no error occurs, make sure Pager.journalMode is not set to
42451 ** PAGER_JOURNALMODE_WAL.
42452 **
42453 ** Return SQLCIPHER_OK or an error code.
42454 **
42455 ** The caller must hold a SHARED lock on the database file to call this
42456 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
42457 ** a WAL on a none-empty database, this ensures there is no race condition 
42458 ** between the xAccess() below and an xDelete() being executed by some 
42459 ** other connection.
42460 */
42461 static int pagerOpenWalIfPresent(Pager *pPager){
42462   int rc = SQLCIPHER_OK;
42463   assert( pPager->eState==PAGER_OPEN );
42464   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
42465
42466   if( !pPager->tempFile ){
42467     int isWal;                    /* True if WAL file exists */
42468     Pgno nPage;                   /* Size of the database file */
42469
42470     rc = pagerPagecount(pPager, &nPage);
42471     if( rc ) return rc;
42472     if( nPage==0 ){
42473       rc = sqlcipher3OsDelete(pPager->pVfs, pPager->zWal, 0);
42474       isWal = 0;
42475     }else{
42476       rc = sqlcipher3OsAccess(
42477           pPager->pVfs, pPager->zWal, SQLCIPHER_ACCESS_EXISTS, &isWal
42478       );
42479     }
42480     if( rc==SQLCIPHER_OK ){
42481       if( isWal ){
42482         testcase( sqlcipher3PcachePagecount(pPager->pPCache)==0 );
42483         rc = sqlcipher3PagerOpenWal(pPager, 0);
42484       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
42485         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
42486       }
42487     }
42488   }
42489   return rc;
42490 }
42491 #endif
42492
42493 /*
42494 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
42495 ** the entire master journal file. The case pSavepoint==NULL occurs when 
42496 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
42497 ** savepoint.
42498 **
42499 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
42500 ** being rolled back), then the rollback consists of up to three stages,
42501 ** performed in the order specified:
42502 **
42503 **   * Pages are played back from the main journal starting at byte
42504 **     offset PagerSavepoint.iOffset and continuing to 
42505 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
42506 **     file if PagerSavepoint.iHdrOffset is zero.
42507 **
42508 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
42509 **     back starting from the journal header immediately following 
42510 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
42511 **
42512 **   * Pages are then played back from the sub-journal file, starting
42513 **     with the PagerSavepoint.iSubRec and continuing to the end of
42514 **     the journal file.
42515 **
42516 ** Throughout the rollback process, each time a page is rolled back, the
42517 ** corresponding bit is set in a bitvec structure (variable pDone in the
42518 ** implementation below). This is used to ensure that a page is only
42519 ** rolled back the first time it is encountered in either journal.
42520 **
42521 ** If pSavepoint is NULL, then pages are only played back from the main
42522 ** journal file. There is no need for a bitvec in this case.
42523 **
42524 ** In either case, before playback commences the Pager.dbSize variable
42525 ** is reset to the value that it held at the start of the savepoint 
42526 ** (or transaction). No page with a page-number greater than this value
42527 ** is played back. If one is encountered it is simply skipped.
42528 */
42529 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
42530   i64 szJ;                 /* Effective size of the main journal */
42531   i64 iHdrOff;             /* End of first segment of main-journal records */
42532   int rc = SQLCIPHER_OK;      /* Return code */
42533   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
42534
42535   assert( pPager->eState!=PAGER_ERROR );
42536   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42537
42538   /* Allocate a bitvec to use to store the set of pages rolled back */
42539   if( pSavepoint ){
42540     pDone = sqlcipher3BitvecCreate(pSavepoint->nOrig);
42541     if( !pDone ){
42542       return SQLCIPHER_NOMEM;
42543     }
42544   }
42545
42546   /* Set the database size back to the value it was before the savepoint 
42547   ** being reverted was opened.
42548   */
42549   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
42550   pPager->changeCountDone = pPager->tempFile;
42551
42552   if( !pSavepoint && pagerUseWal(pPager) ){
42553     return pagerRollbackWal(pPager);
42554   }
42555
42556   /* Use pPager->journalOff as the effective size of the main rollback
42557   ** journal.  The actual file might be larger than this in
42558   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
42559   ** past pPager->journalOff is off-limits to us.
42560   */
42561   szJ = pPager->journalOff;
42562   assert( pagerUseWal(pPager)==0 || szJ==0 );
42563
42564   /* Begin by rolling back records from the main journal starting at
42565   ** PagerSavepoint.iOffset and continuing to the next journal header.
42566   ** There might be records in the main journal that have a page number
42567   ** greater than the current database size (pPager->dbSize) but those
42568   ** will be skipped automatically.  Pages are added to pDone as they
42569   ** are played back.
42570   */
42571   if( pSavepoint && !pagerUseWal(pPager) ){
42572     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
42573     pPager->journalOff = pSavepoint->iOffset;
42574     while( rc==SQLCIPHER_OK && pPager->journalOff<iHdrOff ){
42575       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
42576     }
42577     assert( rc!=SQLCIPHER_DONE );
42578   }else{
42579     pPager->journalOff = 0;
42580   }
42581
42582   /* Continue rolling back records out of the main journal starting at
42583   ** the first journal header seen and continuing until the effective end
42584   ** of the main journal file.  Continue to skip out-of-range pages and
42585   ** continue adding pages rolled back to pDone.
42586   */
42587   while( rc==SQLCIPHER_OK && pPager->journalOff<szJ ){
42588     u32 ii;            /* Loop counter */
42589     u32 nJRec = 0;     /* Number of Journal Records */
42590     u32 dummy;
42591     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
42592     assert( rc!=SQLCIPHER_DONE );
42593
42594     /*
42595     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
42596     ** test is related to ticket #2565.  See the discussion in the
42597     ** pager_playback() function for additional information.
42598     */
42599     if( nJRec==0 
42600      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
42601     ){
42602       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
42603     }
42604     for(ii=0; rc==SQLCIPHER_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
42605       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
42606     }
42607     assert( rc!=SQLCIPHER_DONE );
42608   }
42609   assert( rc!=SQLCIPHER_OK || pPager->journalOff>=szJ );
42610
42611   /* Finally,  rollback pages from the sub-journal.  Page that were
42612   ** previously rolled back out of the main journal (and are hence in pDone)
42613   ** will be skipped.  Out-of-range pages are also skipped.
42614   */
42615   if( pSavepoint ){
42616     u32 ii;            /* Loop counter */
42617     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
42618
42619     if( pagerUseWal(pPager) ){
42620       rc = sqlcipher3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
42621     }
42622     for(ii=pSavepoint->iSubRec; rc==SQLCIPHER_OK && ii<pPager->nSubRec; ii++){
42623       assert( offset==ii*(4+pPager->pageSize) );
42624       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
42625     }
42626     assert( rc!=SQLCIPHER_DONE );
42627   }
42628
42629   sqlcipher3BitvecDestroy(pDone);
42630   if( rc==SQLCIPHER_OK ){
42631     pPager->journalOff = szJ;
42632   }
42633
42634   return rc;
42635 }
42636
42637 /*
42638 ** Change the maximum number of in-memory pages that are allowed.
42639 */
42640 SQLCIPHER_PRIVATE void sqlcipher3PagerSetCachesize(Pager *pPager, int mxPage){
42641   sqlcipher3PcacheSetCachesize(pPager->pPCache, mxPage);
42642 }
42643
42644 /*
42645 ** Adjust the robustness of the database to damage due to OS crashes
42646 ** or power failures by changing the number of syncs()s when writing
42647 ** the rollback journal.  There are three levels:
42648 **
42649 **    OFF       sqlcipher3OsSync() is never called.  This is the default
42650 **              for temporary and transient files.
42651 **
42652 **    NORMAL    The journal is synced once before writes begin on the
42653 **              database.  This is normally adequate protection, but
42654 **              it is theoretically possible, though very unlikely,
42655 **              that an inopertune power failure could leave the journal
42656 **              in a state which would cause damage to the database
42657 **              when it is rolled back.
42658 **
42659 **    FULL      The journal is synced twice before writes begin on the
42660 **              database (with some additional information - the nRec field
42661 **              of the journal header - being written in between the two
42662 **              syncs).  If we assume that writing a
42663 **              single disk sector is atomic, then this mode provides
42664 **              assurance that the journal will not be corrupted to the
42665 **              point of causing damage to the database during rollback.
42666 **
42667 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
42668 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
42669 ** prior to the start of checkpoint and that the database file is synced
42670 ** at the conclusion of the checkpoint if the entire content of the WAL
42671 ** was written back into the database.  But no sync operations occur for
42672 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
42673 ** file is synced following each commit operation, in addition to the
42674 ** syncs associated with NORMAL.
42675 **
42676 ** Do not confuse synchronous=FULL with SQLCIPHER_SYNC_FULL.  The
42677 ** SQLCIPHER_SYNC_FULL macro means to use the MacOSX-style full-fsync
42678 ** using fcntl(F_FULLFSYNC).  SQLCIPHER_SYNC_NORMAL means to do an
42679 ** ordinary fsync() call.  There is no difference between SQLCIPHER_SYNC_FULL
42680 ** and SQLCIPHER_SYNC_NORMAL on platforms other than MacOSX.  But the
42681 ** synchronous=FULL versus synchronous=NORMAL setting determines when
42682 ** the xSync primitive is called and is relevant to all platforms.
42683 **
42684 ** Numeric values associated with these states are OFF==1, NORMAL=2,
42685 ** and FULL=3.
42686 */
42687 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
42688 SQLCIPHER_PRIVATE void sqlcipher3PagerSetSafetyLevel(
42689   Pager *pPager,        /* The pager to set safety level for */
42690   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */  
42691   int bFullFsync,       /* PRAGMA fullfsync */
42692   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
42693 ){
42694   assert( level>=1 && level<=3 );
42695   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
42696   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
42697   if( pPager->noSync ){
42698     pPager->syncFlags = 0;
42699     pPager->ckptSyncFlags = 0;
42700   }else if( bFullFsync ){
42701     pPager->syncFlags = SQLCIPHER_SYNC_FULL;
42702     pPager->ckptSyncFlags = SQLCIPHER_SYNC_FULL;
42703   }else if( bCkptFullFsync ){
42704     pPager->syncFlags = SQLCIPHER_SYNC_NORMAL;
42705     pPager->ckptSyncFlags = SQLCIPHER_SYNC_FULL;
42706   }else{
42707     pPager->syncFlags = SQLCIPHER_SYNC_NORMAL;
42708     pPager->ckptSyncFlags = SQLCIPHER_SYNC_NORMAL;
42709   }
42710 }
42711 #endif
42712
42713 /*
42714 ** The following global variable is incremented whenever the library
42715 ** attempts to open a temporary file.  This information is used for
42716 ** testing and analysis only.  
42717 */
42718 #ifdef SQLCIPHER_TEST
42719 SQLCIPHER_API int sqlcipher3_opentemp_count = 0;
42720 #endif
42721
42722 /*
42723 ** Open a temporary file.
42724 **
42725 ** Write the file descriptor into *pFile. Return SQLCIPHER_OK on success 
42726 ** or some other error code if we fail. The OS will automatically 
42727 ** delete the temporary file when it is closed.
42728 **
42729 ** The flags passed to the VFS layer xOpen() call are those specified
42730 ** by parameter vfsFlags ORed with the following:
42731 **
42732 **     SQLCIPHER_OPEN_READWRITE
42733 **     SQLCIPHER_OPEN_CREATE
42734 **     SQLCIPHER_OPEN_EXCLUSIVE
42735 **     SQLCIPHER_OPEN_DELETEONCLOSE
42736 */
42737 static int pagerOpentemp(
42738   Pager *pPager,        /* The pager object */
42739   sqlcipher3_file *pFile,  /* Write the file descriptor here */
42740   int vfsFlags          /* Flags passed through to the VFS */
42741 ){
42742   int rc;               /* Return code */
42743
42744 #ifdef SQLCIPHER_TEST
42745   sqlcipher3_opentemp_count++;  /* Used for testing and analysis only */
42746 #endif
42747
42748   vfsFlags |=  SQLCIPHER_OPEN_READWRITE | SQLCIPHER_OPEN_CREATE |
42749             SQLCIPHER_OPEN_EXCLUSIVE | SQLCIPHER_OPEN_DELETEONCLOSE;
42750   rc = sqlcipher3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
42751   assert( rc!=SQLCIPHER_OK || isOpen(pFile) );
42752   return rc;
42753 }
42754
42755 /*
42756 ** Set the busy handler function.
42757 **
42758 ** The pager invokes the busy-handler if sqlcipher3OsLock() returns 
42759 ** SQLCIPHER_BUSY when trying to upgrade from no-lock to a SHARED lock,
42760 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
42761 ** lock. It does *not* invoke the busy handler when upgrading from
42762 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
42763 ** (which occurs during hot-journal rollback). Summary:
42764 **
42765 **   Transition                        | Invokes xBusyHandler
42766 **   --------------------------------------------------------
42767 **   NO_LOCK       -> SHARED_LOCK      | Yes
42768 **   SHARED_LOCK   -> RESERVED_LOCK    | No
42769 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
42770 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
42771 **
42772 ** If the busy-handler callback returns non-zero, the lock is 
42773 ** retried. If it returns zero, then the SQLCIPHER_BUSY error is
42774 ** returned to the caller of the pager API function.
42775 */
42776 SQLCIPHER_PRIVATE void sqlcipher3PagerSetBusyhandler(
42777   Pager *pPager,                       /* Pager object */
42778   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
42779   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
42780 ){  
42781   pPager->xBusyHandler = xBusyHandler;
42782   pPager->pBusyHandlerArg = pBusyHandlerArg;
42783 }
42784
42785 /*
42786 ** Change the page size used by the Pager object. The new page size 
42787 ** is passed in *pPageSize.
42788 **
42789 ** If the pager is in the error state when this function is called, it
42790 ** is a no-op. The value returned is the error state error code (i.e. 
42791 ** one of SQLCIPHER_IOERR, an SQLCIPHER_IOERR_xxx sub-code or SQLCIPHER_FULL).
42792 **
42793 ** Otherwise, if all of the following are true:
42794 **
42795 **   * the new page size (value of *pPageSize) is valid (a power 
42796 **     of two between 512 and SQLCIPHER_MAX_PAGE_SIZE, inclusive), and
42797 **
42798 **   * there are no outstanding page references, and
42799 **
42800 **   * the database is either not an in-memory database or it is
42801 **     an in-memory database that currently consists of zero pages.
42802 **
42803 ** then the pager object page size is set to *pPageSize.
42804 **
42805 ** If the page size is changed, then this function uses sqlcipher3PagerMalloc() 
42806 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
42807 ** fails, SQLCIPHER_NOMEM is returned and the page size remains unchanged. 
42808 ** In all other cases, SQLCIPHER_OK is returned.
42809 **
42810 ** If the page size is not changed, either because one of the enumerated
42811 ** conditions above is not true, the pager was in error state when this
42812 ** function was called, or because the memory allocation attempt failed, 
42813 ** then *pPageSize is set to the old, retained page size before returning.
42814 */
42815 SQLCIPHER_PRIVATE int sqlcipher3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
42816   int rc = SQLCIPHER_OK;
42817
42818   /* It is not possible to do a full assert_pager_state() here, as this
42819   ** function may be called from within PagerOpen(), before the state
42820   ** of the Pager object is internally consistent.
42821   **
42822   ** At one point this function returned an error if the pager was in 
42823   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
42824   ** there is at least one outstanding page reference, this function
42825   ** is a no-op for that case anyhow.
42826   */
42827
42828   u32 pageSize = *pPageSize;
42829   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLCIPHER_MAX_PAGE_SIZE) );
42830   if( (pPager->memDb==0 || pPager->dbSize==0)
42831    && sqlcipher3PcacheRefCount(pPager->pPCache)==0 
42832    && pageSize && pageSize!=(u32)pPager->pageSize 
42833   ){
42834     char *pNew = NULL;             /* New temp space */
42835     i64 nByte = 0;
42836
42837     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
42838       rc = sqlcipher3OsFileSize(pPager->fd, &nByte);
42839     }
42840     if( rc==SQLCIPHER_OK ){
42841       pNew = (char *)sqlcipher3PageMalloc(pageSize);
42842       if( !pNew ) rc = SQLCIPHER_NOMEM;
42843     }
42844
42845     if( rc==SQLCIPHER_OK ){
42846       pager_reset(pPager);
42847       pPager->dbSize = (Pgno)(nByte/pageSize);
42848       pPager->pageSize = pageSize;
42849       sqlcipher3PageFree(pPager->pTmpSpace);
42850       pPager->pTmpSpace = pNew;
42851       sqlcipher3PcacheSetPageSize(pPager->pPCache, pageSize);
42852     }
42853   }
42854
42855   *pPageSize = pPager->pageSize;
42856   if( rc==SQLCIPHER_OK ){
42857     if( nReserve<0 ) nReserve = pPager->nReserve;
42858     assert( nReserve>=0 && nReserve<1000 );
42859     pPager->nReserve = (i16)nReserve;
42860     pagerReportSize(pPager);
42861   }
42862   return rc;
42863 }
42864
42865 /*
42866 ** Return a pointer to the "temporary page" buffer held internally
42867 ** by the pager.  This is a buffer that is big enough to hold the
42868 ** entire content of a database page.  This buffer is used internally
42869 ** during rollback and will be overwritten whenever a rollback
42870 ** occurs.  But other modules are free to use it too, as long as
42871 ** no rollbacks are happening.
42872 */
42873 SQLCIPHER_PRIVATE void *sqlcipher3PagerTempSpace(Pager *pPager){
42874   return pPager->pTmpSpace;
42875 }
42876
42877 /*
42878 ** Attempt to set the maximum database page count if mxPage is positive. 
42879 ** Make no changes if mxPage is zero or negative.  And never reduce the
42880 ** maximum page count below the current size of the database.
42881 **
42882 ** Regardless of mxPage, return the current maximum page count.
42883 */
42884 SQLCIPHER_PRIVATE int sqlcipher3PagerMaxPageCount(Pager *pPager, int mxPage){
42885   if( mxPage>0 ){
42886     pPager->mxPgno = mxPage;
42887   }
42888   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
42889   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
42890   return pPager->mxPgno;
42891 }
42892
42893 /*
42894 ** The following set of routines are used to disable the simulated
42895 ** I/O error mechanism.  These routines are used to avoid simulated
42896 ** errors in places where we do not care about errors.
42897 **
42898 ** Unless -DSQLCIPHER_TEST=1 is used, these routines are all no-ops
42899 ** and generate no code.
42900 */
42901 #ifdef SQLCIPHER_TEST
42902 SQLCIPHER_API extern int sqlcipher3_io_error_pending;
42903 SQLCIPHER_API extern int sqlcipher3_io_error_hit;
42904 static int saved_cnt;
42905 void disable_simulated_io_errors(void){
42906   saved_cnt = sqlcipher3_io_error_pending;
42907   sqlcipher3_io_error_pending = -1;
42908 }
42909 void enable_simulated_io_errors(void){
42910   sqlcipher3_io_error_pending = saved_cnt;
42911 }
42912 #else
42913 # define disable_simulated_io_errors()
42914 # define enable_simulated_io_errors()
42915 #endif
42916
42917 /*
42918 ** Read the first N bytes from the beginning of the file into memory
42919 ** that pDest points to. 
42920 **
42921 ** If the pager was opened on a transient file (zFilename==""), or
42922 ** opened on a file less than N bytes in size, the output buffer is
42923 ** zeroed and SQLCIPHER_OK returned. The rationale for this is that this 
42924 ** function is used to read database headers, and a new transient or
42925 ** zero sized database has a header than consists entirely of zeroes.
42926 **
42927 ** If any IO error apart from SQLCIPHER_IOERR_SHORT_READ is encountered,
42928 ** the error code is returned to the caller and the contents of the
42929 ** output buffer undefined.
42930 */
42931 SQLCIPHER_PRIVATE int sqlcipher3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
42932   int rc = SQLCIPHER_OK;
42933   memset(pDest, 0, N);
42934   assert( isOpen(pPager->fd) || pPager->tempFile );
42935
42936   /* This routine is only called by btree immediately after creating
42937   ** the Pager object.  There has not been an opportunity to transition
42938   ** to WAL mode yet.
42939   */
42940   assert( !pagerUseWal(pPager) );
42941
42942   if( isOpen(pPager->fd) ){
42943     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
42944     rc = sqlcipher3OsRead(pPager->fd, pDest, N, 0);
42945     if( rc==SQLCIPHER_IOERR_SHORT_READ ){
42946       rc = SQLCIPHER_OK;
42947     }
42948   }
42949   return rc;
42950 }
42951
42952 /*
42953 ** This function may only be called when a read-transaction is open on
42954 ** the pager. It returns the total number of pages in the database.
42955 **
42956 ** However, if the file is between 1 and <page-size> bytes in size, then 
42957 ** this is considered a 1 page file.
42958 */
42959 SQLCIPHER_PRIVATE void sqlcipher3PagerPagecount(Pager *pPager, int *pnPage){
42960   assert( pPager->eState>=PAGER_READER );
42961   assert( pPager->eState!=PAGER_WRITER_FINISHED );
42962   *pnPage = (int)pPager->dbSize;
42963 }
42964
42965
42966 /*
42967 ** Try to obtain a lock of type locktype on the database file. If
42968 ** a similar or greater lock is already held, this function is a no-op
42969 ** (returning SQLCIPHER_OK immediately).
42970 **
42971 ** Otherwise, attempt to obtain the lock using sqlcipher3OsLock(). Invoke 
42972 ** the busy callback if the lock is currently not available. Repeat 
42973 ** until the busy callback returns false or until the attempt to 
42974 ** obtain the lock succeeds.
42975 **
42976 ** Return SQLCIPHER_OK on success and an error code if we cannot obtain
42977 ** the lock. If the lock is obtained successfully, set the Pager.state 
42978 ** variable to locktype before returning.
42979 */
42980 static int pager_wait_on_lock(Pager *pPager, int locktype){
42981   int rc;                              /* Return code */
42982
42983   /* Check that this is either a no-op (because the requested lock is 
42984   ** already held, or one of the transistions that the busy-handler
42985   ** may be invoked during, according to the comment above
42986   ** sqlcipher3PagerSetBusyhandler().
42987   */
42988   assert( (pPager->eLock>=locktype)
42989        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
42990        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
42991   );
42992
42993   do {
42994     rc = pagerLockDb(pPager, locktype);
42995   }while( rc==SQLCIPHER_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
42996   return rc;
42997 }
42998
42999 /*
43000 ** Function assertTruncateConstraint(pPager) checks that one of the 
43001 ** following is true for all dirty pages currently in the page-cache:
43002 **
43003 **   a) The page number is less than or equal to the size of the 
43004 **      current database image, in pages, OR
43005 **
43006 **   b) if the page content were written at this time, it would not
43007 **      be necessary to write the current content out to the sub-journal
43008 **      (as determined by function subjRequiresPage()).
43009 **
43010 ** If the condition asserted by this function were not true, and the
43011 ** dirty page were to be discarded from the cache via the pagerStress()
43012 ** routine, pagerStress() would not write the current page content to
43013 ** the database file. If a savepoint transaction were rolled back after
43014 ** this happened, the correct behaviour would be to restore the current
43015 ** content of the page. However, since this content is not present in either
43016 ** the database file or the portion of the rollback journal and 
43017 ** sub-journal rolled back the content could not be restored and the
43018 ** database image would become corrupt. It is therefore fortunate that 
43019 ** this circumstance cannot arise.
43020 */
43021 #if defined(SQLCIPHER_DEBUG)
43022 static void assertTruncateConstraintCb(PgHdr *pPg){
43023   assert( pPg->flags&PGHDR_DIRTY );
43024   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
43025 }
43026 static void assertTruncateConstraint(Pager *pPager){
43027   sqlcipher3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
43028 }
43029 #else
43030 # define assertTruncateConstraint(pPager)
43031 #endif
43032
43033 /*
43034 ** Truncate the in-memory database file image to nPage pages. This 
43035 ** function does not actually modify the database file on disk. It 
43036 ** just sets the internal state of the pager object so that the 
43037 ** truncation will be done when the current transaction is committed.
43038 */
43039 SQLCIPHER_PRIVATE void sqlcipher3PagerTruncateImage(Pager *pPager, Pgno nPage){
43040   assert( pPager->dbSize>=nPage );
43041   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
43042   pPager->dbSize = nPage;
43043   assertTruncateConstraint(pPager);
43044 }
43045
43046
43047 /*
43048 ** This function is called before attempting a hot-journal rollback. It
43049 ** syncs the journal file to disk, then sets pPager->journalHdr to the
43050 ** size of the journal file so that the pager_playback() routine knows
43051 ** that the entire journal file has been synced.
43052 **
43053 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
43054 ** that if a power-failure occurs during the rollback, the process that
43055 ** attempts rollback following system recovery sees the same journal
43056 ** content as this process.
43057 **
43058 ** If everything goes as planned, SQLCIPHER_OK is returned. Otherwise, 
43059 ** an SQLite error code.
43060 */
43061 static int pagerSyncHotJournal(Pager *pPager){
43062   int rc = SQLCIPHER_OK;
43063   if( !pPager->noSync ){
43064     rc = sqlcipher3OsSync(pPager->jfd, SQLCIPHER_SYNC_NORMAL);
43065   }
43066   if( rc==SQLCIPHER_OK ){
43067     rc = sqlcipher3OsFileSize(pPager->jfd, &pPager->journalHdr);
43068   }
43069   return rc;
43070 }
43071
43072 /*
43073 ** Shutdown the page cache.  Free all memory and close all files.
43074 **
43075 ** If a transaction was in progress when this routine is called, that
43076 ** transaction is rolled back.  All outstanding pages are invalidated
43077 ** and their memory is freed.  Any attempt to use a page associated
43078 ** with this page cache after this function returns will likely
43079 ** result in a coredump.
43080 **
43081 ** This function always succeeds. If a transaction is active an attempt
43082 ** is made to roll it back. If an error occurs during the rollback 
43083 ** a hot journal may be left in the filesystem but no error is returned
43084 ** to the caller.
43085 */
43086 SQLCIPHER_PRIVATE int sqlcipher3PagerClose(Pager *pPager){
43087   u8 *pTmp = (u8 *)pPager->pTmpSpace;
43088
43089   assert( assert_pager_state(pPager) );
43090   disable_simulated_io_errors();
43091   sqlcipher3BeginBenignMalloc();
43092   /* pPager->errCode = 0; */
43093   pPager->exclusiveMode = 0;
43094 #ifndef SQLCIPHER_OMIT_WAL
43095   sqlcipher3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
43096   pPager->pWal = 0;
43097 #endif
43098   pager_reset(pPager);
43099   if( MEMDB ){
43100     pager_unlock(pPager);
43101   }else{
43102     /* If it is open, sync the journal file before calling UnlockAndRollback.
43103     ** If this is not done, then an unsynced portion of the open journal 
43104     ** file may be played back into the database. If a power failure occurs 
43105     ** while this is happening, the database could become corrupt.
43106     **
43107     ** If an error occurs while trying to sync the journal, shift the pager
43108     ** into the ERROR state. This causes UnlockAndRollback to unlock the
43109     ** database and close the journal file without attempting to roll it
43110     ** back or finalize it. The next database user will have to do hot-journal
43111     ** rollback before accessing the database file.
43112     */
43113     if( isOpen(pPager->jfd) ){
43114       pager_error(pPager, pagerSyncHotJournal(pPager));
43115     }
43116     pagerUnlockAndRollback(pPager);
43117   }
43118   sqlcipher3EndBenignMalloc();
43119   enable_simulated_io_errors();
43120   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
43121   IOTRACE(("CLOSE %p\n", pPager))
43122   sqlcipher3OsClose(pPager->jfd);
43123   sqlcipher3OsClose(pPager->fd);
43124   sqlcipher3PageFree(pTmp);
43125   sqlcipher3PcacheClose(pPager->pPCache);
43126
43127 #ifdef SQLCIPHER_HAS_CODEC
43128   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
43129 #endif
43130
43131   assert( !pPager->aSavepoint && !pPager->pInJournal );
43132   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
43133
43134   sqlcipher3_free(pPager);
43135   return SQLCIPHER_OK;
43136 }
43137
43138 #if !defined(NDEBUG) || defined(SQLCIPHER_TEST)
43139 /*
43140 ** Return the page number for page pPg.
43141 */
43142 SQLCIPHER_PRIVATE Pgno sqlcipher3PagerPagenumber(DbPage *pPg){
43143   return pPg->pgno;
43144 }
43145 #endif
43146
43147 /*
43148 ** Increment the reference count for page pPg.
43149 */
43150 SQLCIPHER_PRIVATE void sqlcipher3PagerRef(DbPage *pPg){
43151   sqlcipher3PcacheRef(pPg);
43152 }
43153
43154 /*
43155 ** Sync the journal. In other words, make sure all the pages that have
43156 ** been written to the journal have actually reached the surface of the
43157 ** disk and can be restored in the event of a hot-journal rollback.
43158 **
43159 ** If the Pager.noSync flag is set, then this function is a no-op.
43160 ** Otherwise, the actions required depend on the journal-mode and the 
43161 ** device characteristics of the the file-system, as follows:
43162 **
43163 **   * If the journal file is an in-memory journal file, no action need
43164 **     be taken.
43165 **
43166 **   * Otherwise, if the device does not support the SAFE_APPEND property,
43167 **     then the nRec field of the most recently written journal header
43168 **     is updated to contain the number of journal records that have
43169 **     been written following it. If the pager is operating in full-sync
43170 **     mode, then the journal file is synced before this field is updated.
43171 **
43172 **   * If the device does not support the SEQUENTIAL property, then 
43173 **     journal file is synced.
43174 **
43175 ** Or, in pseudo-code:
43176 **
43177 **   if( NOT <in-memory journal> ){
43178 **     if( NOT SAFE_APPEND ){
43179 **       if( <full-sync mode> ) xSync(<journal file>);
43180 **       <update nRec field>
43181 **     } 
43182 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
43183 **   }
43184 **
43185 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
43186 ** page currently held in memory before returning SQLCIPHER_OK. If an IO
43187 ** error is encountered, then the IO error code is returned to the caller.
43188 */
43189 static int syncJournal(Pager *pPager, int newHdr){
43190   int rc;                         /* Return code */
43191
43192   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43193        || pPager->eState==PAGER_WRITER_DBMOD
43194   );
43195   assert( assert_pager_state(pPager) );
43196   assert( !pagerUseWal(pPager) );
43197
43198   rc = sqlcipher3PagerExclusiveLock(pPager);
43199   if( rc!=SQLCIPHER_OK ) return rc;
43200
43201   if( !pPager->noSync ){
43202     assert( !pPager->tempFile );
43203     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
43204       const int iDc = sqlcipher3OsDeviceCharacteristics(pPager->fd);
43205       assert( isOpen(pPager->jfd) );
43206
43207       if( 0==(iDc&SQLCIPHER_IOCAP_SAFE_APPEND) ){
43208         /* This block deals with an obscure problem. If the last connection
43209         ** that wrote to this database was operating in persistent-journal
43210         ** mode, then the journal file may at this point actually be larger
43211         ** than Pager.journalOff bytes. If the next thing in the journal
43212         ** file happens to be a journal-header (written as part of the
43213         ** previous connection's transaction), and a crash or power-failure 
43214         ** occurs after nRec is updated but before this connection writes 
43215         ** anything else to the journal file (or commits/rolls back its 
43216         ** transaction), then SQLite may become confused when doing the 
43217         ** hot-journal rollback following recovery. It may roll back all
43218         ** of this connections data, then proceed to rolling back the old,
43219         ** out-of-date data that follows it. Database corruption.
43220         **
43221         ** To work around this, if the journal file does appear to contain
43222         ** a valid header following Pager.journalOff, then write a 0x00
43223         ** byte to the start of it to prevent it from being recognized.
43224         **
43225         ** Variable iNextHdrOffset is set to the offset at which this
43226         ** problematic header will occur, if it exists. aMagic is used 
43227         ** as a temporary buffer to inspect the first couple of bytes of
43228         ** the potential journal header.
43229         */
43230         i64 iNextHdrOffset;
43231         u8 aMagic[8];
43232         u8 zHeader[sizeof(aJournalMagic)+4];
43233
43234         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
43235         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
43236
43237         iNextHdrOffset = journalHdrOffset(pPager);
43238         rc = sqlcipher3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
43239         if( rc==SQLCIPHER_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
43240           static const u8 zerobyte = 0;
43241           rc = sqlcipher3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
43242         }
43243         if( rc!=SQLCIPHER_OK && rc!=SQLCIPHER_IOERR_SHORT_READ ){
43244           return rc;
43245         }
43246
43247         /* Write the nRec value into the journal file header. If in
43248         ** full-synchronous mode, sync the journal first. This ensures that
43249         ** all data has really hit the disk before nRec is updated to mark
43250         ** it as a candidate for rollback.
43251         **
43252         ** This is not required if the persistent media supports the
43253         ** SAFE_APPEND property. Because in this case it is not possible 
43254         ** for garbage data to be appended to the file, the nRec field
43255         ** is populated with 0xFFFFFFFF when the journal header is written
43256         ** and never needs to be updated.
43257         */
43258         if( pPager->fullSync && 0==(iDc&SQLCIPHER_IOCAP_SEQUENTIAL) ){
43259           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
43260           IOTRACE(("JSYNC %p\n", pPager))
43261           rc = sqlcipher3OsSync(pPager->jfd, pPager->syncFlags);
43262           if( rc!=SQLCIPHER_OK ) return rc;
43263         }
43264         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
43265         rc = sqlcipher3OsWrite(
43266             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
43267         );
43268         if( rc!=SQLCIPHER_OK ) return rc;
43269       }
43270       if( 0==(iDc&SQLCIPHER_IOCAP_SEQUENTIAL) ){
43271         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
43272         IOTRACE(("JSYNC %p\n", pPager))
43273         rc = sqlcipher3OsSync(pPager->jfd, pPager->syncFlags| 
43274           (pPager->syncFlags==SQLCIPHER_SYNC_FULL?SQLCIPHER_SYNC_DATAONLY:0)
43275         );
43276         if( rc!=SQLCIPHER_OK ) return rc;
43277       }
43278
43279       pPager->journalHdr = pPager->journalOff;
43280       if( newHdr && 0==(iDc&SQLCIPHER_IOCAP_SAFE_APPEND) ){
43281         pPager->nRec = 0;
43282         rc = writeJournalHdr(pPager);
43283         if( rc!=SQLCIPHER_OK ) return rc;
43284       }
43285     }else{
43286       pPager->journalHdr = pPager->journalOff;
43287     }
43288   }
43289
43290   /* Unless the pager is in noSync mode, the journal file was just 
43291   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
43292   ** all pages.
43293   */
43294   sqlcipher3PcacheClearSyncFlags(pPager->pPCache);
43295   pPager->eState = PAGER_WRITER_DBMOD;
43296   assert( assert_pager_state(pPager) );
43297   return SQLCIPHER_OK;
43298 }
43299
43300 /*
43301 ** The argument is the first in a linked list of dirty pages connected
43302 ** by the PgHdr.pDirty pointer. This function writes each one of the
43303 ** in-memory pages in the list to the database file. The argument may
43304 ** be NULL, representing an empty list. In this case this function is
43305 ** a no-op.
43306 **
43307 ** The pager must hold at least a RESERVED lock when this function
43308 ** is called. Before writing anything to the database file, this lock
43309 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
43310 ** SQLCIPHER_BUSY is returned and no data is written to the database file.
43311 ** 
43312 ** If the pager is a temp-file pager and the actual file-system file
43313 ** is not yet open, it is created and opened before any data is 
43314 ** written out.
43315 **
43316 ** Once the lock has been upgraded and, if necessary, the file opened,
43317 ** the pages are written out to the database file in list order. Writing
43318 ** a page is skipped if it meets either of the following criteria:
43319 **
43320 **   * The page number is greater than Pager.dbSize, or
43321 **   * The PGHDR_DONT_WRITE flag is set on the page.
43322 **
43323 ** If writing out a page causes the database file to grow, Pager.dbFileSize
43324 ** is updated accordingly. If page 1 is written out, then the value cached
43325 ** in Pager.dbFileVers[] is updated to match the new value stored in
43326 ** the database file.
43327 **
43328 ** If everything is successful, SQLCIPHER_OK is returned. If an IO error 
43329 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
43330 ** be obtained, SQLCIPHER_BUSY is returned.
43331 */
43332 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
43333   int rc = SQLCIPHER_OK;                  /* Return code */
43334
43335   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
43336   assert( !pagerUseWal(pPager) );
43337   assert( pPager->eState==PAGER_WRITER_DBMOD );
43338   assert( pPager->eLock==EXCLUSIVE_LOCK );
43339
43340   /* If the file is a temp-file has not yet been opened, open it now. It
43341   ** is not possible for rc to be other than SQLCIPHER_OK if this branch
43342   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
43343   */
43344   if( !isOpen(pPager->fd) ){
43345     assert( pPager->tempFile && rc==SQLCIPHER_OK );
43346     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
43347   }
43348
43349   /* Before the first write, give the VFS a hint of what the final
43350   ** file size will be.
43351   */
43352   assert( rc!=SQLCIPHER_OK || isOpen(pPager->fd) );
43353   if( rc==SQLCIPHER_OK && pPager->dbSize>pPager->dbHintSize ){
43354     sqlcipher3_int64 szFile = pPager->pageSize * (sqlcipher3_int64)pPager->dbSize;
43355     sqlcipher3OsFileControl(pPager->fd, SQLCIPHER_FCNTL_SIZE_HINT, &szFile);
43356     pPager->dbHintSize = pPager->dbSize;
43357   }
43358
43359   while( rc==SQLCIPHER_OK && pList ){
43360     Pgno pgno = pList->pgno;
43361
43362     /* If there are dirty pages in the page cache with page numbers greater
43363     ** than Pager.dbSize, this means sqlcipher3PagerTruncateImage() was called to
43364     ** make the file smaller (presumably by auto-vacuum code). Do not write
43365     ** any such pages to the file.
43366     **
43367     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
43368     ** set (set by sqlcipher3PagerDontWrite()).
43369     */
43370     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
43371       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
43372       char *pData;                                   /* Data to write */    
43373
43374       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
43375       if( pList->pgno==1 ) pager_write_changecounter(pList);
43376
43377       /* Encode the database */
43378       CODEC2(pPager, pList->pData, pgno, 6, return SQLCIPHER_NOMEM, pData);
43379
43380       /* Write out the page data. */
43381       rc = sqlcipher3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
43382
43383       /* If page 1 was just written, update Pager.dbFileVers to match
43384       ** the value now stored in the database file. If writing this 
43385       ** page caused the database file to grow, update dbFileSize. 
43386       */
43387       if( pgno==1 ){
43388         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
43389       }
43390       if( pgno>pPager->dbFileSize ){
43391         pPager->dbFileSize = pgno;
43392       }
43393
43394       /* Update any backup objects copying the contents of this pager. */
43395       sqlcipher3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
43396
43397       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
43398                    PAGERID(pPager), pgno, pager_pagehash(pList)));
43399       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
43400       PAGER_INCR(sqlcipher3_pager_writedb_count);
43401       PAGER_INCR(pPager->nWrite);
43402     }else{
43403       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
43404     }
43405     pager_set_pagehash(pList);
43406     pList = pList->pDirty;
43407   }
43408
43409   return rc;
43410 }
43411
43412 /*
43413 ** Ensure that the sub-journal file is open. If it is already open, this 
43414 ** function is a no-op.
43415 **
43416 ** SQLCIPHER_OK is returned if everything goes according to plan. An 
43417 ** SQLCIPHER_IOERR_XXX error code is returned if a call to sqlcipher3OsOpen() 
43418 ** fails.
43419 */
43420 static int openSubJournal(Pager *pPager){
43421   int rc = SQLCIPHER_OK;
43422   if( !isOpen(pPager->sjfd) ){
43423     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
43424       sqlcipher3MemJournalOpen(pPager->sjfd);
43425     }else{
43426       rc = pagerOpentemp(pPager, pPager->sjfd, SQLCIPHER_OPEN_SUBJOURNAL);
43427     }
43428   }
43429   return rc;
43430 }
43431
43432 /*
43433 ** Append a record of the current state of page pPg to the sub-journal. 
43434 ** It is the callers responsibility to use subjRequiresPage() to check 
43435 ** that it is really required before calling this function.
43436 **
43437 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
43438 ** for all open savepoints before returning.
43439 **
43440 ** This function returns SQLCIPHER_OK if everything is successful, an IO
43441 ** error code if the attempt to write to the sub-journal fails, or 
43442 ** SQLCIPHER_NOMEM if a malloc fails while setting a bit in a savepoint
43443 ** bitvec.
43444 */
43445 static int subjournalPage(PgHdr *pPg){
43446   int rc = SQLCIPHER_OK;
43447   Pager *pPager = pPg->pPager;
43448   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
43449
43450     /* Open the sub-journal, if it has not already been opened */
43451     assert( pPager->useJournal );
43452     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
43453     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
43454     assert( pagerUseWal(pPager) 
43455          || pageInJournal(pPg) 
43456          || pPg->pgno>pPager->dbOrigSize 
43457     );
43458     rc = openSubJournal(pPager);
43459
43460     /* If the sub-journal was opened successfully (or was already open),
43461     ** write the journal record into the file.  */
43462     if( rc==SQLCIPHER_OK ){
43463       void *pData = pPg->pData;
43464       i64 offset = pPager->nSubRec*(4+pPager->pageSize);
43465       char *pData2;
43466   
43467       CODEC2(pPager, pData, pPg->pgno, 7, return SQLCIPHER_NOMEM, pData2);
43468       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
43469       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
43470       if( rc==SQLCIPHER_OK ){
43471         rc = sqlcipher3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
43472       }
43473     }
43474   }
43475   if( rc==SQLCIPHER_OK ){
43476     pPager->nSubRec++;
43477     assert( pPager->nSavepoint>0 );
43478     rc = addToSavepointBitvecs(pPager, pPg->pgno);
43479   }
43480   return rc;
43481 }
43482
43483 /*
43484 ** This function is called by the pcache layer when it has reached some
43485 ** soft memory limit. The first argument is a pointer to a Pager object
43486 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
43487 ** database). The second argument is a reference to a page that is 
43488 ** currently dirty but has no outstanding references. The page
43489 ** is always associated with the Pager object passed as the first 
43490 ** argument.
43491 **
43492 ** The job of this function is to make pPg clean by writing its contents
43493 ** out to the database file, if possible. This may involve syncing the
43494 ** journal file. 
43495 **
43496 ** If successful, sqlcipher3PcacheMakeClean() is called on the page and
43497 ** SQLCIPHER_OK returned. If an IO error occurs while trying to make the
43498 ** page clean, the IO error code is returned. If the page cannot be
43499 ** made clean for some other reason, but no error occurs, then SQLCIPHER_OK
43500 ** is returned by sqlcipher3PcacheMakeClean() is not called.
43501 */
43502 static int pagerStress(void *p, PgHdr *pPg){
43503   Pager *pPager = (Pager *)p;
43504   int rc = SQLCIPHER_OK;
43505
43506   assert( pPg->pPager==pPager );
43507   assert( pPg->flags&PGHDR_DIRTY );
43508
43509   /* The doNotSyncSpill flag is set during times when doing a sync of
43510   ** journal (and adding a new header) is not allowed.  This occurs
43511   ** during calls to sqlcipher3PagerWrite() while trying to journal multiple
43512   ** pages belonging to the same sector.
43513   **
43514   ** The doNotSpill flag inhibits all cache spilling regardless of whether
43515   ** or not a sync is required.  This is set during a rollback.
43516   **
43517   ** Spilling is also prohibited when in an error state since that could
43518   ** lead to database corruption.   In the current implementaton it 
43519   ** is impossible for sqlcipher3PcacheFetch() to be called with createFlag==1
43520   ** while in the error state, hence it is impossible for this routine to
43521   ** be called in the error state.  Nevertheless, we include a NEVER()
43522   ** test for the error state as a safeguard against future changes.
43523   */
43524   if( NEVER(pPager->errCode) ) return SQLCIPHER_OK;
43525   if( pPager->doNotSpill ) return SQLCIPHER_OK;
43526   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
43527     return SQLCIPHER_OK;
43528   }
43529
43530   pPg->pDirty = 0;
43531   if( pagerUseWal(pPager) ){
43532     /* Write a single frame for this page to the log. */
43533     if( subjRequiresPage(pPg) ){ 
43534       rc = subjournalPage(pPg); 
43535     }
43536     if( rc==SQLCIPHER_OK ){
43537       rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
43538     }
43539   }else{
43540   
43541     /* Sync the journal file if required. */
43542     if( pPg->flags&PGHDR_NEED_SYNC 
43543      || pPager->eState==PAGER_WRITER_CACHEMOD
43544     ){
43545       rc = syncJournal(pPager, 1);
43546     }
43547   
43548     /* If the page number of this page is larger than the current size of
43549     ** the database image, it may need to be written to the sub-journal.
43550     ** This is because the call to pager_write_pagelist() below will not
43551     ** actually write data to the file in this case.
43552     **
43553     ** Consider the following sequence of events:
43554     **
43555     **   BEGIN;
43556     **     <journal page X>
43557     **     <modify page X>
43558     **     SAVEPOINT sp;
43559     **       <shrink database file to Y pages>
43560     **       pagerStress(page X)
43561     **     ROLLBACK TO sp;
43562     **
43563     ** If (X>Y), then when pagerStress is called page X will not be written
43564     ** out to the database file, but will be dropped from the cache. Then,
43565     ** following the "ROLLBACK TO sp" statement, reading page X will read
43566     ** data from the database file. This will be the copy of page X as it
43567     ** was when the transaction started, not as it was when "SAVEPOINT sp"
43568     ** was executed.
43569     **
43570     ** The solution is to write the current data for page X into the 
43571     ** sub-journal file now (if it is not already there), so that it will
43572     ** be restored to its current value when the "ROLLBACK TO sp" is 
43573     ** executed.
43574     */
43575     if( NEVER(
43576         rc==SQLCIPHER_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
43577     ) ){
43578       rc = subjournalPage(pPg);
43579     }
43580   
43581     /* Write the contents of the page out to the database file. */
43582     if( rc==SQLCIPHER_OK ){
43583       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
43584       rc = pager_write_pagelist(pPager, pPg);
43585     }
43586   }
43587
43588   /* Mark the page as clean. */
43589   if( rc==SQLCIPHER_OK ){
43590     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
43591     sqlcipher3PcacheMakeClean(pPg);
43592   }
43593
43594   return pager_error(pPager, rc); 
43595 }
43596
43597
43598 /*
43599 ** Allocate and initialize a new Pager object and put a pointer to it
43600 ** in *ppPager. The pager should eventually be freed by passing it
43601 ** to sqlcipher3PagerClose().
43602 **
43603 ** The zFilename argument is the path to the database file to open.
43604 ** If zFilename is NULL then a randomly-named temporary file is created
43605 ** and used as the file to be cached. Temporary files are be deleted
43606 ** automatically when they are closed. If zFilename is ":memory:" then 
43607 ** all information is held in cache. It is never written to disk. 
43608 ** This can be used to implement an in-memory database.
43609 **
43610 ** The nExtra parameter specifies the number of bytes of space allocated
43611 ** along with each page reference. This space is available to the user
43612 ** via the sqlcipher3PagerGetExtra() API.
43613 **
43614 ** The flags argument is used to specify properties that affect the
43615 ** operation of the pager. It should be passed some bitwise combination
43616 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
43617 **
43618 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
43619 ** of the xOpen() method of the supplied VFS when opening files. 
43620 **
43621 ** If the pager object is allocated and the specified file opened 
43622 ** successfully, SQLCIPHER_OK is returned and *ppPager set to point to
43623 ** the new pager object. If an error occurs, *ppPager is set to NULL
43624 ** and error code returned. This function may return SQLCIPHER_NOMEM
43625 ** (sqlcipher3Malloc() is used to allocate memory), SQLCIPHER_CANTOPEN or 
43626 ** various SQLCIPHER_IO_XXX errors.
43627 */
43628 SQLCIPHER_PRIVATE int sqlcipher3PagerOpen(
43629   sqlcipher3_vfs *pVfs,       /* The virtual file system to use */
43630   Pager **ppPager,         /* OUT: Return the Pager structure here */
43631   const char *zFilename,   /* Name of the database file to open */
43632   int nExtra,              /* Extra bytes append to each in-memory page */
43633   int flags,               /* flags controlling this file */
43634   int vfsFlags,            /* flags passed through to sqlcipher3_vfs.xOpen() */
43635   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
43636 ){
43637   u8 *pPtr;
43638   Pager *pPager = 0;       /* Pager object to allocate and return */
43639   int rc = SQLCIPHER_OK;      /* Return code */
43640   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
43641   int memDb = 0;           /* True if this is an in-memory file */
43642   int readOnly = 0;        /* True if this is a read-only file */
43643   int journalFileSize;     /* Bytes to allocate for each journal fd */
43644   char *zPathname = 0;     /* Full path to database file */
43645   int nPathname = 0;       /* Number of bytes in zPathname */
43646   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
43647   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
43648   int pcacheSize = sqlcipher3PcacheSize();       /* Bytes to allocate for PCache */
43649   u32 szPageDflt = SQLCIPHER_DEFAULT_PAGE_SIZE;  /* Default page size */
43650   const char *zUri = 0;    /* URI args to copy */
43651   int nUri = 0;            /* Number of bytes of URI args at *zUri */
43652
43653   /* Figure out how much space is required for each journal file-handle
43654   ** (there are two of them, the main journal and the sub-journal). This
43655   ** is the maximum space required for an in-memory journal file handle 
43656   ** and a regular journal file-handle. Note that a "regular journal-handle"
43657   ** may be a wrapper capable of caching the first portion of the journal
43658   ** file in memory to implement the atomic-write optimization (see 
43659   ** source file journal.c).
43660   */
43661   if( sqlcipher3JournalSize(pVfs)>sqlcipher3MemJournalSize() ){
43662     journalFileSize = ROUND8(sqlcipher3JournalSize(pVfs));
43663   }else{
43664     journalFileSize = ROUND8(sqlcipher3MemJournalSize());
43665   }
43666
43667   /* Set the output variable to NULL in case an error occurs. */
43668   *ppPager = 0;
43669
43670 #ifndef SQLCIPHER_OMIT_MEMORYDB
43671   if( flags & PAGER_MEMORY ){
43672     memDb = 1;
43673     zFilename = 0;
43674   }
43675 #endif
43676
43677   /* Compute and store the full pathname in an allocated buffer pointed
43678   ** to by zPathname, length nPathname. Or, if this is a temporary file,
43679   ** leave both nPathname and zPathname set to 0.
43680   */
43681   if( zFilename && zFilename[0] ){
43682     const char *z;
43683     nPathname = pVfs->mxPathname+1;
43684     zPathname = sqlcipher3Malloc(nPathname*2);
43685     if( zPathname==0 ){
43686       return SQLCIPHER_NOMEM;
43687     }
43688     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
43689     rc = sqlcipher3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
43690     nPathname = sqlcipher3Strlen30(zPathname);
43691     z = zUri = &zFilename[sqlcipher3Strlen30(zFilename)+1];
43692     while( *z ){
43693       z += sqlcipher3Strlen30(z)+1;
43694       z += sqlcipher3Strlen30(z)+1;
43695     }
43696     nUri = &z[1] - zUri;
43697     if( rc==SQLCIPHER_OK && nPathname+8>pVfs->mxPathname ){
43698       /* This branch is taken when the journal path required by
43699       ** the database being opened will be more than pVfs->mxPathname
43700       ** bytes in length. This means the database cannot be opened,
43701       ** as it will not be possible to open the journal file or even
43702       ** check for a hot-journal before reading.
43703       */
43704       rc = SQLCIPHER_CANTOPEN_BKPT;
43705     }
43706     if( rc!=SQLCIPHER_OK ){
43707       sqlcipher3_free(zPathname);
43708       return rc;
43709     }
43710   }
43711
43712   /* Allocate memory for the Pager structure, PCache object, the
43713   ** three file descriptors, the database file name and the journal 
43714   ** file name. The layout in memory is as follows:
43715   **
43716   **     Pager object                    (sizeof(Pager) bytes)
43717   **     PCache object                   (sqlcipher3PcacheSize() bytes)
43718   **     Database file handle            (pVfs->szOsFile bytes)
43719   **     Sub-journal file handle         (journalFileSize bytes)
43720   **     Main journal file handle        (journalFileSize bytes)
43721   **     Database file name              (nPathname+1 bytes)
43722   **     Journal file name               (nPathname+8+1 bytes)
43723   */
43724   pPtr = (u8 *)sqlcipher3MallocZero(
43725     ROUND8(sizeof(*pPager)) +      /* Pager structure */
43726     ROUND8(pcacheSize) +           /* PCache object */
43727     ROUND8(pVfs->szOsFile) +       /* The main db file */
43728     journalFileSize * 2 +          /* The two journal files */ 
43729     nPathname + 1 + nUri +         /* zFilename */
43730     nPathname + 8 + 1              /* zJournal */
43731 #ifndef SQLCIPHER_OMIT_WAL
43732     + nPathname + 4 + 1              /* zWal */
43733 #endif
43734   );
43735   assert( EIGHT_BYTE_ALIGNMENT(SQLCIPHER_INT_TO_PTR(journalFileSize)) );
43736   if( !pPtr ){
43737     sqlcipher3_free(zPathname);
43738     return SQLCIPHER_NOMEM;
43739   }
43740   pPager =              (Pager*)(pPtr);
43741   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
43742   pPager->fd =   (sqlcipher3_file*)(pPtr += ROUND8(pcacheSize));
43743   pPager->sjfd = (sqlcipher3_file*)(pPtr += ROUND8(pVfs->szOsFile));
43744   pPager->jfd =  (sqlcipher3_file*)(pPtr += journalFileSize);
43745   pPager->zFilename =    (char*)(pPtr += journalFileSize);
43746   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
43747
43748   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
43749   if( zPathname ){
43750     assert( nPathname>0 );
43751     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
43752     memcpy(pPager->zFilename, zPathname, nPathname);
43753     memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
43754     memcpy(pPager->zJournal, zPathname, nPathname);
43755     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
43756     sqlcipher3FileSuffix3(pPager->zFilename, pPager->zJournal);
43757 #ifndef SQLCIPHER_OMIT_WAL
43758     pPager->zWal = &pPager->zJournal[nPathname+8+1];
43759     memcpy(pPager->zWal, zPathname, nPathname);
43760     memcpy(&pPager->zWal[nPathname], "-wal", 4);
43761     sqlcipher3FileSuffix3(pPager->zFilename, pPager->zWal);
43762 #endif
43763     sqlcipher3_free(zPathname);
43764   }
43765   pPager->pVfs = pVfs;
43766   pPager->vfsFlags = vfsFlags;
43767
43768   /* Open the pager file.
43769   */
43770   if( zFilename && zFilename[0] ){
43771     int fout = 0;                    /* VFS flags returned by xOpen() */
43772     rc = sqlcipher3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
43773     assert( !memDb );
43774     readOnly = (fout&SQLCIPHER_OPEN_READONLY);
43775
43776     /* If the file was successfully opened for read/write access,
43777     ** choose a default page size in case we have to create the
43778     ** database file. The default page size is the maximum of:
43779     **
43780     **    + SQLCIPHER_DEFAULT_PAGE_SIZE,
43781     **    + The value returned by sqlcipher3OsSectorSize()
43782     **    + The largest page size that can be written atomically.
43783     */
43784     if( rc==SQLCIPHER_OK && !readOnly ){
43785       setSectorSize(pPager);
43786       assert(SQLCIPHER_DEFAULT_PAGE_SIZE<=SQLCIPHER_MAX_DEFAULT_PAGE_SIZE);
43787       if( szPageDflt<pPager->sectorSize ){
43788         if( pPager->sectorSize>SQLCIPHER_MAX_DEFAULT_PAGE_SIZE ){
43789           szPageDflt = SQLCIPHER_MAX_DEFAULT_PAGE_SIZE;
43790         }else{
43791           szPageDflt = (u32)pPager->sectorSize;
43792         }
43793       }
43794 #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
43795       {
43796         int iDc = sqlcipher3OsDeviceCharacteristics(pPager->fd);
43797         int ii;
43798         assert(SQLCIPHER_IOCAP_ATOMIC512==(512>>8));
43799         assert(SQLCIPHER_IOCAP_ATOMIC64K==(65536>>8));
43800         assert(SQLCIPHER_MAX_DEFAULT_PAGE_SIZE<=65536);
43801         for(ii=szPageDflt; ii<=SQLCIPHER_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
43802           if( iDc&(SQLCIPHER_IOCAP_ATOMIC|(ii>>8)) ){
43803             szPageDflt = ii;
43804           }
43805         }
43806       }
43807 #endif
43808     }
43809   }else{
43810     /* If a temporary file is requested, it is not opened immediately.
43811     ** In this case we accept the default page size and delay actually
43812     ** opening the file until the first call to OsWrite().
43813     **
43814     ** This branch is also run for an in-memory database. An in-memory
43815     ** database is the same as a temp-file that is never written out to
43816     ** disk and uses an in-memory rollback journal.
43817     */ 
43818     tempFile = 1;
43819     pPager->eState = PAGER_READER;
43820     pPager->eLock = EXCLUSIVE_LOCK;
43821     readOnly = (vfsFlags&SQLCIPHER_OPEN_READONLY);
43822   }
43823
43824   /* The following call to PagerSetPagesize() serves to set the value of 
43825   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
43826   */
43827   if( rc==SQLCIPHER_OK ){
43828     assert( pPager->memDb==0 );
43829     rc = sqlcipher3PagerSetPagesize(pPager, &szPageDflt, -1);
43830     testcase( rc!=SQLCIPHER_OK );
43831   }
43832
43833   /* If an error occurred in either of the blocks above, free the 
43834   ** Pager structure and close the file.
43835   */
43836   if( rc!=SQLCIPHER_OK ){
43837     assert( !pPager->pTmpSpace );
43838     sqlcipher3OsClose(pPager->fd);
43839     sqlcipher3_free(pPager);
43840     return rc;
43841   }
43842
43843   /* Initialize the PCache object. */
43844   assert( nExtra<1000 );
43845   nExtra = ROUND8(nExtra);
43846   sqlcipher3PcacheOpen(szPageDflt, nExtra, !memDb,
43847                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
43848
43849   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
43850   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
43851
43852   pPager->useJournal = (u8)useJournal;
43853   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
43854   /* pPager->stmtOpen = 0; */
43855   /* pPager->stmtInUse = 0; */
43856   /* pPager->nRef = 0; */
43857   /* pPager->stmtSize = 0; */
43858   /* pPager->stmtJSize = 0; */
43859   /* pPager->nPage = 0; */
43860   pPager->mxPgno = SQLCIPHER_MAX_PAGE_COUNT;
43861   /* pPager->state = PAGER_UNLOCK; */
43862 #if 0
43863   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
43864 #endif
43865   /* pPager->errMask = 0; */
43866   pPager->tempFile = (u8)tempFile;
43867   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
43868           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
43869   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
43870   pPager->exclusiveMode = (u8)tempFile; 
43871   pPager->changeCountDone = pPager->tempFile;
43872   pPager->memDb = (u8)memDb;
43873   pPager->readOnly = (u8)readOnly;
43874   assert( useJournal || pPager->tempFile );
43875   pPager->noSync = pPager->tempFile;
43876   pPager->fullSync = pPager->noSync ?0:1;
43877   pPager->syncFlags = pPager->noSync ? 0 : SQLCIPHER_SYNC_NORMAL;
43878   pPager->ckptSyncFlags = pPager->syncFlags;
43879   /* pPager->pFirst = 0; */
43880   /* pPager->pFirstSynced = 0; */
43881   /* pPager->pLast = 0; */
43882   pPager->nExtra = (u16)nExtra;
43883   pPager->journalSizeLimit = SQLCIPHER_DEFAULT_JOURNAL_SIZE_LIMIT;
43884   assert( isOpen(pPager->fd) || tempFile );
43885   setSectorSize(pPager);
43886   if( !useJournal ){
43887     pPager->journalMode = PAGER_JOURNALMODE_OFF;
43888   }else if( memDb ){
43889     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
43890   }
43891   /* pPager->xBusyHandler = 0; */
43892   /* pPager->pBusyHandlerArg = 0; */
43893   pPager->xReiniter = xReinit;
43894   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
43895
43896   *ppPager = pPager;
43897   return SQLCIPHER_OK;
43898 }
43899
43900
43901
43902 /*
43903 ** This function is called after transitioning from PAGER_UNLOCK to
43904 ** PAGER_SHARED state. It tests if there is a hot journal present in
43905 ** the file-system for the given pager. A hot journal is one that 
43906 ** needs to be played back. According to this function, a hot-journal
43907 ** file exists if the following criteria are met:
43908 **
43909 **   * The journal file exists in the file system, and
43910 **   * No process holds a RESERVED or greater lock on the database file, and
43911 **   * The database file itself is greater than 0 bytes in size, and
43912 **   * The first byte of the journal file exists and is not 0x00.
43913 **
43914 ** If the current size of the database file is 0 but a journal file
43915 ** exists, that is probably an old journal left over from a prior
43916 ** database with the same name. In this case the journal file is
43917 ** just deleted using OsDelete, *pExists is set to 0 and SQLCIPHER_OK
43918 ** is returned.
43919 **
43920 ** This routine does not check if there is a master journal filename
43921 ** at the end of the file. If there is, and that master journal file
43922 ** does not exist, then the journal file is not really hot. In this
43923 ** case this routine will return a false-positive. The pager_playback()
43924 ** routine will discover that the journal file is not really hot and 
43925 ** will not roll it back. 
43926 **
43927 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
43928 ** SQLCIPHER_OK returned. If no hot-journal file is present, *pExists is
43929 ** set to 0 and SQLCIPHER_OK returned. If an IO error occurs while trying
43930 ** to determine whether or not a hot-journal file exists, the IO error
43931 ** code is returned and the value of *pExists is undefined.
43932 */
43933 static int hasHotJournal(Pager *pPager, int *pExists){
43934   sqlcipher3_vfs * const pVfs = pPager->pVfs;
43935   int rc = SQLCIPHER_OK;           /* Return code */
43936   int exists = 1;               /* True if a journal file is present */
43937   int jrnlOpen = !!isOpen(pPager->jfd);
43938
43939   assert( pPager->useJournal );
43940   assert( isOpen(pPager->fd) );
43941   assert( pPager->eState==PAGER_OPEN );
43942
43943   assert( jrnlOpen==0 || ( sqlcipher3OsDeviceCharacteristics(pPager->jfd) &
43944     SQLCIPHER_IOCAP_UNDELETABLE_WHEN_OPEN
43945   ));
43946
43947   *pExists = 0;
43948   if( !jrnlOpen ){
43949     rc = sqlcipher3OsAccess(pVfs, pPager->zJournal, SQLCIPHER_ACCESS_EXISTS, &exists);
43950   }
43951   if( rc==SQLCIPHER_OK && exists ){
43952     int locked = 0;             /* True if some process holds a RESERVED lock */
43953
43954     /* Race condition here:  Another process might have been holding the
43955     ** the RESERVED lock and have a journal open at the sqlcipher3OsAccess() 
43956     ** call above, but then delete the journal and drop the lock before
43957     ** we get to the following sqlcipher3OsCheckReservedLock() call.  If that
43958     ** is the case, this routine might think there is a hot journal when
43959     ** in fact there is none.  This results in a false-positive which will
43960     ** be dealt with by the playback routine.  Ticket #3883.
43961     */
43962     rc = sqlcipher3OsCheckReservedLock(pPager->fd, &locked);
43963     if( rc==SQLCIPHER_OK && !locked ){
43964       Pgno nPage;                 /* Number of pages in database file */
43965
43966       /* Check the size of the database file. If it consists of 0 pages,
43967       ** then delete the journal file. See the header comment above for 
43968       ** the reasoning here.  Delete the obsolete journal file under
43969       ** a RESERVED lock to avoid race conditions and to avoid violating
43970       ** [H33020].
43971       */
43972       rc = pagerPagecount(pPager, &nPage);
43973       if( rc==SQLCIPHER_OK ){
43974         if( nPage==0 ){
43975           sqlcipher3BeginBenignMalloc();
43976           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLCIPHER_OK ){
43977             sqlcipher3OsDelete(pVfs, pPager->zJournal, 0);
43978             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
43979           }
43980           sqlcipher3EndBenignMalloc();
43981         }else{
43982           /* The journal file exists and no other connection has a reserved
43983           ** or greater lock on the database file. Now check that there is
43984           ** at least one non-zero bytes at the start of the journal file.
43985           ** If there is, then we consider this journal to be hot. If not, 
43986           ** it can be ignored.
43987           */
43988           if( !jrnlOpen ){
43989             int f = SQLCIPHER_OPEN_READONLY|SQLCIPHER_OPEN_MAIN_JOURNAL;
43990             rc = sqlcipher3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
43991           }
43992           if( rc==SQLCIPHER_OK ){
43993             u8 first = 0;
43994             rc = sqlcipher3OsRead(pPager->jfd, (void *)&first, 1, 0);
43995             if( rc==SQLCIPHER_IOERR_SHORT_READ ){
43996               rc = SQLCIPHER_OK;
43997             }
43998             if( !jrnlOpen ){
43999               sqlcipher3OsClose(pPager->jfd);
44000             }
44001             *pExists = (first!=0);
44002           }else if( rc==SQLCIPHER_CANTOPEN ){
44003             /* If we cannot open the rollback journal file in order to see if
44004             ** its has a zero header, that might be due to an I/O error, or
44005             ** it might be due to the race condition described above and in
44006             ** ticket #3883.  Either way, assume that the journal is hot.
44007             ** This might be a false positive.  But if it is, then the
44008             ** automatic journal playback and recovery mechanism will deal
44009             ** with it under an EXCLUSIVE lock where we do not need to
44010             ** worry so much with race conditions.
44011             */
44012             *pExists = 1;
44013             rc = SQLCIPHER_OK;
44014           }
44015         }
44016       }
44017     }
44018   }
44019
44020   return rc;
44021 }
44022
44023 /*
44024 ** This function is called to obtain a shared lock on the database file.
44025 ** It is illegal to call sqlcipher3PagerAcquire() until after this function
44026 ** has been successfully called. If a shared-lock is already held when
44027 ** this function is called, it is a no-op.
44028 **
44029 ** The following operations are also performed by this function.
44030 **
44031 **   1) If the pager is currently in PAGER_OPEN state (no lock held
44032 **      on the database file), then an attempt is made to obtain a
44033 **      SHARED lock on the database file. Immediately after obtaining
44034 **      the SHARED lock, the file-system is checked for a hot-journal,
44035 **      which is played back if present. Following any hot-journal 
44036 **      rollback, the contents of the cache are validated by checking
44037 **      the 'change-counter' field of the database file header and
44038 **      discarded if they are found to be invalid.
44039 **
44040 **   2) If the pager is running in exclusive-mode, and there are currently
44041 **      no outstanding references to any pages, and is in the error state,
44042 **      then an attempt is made to clear the error state by discarding
44043 **      the contents of the page cache and rolling back any open journal
44044 **      file.
44045 **
44046 ** If everything is successful, SQLCIPHER_OK is returned. If an IO error 
44047 ** occurs while locking the database, checking for a hot-journal file or 
44048 ** rolling back a journal file, the IO error code is returned.
44049 */
44050 SQLCIPHER_PRIVATE int sqlcipher3PagerSharedLock(Pager *pPager){
44051   int rc = SQLCIPHER_OK;                /* Return code */
44052
44053   /* This routine is only called from b-tree and only when there are no
44054   ** outstanding pages. This implies that the pager state should either
44055   ** be OPEN or READER. READER is only possible if the pager is or was in 
44056   ** exclusive access mode.
44057   */
44058   assert( sqlcipher3PcacheRefCount(pPager->pPCache)==0 );
44059   assert( assert_pager_state(pPager) );
44060   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
44061   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
44062
44063   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
44064     int bHotJournal = 1;          /* True if there exists a hot journal-file */
44065
44066     assert( !MEMDB );
44067     assert( pPager->noReadlock==0 || pPager->readOnly );
44068
44069     if( pPager->noReadlock==0 ){
44070       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
44071       if( rc!=SQLCIPHER_OK ){
44072         assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
44073         goto failed;
44074       }
44075     }
44076
44077     /* If a journal file exists, and there is no RESERVED lock on the
44078     ** database file, then it either needs to be played back or deleted.
44079     */
44080     if( pPager->eLock<=SHARED_LOCK ){
44081       rc = hasHotJournal(pPager, &bHotJournal);
44082     }
44083     if( rc!=SQLCIPHER_OK ){
44084       goto failed;
44085     }
44086     if( bHotJournal ){
44087       /* Get an EXCLUSIVE lock on the database file. At this point it is
44088       ** important that a RESERVED lock is not obtained on the way to the
44089       ** EXCLUSIVE lock. If it were, another process might open the
44090       ** database file, detect the RESERVED lock, and conclude that the
44091       ** database is safe to read while this process is still rolling the 
44092       ** hot-journal back.
44093       ** 
44094       ** Because the intermediate RESERVED lock is not requested, any
44095       ** other process attempting to access the database file will get to 
44096       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
44097       ** on the database file.
44098       **
44099       ** Unless the pager is in locking_mode=exclusive mode, the lock is
44100       ** downgraded to SHARED_LOCK before this function returns.
44101       */
44102       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44103       if( rc!=SQLCIPHER_OK ){
44104         goto failed;
44105       }
44106  
44107       /* If it is not already open and the file exists on disk, open the 
44108       ** journal for read/write access. Write access is required because 
44109       ** in exclusive-access mode the file descriptor will be kept open 
44110       ** and possibly used for a transaction later on. Also, write-access 
44111       ** is usually required to finalize the journal in journal_mode=persist 
44112       ** mode (and also for journal_mode=truncate on some systems).
44113       **
44114       ** If the journal does not exist, it usually means that some 
44115       ** other connection managed to get in and roll it back before 
44116       ** this connection obtained the exclusive lock above. Or, it 
44117       ** may mean that the pager was in the error-state when this
44118       ** function was called and the journal file does not exist.
44119       */
44120       if( !isOpen(pPager->jfd) ){
44121         sqlcipher3_vfs * const pVfs = pPager->pVfs;
44122         int bExists;              /* True if journal file exists */
44123         rc = sqlcipher3OsAccess(
44124             pVfs, pPager->zJournal, SQLCIPHER_ACCESS_EXISTS, &bExists);
44125         if( rc==SQLCIPHER_OK && bExists ){
44126           int fout = 0;
44127           int f = SQLCIPHER_OPEN_READWRITE|SQLCIPHER_OPEN_MAIN_JOURNAL;
44128           assert( !pPager->tempFile );
44129           rc = sqlcipher3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
44130           assert( rc!=SQLCIPHER_OK || isOpen(pPager->jfd) );
44131           if( rc==SQLCIPHER_OK && fout&SQLCIPHER_OPEN_READONLY ){
44132             rc = SQLCIPHER_CANTOPEN_BKPT;
44133             sqlcipher3OsClose(pPager->jfd);
44134           }
44135         }
44136       }
44137  
44138       /* Playback and delete the journal.  Drop the database write
44139       ** lock and reacquire the read lock. Purge the cache before
44140       ** playing back the hot-journal so that we don't end up with
44141       ** an inconsistent cache.  Sync the hot journal before playing
44142       ** it back since the process that crashed and left the hot journal
44143       ** probably did not sync it and we are required to always sync
44144       ** the journal before playing it back.
44145       */
44146       if( isOpen(pPager->jfd) ){
44147         assert( rc==SQLCIPHER_OK );
44148         rc = pagerSyncHotJournal(pPager);
44149         if( rc==SQLCIPHER_OK ){
44150           rc = pager_playback(pPager, 1);
44151           pPager->eState = PAGER_OPEN;
44152         }
44153       }else if( !pPager->exclusiveMode ){
44154         pagerUnlockDb(pPager, SHARED_LOCK);
44155       }
44156
44157       if( rc!=SQLCIPHER_OK ){
44158         /* This branch is taken if an error occurs while trying to open
44159         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
44160         ** pager_unlock() routine will be called before returning to unlock
44161         ** the file. If the unlock attempt fails, then Pager.eLock must be
44162         ** set to UNKNOWN_LOCK (see the comment above the #define for 
44163         ** UNKNOWN_LOCK above for an explanation). 
44164         **
44165         ** In order to get pager_unlock() to do this, set Pager.eState to
44166         ** PAGER_ERROR now. This is not actually counted as a transition
44167         ** to ERROR state in the state diagram at the top of this file,
44168         ** since we know that the same call to pager_unlock() will very
44169         ** shortly transition the pager object to the OPEN state. Calling
44170         ** assert_pager_state() would fail now, as it should not be possible
44171         ** to be in ERROR state when there are zero outstanding page 
44172         ** references.
44173         */
44174         pager_error(pPager, rc);
44175         goto failed;
44176       }
44177
44178       assert( pPager->eState==PAGER_OPEN );
44179       assert( (pPager->eLock==SHARED_LOCK)
44180            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
44181       );
44182     }
44183
44184     if( !pPager->tempFile 
44185      && (pPager->pBackup || sqlcipher3PcachePagecount(pPager->pPCache)>0) 
44186     ){
44187       /* The shared-lock has just been acquired on the database file
44188       ** and there are already pages in the cache (from a previous
44189       ** read or write transaction).  Check to see if the database
44190       ** has been modified.  If the database has changed, flush the
44191       ** cache.
44192       **
44193       ** Database changes is detected by looking at 15 bytes beginning
44194       ** at offset 24 into the file.  The first 4 of these 16 bytes are
44195       ** a 32-bit counter that is incremented with each change.  The
44196       ** other bytes change randomly with each file change when
44197       ** a codec is in use.
44198       ** 
44199       ** There is a vanishingly small chance that a change will not be 
44200       ** detected.  The chance of an undetected change is so small that
44201       ** it can be neglected.
44202       */
44203       Pgno nPage = 0;
44204       char dbFileVers[sizeof(pPager->dbFileVers)];
44205
44206       rc = pagerPagecount(pPager, &nPage);
44207       if( rc ) goto failed;
44208
44209       if( nPage>0 ){
44210         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
44211         rc = sqlcipher3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
44212         if( rc!=SQLCIPHER_OK ){
44213           goto failed;
44214         }
44215       }else{
44216         memset(dbFileVers, 0, sizeof(dbFileVers));
44217       }
44218
44219       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
44220         pager_reset(pPager);
44221       }
44222     }
44223
44224     /* If there is a WAL file in the file-system, open this database in WAL
44225     ** mode. Otherwise, the following function call is a no-op.
44226     */
44227     rc = pagerOpenWalIfPresent(pPager);
44228 #ifndef SQLCIPHER_OMIT_WAL
44229     assert( pPager->pWal==0 || rc==SQLCIPHER_OK );
44230 #endif
44231   }
44232
44233   if( pagerUseWal(pPager) ){
44234     assert( rc==SQLCIPHER_OK );
44235     rc = pagerBeginReadTransaction(pPager);
44236   }
44237
44238   if( pPager->eState==PAGER_OPEN && rc==SQLCIPHER_OK ){
44239     rc = pagerPagecount(pPager, &pPager->dbSize);
44240   }
44241
44242  failed:
44243   if( rc!=SQLCIPHER_OK ){
44244     assert( !MEMDB );
44245     pager_unlock(pPager);
44246     assert( pPager->eState==PAGER_OPEN );
44247   }else{
44248     pPager->eState = PAGER_READER;
44249   }
44250   return rc;
44251 }
44252
44253 /*
44254 ** If the reference count has reached zero, rollback any active
44255 ** transaction and unlock the pager.
44256 **
44257 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
44258 ** the rollback journal, the unlock is not performed and there is
44259 ** nothing to rollback, so this routine is a no-op.
44260 */ 
44261 static void pagerUnlockIfUnused(Pager *pPager){
44262   if( (sqlcipher3PcacheRefCount(pPager->pPCache)==0) ){
44263     pagerUnlockAndRollback(pPager);
44264   }
44265 }
44266
44267 /*
44268 ** Acquire a reference to page number pgno in pager pPager (a page
44269 ** reference has type DbPage*). If the requested reference is 
44270 ** successfully obtained, it is copied to *ppPage and SQLCIPHER_OK returned.
44271 **
44272 ** If the requested page is already in the cache, it is returned. 
44273 ** Otherwise, a new page object is allocated and populated with data
44274 ** read from the database file. In some cases, the pcache module may
44275 ** choose not to allocate a new page object and may reuse an existing
44276 ** object with no outstanding references.
44277 **
44278 ** The extra data appended to a page is always initialized to zeros the 
44279 ** first time a page is loaded into memory. If the page requested is 
44280 ** already in the cache when this function is called, then the extra
44281 ** data is left as it was when the page object was last used.
44282 **
44283 ** If the database image is smaller than the requested page or if a 
44284 ** non-zero value is passed as the noContent parameter and the 
44285 ** requested page is not already stored in the cache, then no 
44286 ** actual disk read occurs. In this case the memory image of the 
44287 ** page is initialized to all zeros. 
44288 **
44289 ** If noContent is true, it means that we do not care about the contents
44290 ** of the page. This occurs in two seperate scenarios:
44291 **
44292 **   a) When reading a free-list leaf page from the database, and
44293 **
44294 **   b) When a savepoint is being rolled back and we need to load
44295 **      a new page into the cache to be filled with the data read
44296 **      from the savepoint journal.
44297 **
44298 ** If noContent is true, then the data returned is zeroed instead of
44299 ** being read from the database. Additionally, the bits corresponding
44300 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
44301 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
44302 ** savepoints are set. This means if the page is made writable at any
44303 ** point in the future, using a call to sqlcipher3PagerWrite(), its contents
44304 ** will not be journaled. This saves IO.
44305 **
44306 ** The acquisition might fail for several reasons.  In all cases,
44307 ** an appropriate error code is returned and *ppPage is set to NULL.
44308 **
44309 ** See also sqlcipher3PagerLookup().  Both this routine and Lookup() attempt
44310 ** to find a page in the in-memory cache first.  If the page is not already
44311 ** in memory, this routine goes to disk to read it in whereas Lookup()
44312 ** just returns 0.  This routine acquires a read-lock the first time it
44313 ** has to go to disk, and could also playback an old journal if necessary.
44314 ** Since Lookup() never goes to disk, it never has to deal with locks
44315 ** or journal files.
44316 */
44317 SQLCIPHER_PRIVATE int sqlcipher3PagerAcquire(
44318   Pager *pPager,      /* The pager open on the database file */
44319   Pgno pgno,          /* Page number to fetch */
44320   DbPage **ppPage,    /* Write a pointer to the page here */
44321   int noContent       /* Do not bother reading content from disk if true */
44322 ){
44323   int rc;
44324   PgHdr *pPg;
44325
44326   assert( pPager->eState>=PAGER_READER );
44327   assert( assert_pager_state(pPager) );
44328
44329   if( pgno==0 ){
44330     return SQLCIPHER_CORRUPT_BKPT;
44331   }
44332
44333   /* If the pager is in the error state, return an error immediately. 
44334   ** Otherwise, request the page from the PCache layer. */
44335   if( pPager->errCode!=SQLCIPHER_OK ){
44336     rc = pPager->errCode;
44337   }else{
44338     rc = sqlcipher3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
44339   }
44340
44341   if( rc!=SQLCIPHER_OK ){
44342     /* Either the call to sqlcipher3PcacheFetch() returned an error or the
44343     ** pager was already in the error-state when this function was called.
44344     ** Set pPg to 0 and jump to the exception handler.  */
44345     pPg = 0;
44346     goto pager_acquire_err;
44347   }
44348   assert( (*ppPage)->pgno==pgno );
44349   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
44350
44351   if( (*ppPage)->pPager && !noContent ){
44352     /* In this case the pcache already contains an initialized copy of
44353     ** the page. Return without further ado.  */
44354     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
44355     pPager->nHit++;
44356     return SQLCIPHER_OK;
44357
44358   }else{
44359     /* The pager cache has created a new page. Its content needs to 
44360     ** be initialized.  */
44361
44362     pPg = *ppPage;
44363     pPg->pPager = pPager;
44364
44365     /* The maximum page number is 2^31. Return SQLCIPHER_CORRUPT if a page
44366     ** number greater than this, or the unused locking-page, is requested. */
44367     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
44368       rc = SQLCIPHER_CORRUPT_BKPT;
44369       goto pager_acquire_err;
44370     }
44371
44372     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
44373       if( pgno>pPager->mxPgno ){
44374         rc = SQLCIPHER_FULL;
44375         goto pager_acquire_err;
44376       }
44377       if( noContent ){
44378         /* Failure to set the bits in the InJournal bit-vectors is benign.
44379         ** It merely means that we might do some extra work to journal a 
44380         ** page that does not need to be journaled.  Nevertheless, be sure 
44381         ** to test the case where a malloc error occurs while trying to set 
44382         ** a bit in a bit vector.
44383         */
44384         sqlcipher3BeginBenignMalloc();
44385         if( pgno<=pPager->dbOrigSize ){
44386           TESTONLY( rc = ) sqlcipher3BitvecSet(pPager->pInJournal, pgno);
44387           testcase( rc==SQLCIPHER_NOMEM );
44388         }
44389         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
44390         testcase( rc==SQLCIPHER_NOMEM );
44391         sqlcipher3EndBenignMalloc();
44392       }
44393       memset(pPg->pData, 0, pPager->pageSize);
44394       IOTRACE(("ZERO %p %d\n", pPager, pgno));
44395     }else{
44396       assert( pPg->pPager==pPager );
44397       pPager->nMiss++;
44398       rc = readDbPage(pPg);
44399       if( rc!=SQLCIPHER_OK ){
44400         goto pager_acquire_err;
44401       }
44402     }
44403     pager_set_pagehash(pPg);
44404   }
44405
44406   return SQLCIPHER_OK;
44407
44408 pager_acquire_err:
44409   assert( rc!=SQLCIPHER_OK );
44410   if( pPg ){
44411     sqlcipher3PcacheDrop(pPg);
44412   }
44413   pagerUnlockIfUnused(pPager);
44414
44415   *ppPage = 0;
44416   return rc;
44417 }
44418
44419 /*
44420 ** Acquire a page if it is already in the in-memory cache.  Do
44421 ** not read the page from disk.  Return a pointer to the page,
44422 ** or 0 if the page is not in cache. 
44423 **
44424 ** See also sqlcipher3PagerGet().  The difference between this routine
44425 ** and sqlcipher3PagerGet() is that _get() will go to the disk and read
44426 ** in the page if the page is not already in cache.  This routine
44427 ** returns NULL if the page is not in cache or if a disk I/O error 
44428 ** has ever happened.
44429 */
44430 SQLCIPHER_PRIVATE DbPage *sqlcipher3PagerLookup(Pager *pPager, Pgno pgno){
44431   PgHdr *pPg = 0;
44432   assert( pPager!=0 );
44433   assert( pgno!=0 );
44434   assert( pPager->pPCache!=0 );
44435   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
44436   sqlcipher3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
44437   return pPg;
44438 }
44439
44440 /*
44441 ** Release a page reference.
44442 **
44443 ** If the number of references to the page drop to zero, then the
44444 ** page is added to the LRU list.  When all references to all pages
44445 ** are released, a rollback occurs and the lock on the database is
44446 ** removed.
44447 */
44448 SQLCIPHER_PRIVATE void sqlcipher3PagerUnref(DbPage *pPg){
44449   if( pPg ){
44450     Pager *pPager = pPg->pPager;
44451     sqlcipher3PcacheRelease(pPg);
44452     pagerUnlockIfUnused(pPager);
44453   }
44454 }
44455
44456 /*
44457 ** This function is called at the start of every write transaction.
44458 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
44459 ** file when this routine is called.
44460 **
44461 ** Open the journal file for pager pPager and write a journal header
44462 ** to the start of it. If there are active savepoints, open the sub-journal
44463 ** as well. This function is only used when the journal file is being 
44464 ** opened to write a rollback log for a transaction. It is not used 
44465 ** when opening a hot journal file to roll it back.
44466 **
44467 ** If the journal file is already open (as it may be in exclusive mode),
44468 ** then this function just writes a journal header to the start of the
44469 ** already open file. 
44470 **
44471 ** Whether or not the journal file is opened by this function, the
44472 ** Pager.pInJournal bitvec structure is allocated.
44473 **
44474 ** Return SQLCIPHER_OK if everything is successful. Otherwise, return 
44475 ** SQLCIPHER_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
44476 ** an IO error code if opening or writing the journal file fails.
44477 */
44478 static int pager_open_journal(Pager *pPager){
44479   int rc = SQLCIPHER_OK;                        /* Return code */
44480   sqlcipher3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
44481
44482   assert( pPager->eState==PAGER_WRITER_LOCKED );
44483   assert( assert_pager_state(pPager) );
44484   assert( pPager->pInJournal==0 );
44485   
44486   /* If already in the error state, this function is a no-op.  But on
44487   ** the other hand, this routine is never called if we are already in
44488   ** an error state. */
44489   if( NEVER(pPager->errCode) ) return pPager->errCode;
44490
44491   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
44492     pPager->pInJournal = sqlcipher3BitvecCreate(pPager->dbSize);
44493     if( pPager->pInJournal==0 ){
44494       return SQLCIPHER_NOMEM;
44495     }
44496   
44497     /* Open the journal file if it is not already open. */
44498     if( !isOpen(pPager->jfd) ){
44499       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
44500         sqlcipher3MemJournalOpen(pPager->jfd);
44501       }else{
44502         const int flags =                   /* VFS flags to open journal file */
44503           SQLCIPHER_OPEN_READWRITE|SQLCIPHER_OPEN_CREATE|
44504           (pPager->tempFile ? 
44505             (SQLCIPHER_OPEN_DELETEONCLOSE|SQLCIPHER_OPEN_TEMP_JOURNAL):
44506             (SQLCIPHER_OPEN_MAIN_JOURNAL)
44507           );
44508   #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
44509         rc = sqlcipher3JournalOpen(
44510             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
44511         );
44512   #else
44513         rc = sqlcipher3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
44514   #endif
44515       }
44516       assert( rc!=SQLCIPHER_OK || isOpen(pPager->jfd) );
44517     }
44518   
44519   
44520     /* Write the first journal header to the journal file and open 
44521     ** the sub-journal if necessary.
44522     */
44523     if( rc==SQLCIPHER_OK ){
44524       /* TODO: Check if all of these are really required. */
44525       pPager->nRec = 0;
44526       pPager->journalOff = 0;
44527       pPager->setMaster = 0;
44528       pPager->journalHdr = 0;
44529       rc = writeJournalHdr(pPager);
44530     }
44531   }
44532
44533   if( rc!=SQLCIPHER_OK ){
44534     sqlcipher3BitvecDestroy(pPager->pInJournal);
44535     pPager->pInJournal = 0;
44536   }else{
44537     assert( pPager->eState==PAGER_WRITER_LOCKED );
44538     pPager->eState = PAGER_WRITER_CACHEMOD;
44539   }
44540
44541   return rc;
44542 }
44543
44544 /*
44545 ** Begin a write-transaction on the specified pager object. If a 
44546 ** write-transaction has already been opened, this function is a no-op.
44547 **
44548 ** If the exFlag argument is false, then acquire at least a RESERVED
44549 ** lock on the database file. If exFlag is true, then acquire at least
44550 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
44551 ** functions need be called.
44552 **
44553 ** If the subjInMemory argument is non-zero, then any sub-journal opened
44554 ** within this transaction will be opened as an in-memory file. This
44555 ** has no effect if the sub-journal is already opened (as it may be when
44556 ** running in exclusive mode) or if the transaction does not require a
44557 ** sub-journal. If the subjInMemory argument is zero, then any required
44558 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
44559 ** or using a temporary file otherwise.
44560 */
44561 SQLCIPHER_PRIVATE int sqlcipher3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
44562   int rc = SQLCIPHER_OK;
44563
44564   if( pPager->errCode ) return pPager->errCode;
44565   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
44566   pPager->subjInMemory = (u8)subjInMemory;
44567
44568   if( ALWAYS(pPager->eState==PAGER_READER) ){
44569     assert( pPager->pInJournal==0 );
44570
44571     if( pagerUseWal(pPager) ){
44572       /* If the pager is configured to use locking_mode=exclusive, and an
44573       ** exclusive lock on the database is not already held, obtain it now.
44574       */
44575       if( pPager->exclusiveMode && sqlcipher3WalExclusiveMode(pPager->pWal, -1) ){
44576         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44577         if( rc!=SQLCIPHER_OK ){
44578           return rc;
44579         }
44580         sqlcipher3WalExclusiveMode(pPager->pWal, 1);
44581       }
44582
44583       /* Grab the write lock on the log file. If successful, upgrade to
44584       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
44585       ** The busy-handler is not invoked if another connection already
44586       ** holds the write-lock. If possible, the upper layer will call it.
44587       */
44588       rc = sqlcipher3WalBeginWriteTransaction(pPager->pWal);
44589     }else{
44590       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
44591       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
44592       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
44593       ** lock, but not when obtaining the RESERVED lock.
44594       */
44595       rc = pagerLockDb(pPager, RESERVED_LOCK);
44596       if( rc==SQLCIPHER_OK && exFlag ){
44597         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
44598       }
44599     }
44600
44601     if( rc==SQLCIPHER_OK ){
44602       /* Change to WRITER_LOCKED state.
44603       **
44604       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
44605       ** when it has an open transaction, but never to DBMOD or FINISHED.
44606       ** This is because in those states the code to roll back savepoint 
44607       ** transactions may copy data from the sub-journal into the database 
44608       ** file as well as into the page cache. Which would be incorrect in 
44609       ** WAL mode.
44610       */
44611       pPager->eState = PAGER_WRITER_LOCKED;
44612       pPager->dbHintSize = pPager->dbSize;
44613       pPager->dbFileSize = pPager->dbSize;
44614       pPager->dbOrigSize = pPager->dbSize;
44615       pPager->journalOff = 0;
44616     }
44617
44618     assert( rc==SQLCIPHER_OK || pPager->eState==PAGER_READER );
44619     assert( rc!=SQLCIPHER_OK || pPager->eState==PAGER_WRITER_LOCKED );
44620     assert( assert_pager_state(pPager) );
44621   }
44622
44623   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
44624   return rc;
44625 }
44626
44627 /*
44628 ** Mark a single data page as writeable. The page is written into the 
44629 ** main journal or sub-journal as required. If the page is written into
44630 ** one of the journals, the corresponding bit is set in the 
44631 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
44632 ** of any open savepoints as appropriate.
44633 */
44634 static int pager_write(PgHdr *pPg){
44635   void *pData = pPg->pData;
44636   Pager *pPager = pPg->pPager;
44637   int rc = SQLCIPHER_OK;
44638
44639   /* This routine is not called unless a write-transaction has already 
44640   ** been started. The journal file may or may not be open at this point.
44641   ** It is never called in the ERROR state.
44642   */
44643   assert( pPager->eState==PAGER_WRITER_LOCKED
44644        || pPager->eState==PAGER_WRITER_CACHEMOD
44645        || pPager->eState==PAGER_WRITER_DBMOD
44646   );
44647   assert( assert_pager_state(pPager) );
44648
44649   /* If an error has been previously detected, report the same error
44650   ** again. This should not happen, but the check provides robustness. */
44651   if( NEVER(pPager->errCode) )  return pPager->errCode;
44652
44653   /* Higher-level routines never call this function if database is not
44654   ** writable.  But check anyway, just for robustness. */
44655   if( NEVER(pPager->readOnly) ) return SQLCIPHER_PERM;
44656
44657   CHECK_PAGE(pPg);
44658
44659   /* The journal file needs to be opened. Higher level routines have already
44660   ** obtained the necessary locks to begin the write-transaction, but the
44661   ** rollback journal might not yet be open. Open it now if this is the case.
44662   **
44663   ** This is done before calling sqlcipher3PcacheMakeDirty() on the page. 
44664   ** Otherwise, if it were done after calling sqlcipher3PcacheMakeDirty(), then
44665   ** an error might occur and the pager would end up in WRITER_LOCKED state
44666   ** with pages marked as dirty in the cache.
44667   */
44668   if( pPager->eState==PAGER_WRITER_LOCKED ){
44669     rc = pager_open_journal(pPager);
44670     if( rc!=SQLCIPHER_OK ) return rc;
44671   }
44672   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
44673   assert( assert_pager_state(pPager) );
44674
44675   /* Mark the page as dirty.  If the page has already been written
44676   ** to the journal then we can return right away.
44677   */
44678   sqlcipher3PcacheMakeDirty(pPg);
44679   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
44680     assert( !pagerUseWal(pPager) );
44681   }else{
44682   
44683     /* The transaction journal now exists and we have a RESERVED or an
44684     ** EXCLUSIVE lock on the main database file.  Write the current page to
44685     ** the transaction journal if it is not there already.
44686     */
44687     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
44688       assert( pagerUseWal(pPager)==0 );
44689       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
44690         u32 cksum;
44691         char *pData2;
44692         i64 iOff = pPager->journalOff;
44693
44694         /* We should never write to the journal file the page that
44695         ** contains the database locks.  The following assert verifies
44696         ** that we do not. */
44697         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
44698
44699         assert( pPager->journalHdr<=pPager->journalOff );
44700         CODEC2(pPager, pData, pPg->pgno, 7, return SQLCIPHER_NOMEM, pData2);
44701         cksum = pager_cksum(pPager, (u8*)pData2);
44702
44703         /* Even if an IO or diskfull error occurs while journalling the
44704         ** page in the block above, set the need-sync flag for the page.
44705         ** Otherwise, when the transaction is rolled back, the logic in
44706         ** playback_one_page() will think that the page needs to be restored
44707         ** in the database file. And if an IO error occurs while doing so,
44708         ** then corruption may follow.
44709         */
44710         pPg->flags |= PGHDR_NEED_SYNC;
44711
44712         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
44713         if( rc!=SQLCIPHER_OK ) return rc;
44714         rc = sqlcipher3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
44715         if( rc!=SQLCIPHER_OK ) return rc;
44716         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
44717         if( rc!=SQLCIPHER_OK ) return rc;
44718
44719         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
44720                  pPager->journalOff, pPager->pageSize));
44721         PAGER_INCR(sqlcipher3_pager_writej_count);
44722         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
44723              PAGERID(pPager), pPg->pgno, 
44724              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
44725
44726         pPager->journalOff += 8 + pPager->pageSize;
44727         pPager->nRec++;
44728         assert( pPager->pInJournal!=0 );
44729         rc = sqlcipher3BitvecSet(pPager->pInJournal, pPg->pgno);
44730         testcase( rc==SQLCIPHER_NOMEM );
44731         assert( rc==SQLCIPHER_OK || rc==SQLCIPHER_NOMEM );
44732         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
44733         if( rc!=SQLCIPHER_OK ){
44734           assert( rc==SQLCIPHER_NOMEM );
44735           return rc;
44736         }
44737       }else{
44738         if( pPager->eState!=PAGER_WRITER_DBMOD ){
44739           pPg->flags |= PGHDR_NEED_SYNC;
44740         }
44741         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
44742                 PAGERID(pPager), pPg->pgno,
44743                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
44744       }
44745     }
44746   
44747     /* If the statement journal is open and the page is not in it,
44748     ** then write the current page to the statement journal.  Note that
44749     ** the statement journal format differs from the standard journal format
44750     ** in that it omits the checksums and the header.
44751     */
44752     if( subjRequiresPage(pPg) ){
44753       rc = subjournalPage(pPg);
44754     }
44755   }
44756
44757   /* Update the database size and return.
44758   */
44759   if( pPager->dbSize<pPg->pgno ){
44760     pPager->dbSize = pPg->pgno;
44761   }
44762   return rc;
44763 }
44764
44765 /*
44766 ** Mark a data page as writeable. This routine must be called before 
44767 ** making changes to a page. The caller must check the return value 
44768 ** of this function and be careful not to change any page data unless 
44769 ** this routine returns SQLCIPHER_OK.
44770 **
44771 ** The difference between this function and pager_write() is that this
44772 ** function also deals with the special case where 2 or more pages
44773 ** fit on a single disk sector. In this case all co-resident pages
44774 ** must have been written to the journal file before returning.
44775 **
44776 ** If an error occurs, SQLCIPHER_NOMEM or an IO error code is returned
44777 ** as appropriate. Otherwise, SQLCIPHER_OK.
44778 */
44779 SQLCIPHER_PRIVATE int sqlcipher3PagerWrite(DbPage *pDbPage){
44780   int rc = SQLCIPHER_OK;
44781
44782   PgHdr *pPg = pDbPage;
44783   Pager *pPager = pPg->pPager;
44784   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
44785
44786   assert( pPager->eState>=PAGER_WRITER_LOCKED );
44787   assert( pPager->eState!=PAGER_ERROR );
44788   assert( assert_pager_state(pPager) );
44789
44790   if( nPagePerSector>1 ){
44791     Pgno nPageCount;          /* Total number of pages in database file */
44792     Pgno pg1;                 /* First page of the sector pPg is located on. */
44793     int nPage = 0;            /* Number of pages starting at pg1 to journal */
44794     int ii;                   /* Loop counter */
44795     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
44796
44797     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
44798     ** a journal header to be written between the pages journaled by
44799     ** this function.
44800     */
44801     assert( !MEMDB );
44802     assert( pPager->doNotSyncSpill==0 );
44803     pPager->doNotSyncSpill++;
44804
44805     /* This trick assumes that both the page-size and sector-size are
44806     ** an integer power of 2. It sets variable pg1 to the identifier
44807     ** of the first page of the sector pPg is located on.
44808     */
44809     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
44810
44811     nPageCount = pPager->dbSize;
44812     if( pPg->pgno>nPageCount ){
44813       nPage = (pPg->pgno - pg1)+1;
44814     }else if( (pg1+nPagePerSector-1)>nPageCount ){
44815       nPage = nPageCount+1-pg1;
44816     }else{
44817       nPage = nPagePerSector;
44818     }
44819     assert(nPage>0);
44820     assert(pg1<=pPg->pgno);
44821     assert((pg1+nPage)>pPg->pgno);
44822
44823     for(ii=0; ii<nPage && rc==SQLCIPHER_OK; ii++){
44824       Pgno pg = pg1+ii;
44825       PgHdr *pPage;
44826       if( pg==pPg->pgno || !sqlcipher3BitvecTest(pPager->pInJournal, pg) ){
44827         if( pg!=PAGER_MJ_PGNO(pPager) ){
44828           rc = sqlcipher3PagerGet(pPager, pg, &pPage);
44829           if( rc==SQLCIPHER_OK ){
44830             rc = pager_write(pPage);
44831             if( pPage->flags&PGHDR_NEED_SYNC ){
44832               needSync = 1;
44833             }
44834             sqlcipher3PagerUnref(pPage);
44835           }
44836         }
44837       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
44838         if( pPage->flags&PGHDR_NEED_SYNC ){
44839           needSync = 1;
44840         }
44841         sqlcipher3PagerUnref(pPage);
44842       }
44843     }
44844
44845     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
44846     ** starting at pg1, then it needs to be set for all of them. Because
44847     ** writing to any of these nPage pages may damage the others, the
44848     ** journal file must contain sync()ed copies of all of them
44849     ** before any of them can be written out to the database file.
44850     */
44851     if( rc==SQLCIPHER_OK && needSync ){
44852       assert( !MEMDB );
44853       for(ii=0; ii<nPage; ii++){
44854         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
44855         if( pPage ){
44856           pPage->flags |= PGHDR_NEED_SYNC;
44857           sqlcipher3PagerUnref(pPage);
44858         }
44859       }
44860     }
44861
44862     assert( pPager->doNotSyncSpill==1 );
44863     pPager->doNotSyncSpill--;
44864   }else{
44865     rc = pager_write(pDbPage);
44866   }
44867   return rc;
44868 }
44869
44870 /*
44871 ** Return TRUE if the page given in the argument was previously passed
44872 ** to sqlcipher3PagerWrite().  In other words, return TRUE if it is ok
44873 ** to change the content of the page.
44874 */
44875 #ifndef NDEBUG
44876 SQLCIPHER_PRIVATE int sqlcipher3PagerIswriteable(DbPage *pPg){
44877   return pPg->flags&PGHDR_DIRTY;
44878 }
44879 #endif
44880
44881 /*
44882 ** A call to this routine tells the pager that it is not necessary to
44883 ** write the information on page pPg back to the disk, even though
44884 ** that page might be marked as dirty.  This happens, for example, when
44885 ** the page has been added as a leaf of the freelist and so its
44886 ** content no longer matters.
44887 **
44888 ** The overlying software layer calls this routine when all of the data
44889 ** on the given page is unused. The pager marks the page as clean so
44890 ** that it does not get written to disk.
44891 **
44892 ** Tests show that this optimization can quadruple the speed of large 
44893 ** DELETE operations.
44894 */
44895 SQLCIPHER_PRIVATE void sqlcipher3PagerDontWrite(PgHdr *pPg){
44896   Pager *pPager = pPg->pPager;
44897   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
44898     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
44899     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
44900     pPg->flags |= PGHDR_DONT_WRITE;
44901     pager_set_pagehash(pPg);
44902   }
44903 }
44904
44905 /*
44906 ** This routine is called to increment the value of the database file 
44907 ** change-counter, stored as a 4-byte big-endian integer starting at 
44908 ** byte offset 24 of the pager file.  The secondary change counter at
44909 ** 92 is also updated, as is the SQLite version number at offset 96.
44910 **
44911 ** But this only happens if the pPager->changeCountDone flag is false.
44912 ** To avoid excess churning of page 1, the update only happens once.
44913 ** See also the pager_write_changecounter() routine that does an 
44914 ** unconditional update of the change counters.
44915 **
44916 ** If the isDirectMode flag is zero, then this is done by calling 
44917 ** sqlcipher3PagerWrite() on page 1, then modifying the contents of the
44918 ** page data. In this case the file will be updated when the current
44919 ** transaction is committed.
44920 **
44921 ** The isDirectMode flag may only be non-zero if the library was compiled
44922 ** with the SQLCIPHER_ENABLE_ATOMIC_WRITE macro defined. In this case,
44923 ** if isDirect is non-zero, then the database file is updated directly
44924 ** by writing an updated version of page 1 using a call to the 
44925 ** sqlcipher3OsWrite() function.
44926 */
44927 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
44928   int rc = SQLCIPHER_OK;
44929
44930   assert( pPager->eState==PAGER_WRITER_CACHEMOD
44931        || pPager->eState==PAGER_WRITER_DBMOD
44932   );
44933   assert( assert_pager_state(pPager) );
44934
44935   /* Declare and initialize constant integer 'isDirect'. If the
44936   ** atomic-write optimization is enabled in this build, then isDirect
44937   ** is initialized to the value passed as the isDirectMode parameter
44938   ** to this function. Otherwise, it is always set to zero.
44939   **
44940   ** The idea is that if the atomic-write optimization is not
44941   ** enabled at compile time, the compiler can omit the tests of
44942   ** 'isDirect' below, as well as the block enclosed in the
44943   ** "if( isDirect )" condition.
44944   */
44945 #ifndef SQLCIPHER_ENABLE_ATOMIC_WRITE
44946 # define DIRECT_MODE 0
44947   assert( isDirectMode==0 );
44948   UNUSED_PARAMETER(isDirectMode);
44949 #else
44950 # define DIRECT_MODE isDirectMode
44951 #endif
44952
44953   if( !pPager->changeCountDone && pPager->dbSize>0 ){
44954     PgHdr *pPgHdr;                /* Reference to page 1 */
44955
44956     assert( !pPager->tempFile && isOpen(pPager->fd) );
44957
44958     /* Open page 1 of the file for writing. */
44959     rc = sqlcipher3PagerGet(pPager, 1, &pPgHdr);
44960     assert( pPgHdr==0 || rc==SQLCIPHER_OK );
44961
44962     /* If page one was fetched successfully, and this function is not
44963     ** operating in direct-mode, make page 1 writable.  When not in 
44964     ** direct mode, page 1 is always held in cache and hence the PagerGet()
44965     ** above is always successful - hence the ALWAYS on rc==SQLCIPHER_OK.
44966     */
44967     if( !DIRECT_MODE && ALWAYS(rc==SQLCIPHER_OK) ){
44968       rc = sqlcipher3PagerWrite(pPgHdr);
44969     }
44970
44971     if( rc==SQLCIPHER_OK ){
44972       /* Actually do the update of the change counter */
44973       pager_write_changecounter(pPgHdr);
44974
44975       /* If running in direct mode, write the contents of page 1 to the file. */
44976       if( DIRECT_MODE ){
44977         const void *zBuf;
44978         assert( pPager->dbFileSize>0 );
44979         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLCIPHER_NOMEM, zBuf);
44980         if( rc==SQLCIPHER_OK ){
44981           rc = sqlcipher3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
44982         }
44983         if( rc==SQLCIPHER_OK ){
44984           pPager->changeCountDone = 1;
44985         }
44986       }else{
44987         pPager->changeCountDone = 1;
44988       }
44989     }
44990
44991     /* Release the page reference. */
44992     sqlcipher3PagerUnref(pPgHdr);
44993   }
44994   return rc;
44995 }
44996
44997 /*
44998 ** Sync the database file to disk. This is a no-op for in-memory databases
44999 ** or pages with the Pager.noSync flag set.
45000 **
45001 ** If successful, or if called on a pager for which it is a no-op, this
45002 ** function returns SQLCIPHER_OK. Otherwise, an IO error code is returned.
45003 */
45004 SQLCIPHER_PRIVATE int sqlcipher3PagerSync(Pager *pPager){
45005   int rc = SQLCIPHER_OK;
45006   if( !pPager->noSync ){
45007     assert( !MEMDB );
45008     rc = sqlcipher3OsSync(pPager->fd, pPager->syncFlags);
45009   }else if( isOpen(pPager->fd) ){
45010     assert( !MEMDB );
45011     sqlcipher3OsFileControl(pPager->fd, SQLCIPHER_FCNTL_SYNC_OMITTED, (void *)&rc);
45012   }
45013   return rc;
45014 }
45015
45016 /*
45017 ** This function may only be called while a write-transaction is active in
45018 ** rollback. If the connection is in WAL mode, this call is a no-op. 
45019 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
45020 ** the database file, an attempt is made to obtain one.
45021 **
45022 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
45023 ** successful, or the connection is in WAL mode, SQLCIPHER_OK is returned.
45024 ** Otherwise, either SQLCIPHER_BUSY or an SQLCIPHER_IOERR_XXX error code is 
45025 ** returned.
45026 */
45027 SQLCIPHER_PRIVATE int sqlcipher3PagerExclusiveLock(Pager *pPager){
45028   int rc = SQLCIPHER_OK;
45029   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
45030        || pPager->eState==PAGER_WRITER_DBMOD 
45031        || pPager->eState==PAGER_WRITER_LOCKED 
45032   );
45033   assert( assert_pager_state(pPager) );
45034   if( 0==pagerUseWal(pPager) ){
45035     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
45036   }
45037   return rc;
45038 }
45039
45040 /*
45041 ** Sync the database file for the pager pPager. zMaster points to the name
45042 ** of a master journal file that should be written into the individual
45043 ** journal file. zMaster may be NULL, which is interpreted as no master
45044 ** journal (a single database transaction).
45045 **
45046 ** This routine ensures that:
45047 **
45048 **   * The database file change-counter is updated,
45049 **   * the journal is synced (unless the atomic-write optimization is used),
45050 **   * all dirty pages are written to the database file, 
45051 **   * the database file is truncated (if required), and
45052 **   * the database file synced. 
45053 **
45054 ** The only thing that remains to commit the transaction is to finalize 
45055 ** (delete, truncate or zero the first part of) the journal file (or 
45056 ** delete the master journal file if specified).
45057 **
45058 ** Note that if zMaster==NULL, this does not overwrite a previous value
45059 ** passed to an sqlcipher3PagerCommitPhaseOne() call.
45060 **
45061 ** If the final parameter - noSync - is true, then the database file itself
45062 ** is not synced. The caller must call sqlcipher3PagerSync() directly to
45063 ** sync the database file before calling CommitPhaseTwo() to delete the
45064 ** journal file in this case.
45065 */
45066 SQLCIPHER_PRIVATE int sqlcipher3PagerCommitPhaseOne(
45067   Pager *pPager,                  /* Pager object */
45068   const char *zMaster,            /* If not NULL, the master journal name */
45069   int noSync                      /* True to omit the xSync on the db file */
45070 ){
45071   int rc = SQLCIPHER_OK;             /* Return code */
45072
45073   assert( pPager->eState==PAGER_WRITER_LOCKED
45074        || pPager->eState==PAGER_WRITER_CACHEMOD
45075        || pPager->eState==PAGER_WRITER_DBMOD
45076        || pPager->eState==PAGER_ERROR
45077   );
45078   assert( assert_pager_state(pPager) );
45079
45080   /* If a prior error occurred, report that error again. */
45081   if( NEVER(pPager->errCode) ) return pPager->errCode;
45082
45083   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
45084       pPager->zFilename, zMaster, pPager->dbSize));
45085
45086   /* If no database changes have been made, return early. */
45087   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLCIPHER_OK;
45088
45089   if( MEMDB ){
45090     /* If this is an in-memory db, or no pages have been written to, or this
45091     ** function has already been called, it is mostly a no-op.  However, any
45092     ** backup in progress needs to be restarted.
45093     */
45094     sqlcipher3BackupRestart(pPager->pBackup);
45095   }else{
45096     if( pagerUseWal(pPager) ){
45097       PgHdr *pList = sqlcipher3PcacheDirtyList(pPager->pPCache);
45098       PgHdr *pPageOne = 0;
45099       if( pList==0 ){
45100         /* Must have at least one page for the WAL commit flag.
45101         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
45102         rc = sqlcipher3PagerGet(pPager, 1, &pPageOne);
45103         pList = pPageOne;
45104         pList->pDirty = 0;
45105       }
45106       assert( rc==SQLCIPHER_OK );
45107       if( ALWAYS(pList) ){
45108         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1, 
45109             (pPager->fullSync ? pPager->syncFlags : 0)
45110         );
45111       }
45112       sqlcipher3PagerUnref(pPageOne);
45113       if( rc==SQLCIPHER_OK ){
45114         sqlcipher3PcacheCleanAll(pPager->pPCache);
45115       }
45116     }else{
45117       /* The following block updates the change-counter. Exactly how it
45118       ** does this depends on whether or not the atomic-update optimization
45119       ** was enabled at compile time, and if this transaction meets the 
45120       ** runtime criteria to use the operation: 
45121       **
45122       **    * The file-system supports the atomic-write property for
45123       **      blocks of size page-size, and 
45124       **    * This commit is not part of a multi-file transaction, and
45125       **    * Exactly one page has been modified and store in the journal file.
45126       **
45127       ** If the optimization was not enabled at compile time, then the
45128       ** pager_incr_changecounter() function is called to update the change
45129       ** counter in 'indirect-mode'. If the optimization is compiled in but
45130       ** is not applicable to this transaction, call sqlcipher3JournalCreate()
45131       ** to make sure the journal file has actually been created, then call
45132       ** pager_incr_changecounter() to update the change-counter in indirect
45133       ** mode. 
45134       **
45135       ** Otherwise, if the optimization is both enabled and applicable,
45136       ** then call pager_incr_changecounter() to update the change-counter
45137       ** in 'direct' mode. In this case the journal file will never be
45138       ** created for this transaction.
45139       */
45140   #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
45141       PgHdr *pPg;
45142       assert( isOpen(pPager->jfd) 
45143            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
45144            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
45145       );
45146       if( !zMaster && isOpen(pPager->jfd) 
45147        && pPager->journalOff==jrnlBufferSize(pPager) 
45148        && pPager->dbSize>=pPager->dbOrigSize
45149        && (0==(pPg = sqlcipher3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
45150       ){
45151         /* Update the db file change counter via the direct-write method. The 
45152         ** following call will modify the in-memory representation of page 1 
45153         ** to include the updated change counter and then write page 1 
45154         ** directly to the database file. Because of the atomic-write 
45155         ** property of the host file-system, this is safe.
45156         */
45157         rc = pager_incr_changecounter(pPager, 1);
45158       }else{
45159         rc = sqlcipher3JournalCreate(pPager->jfd);
45160         if( rc==SQLCIPHER_OK ){
45161           rc = pager_incr_changecounter(pPager, 0);
45162         }
45163       }
45164   #else
45165       rc = pager_incr_changecounter(pPager, 0);
45166   #endif
45167       if( rc!=SQLCIPHER_OK ) goto commit_phase_one_exit;
45168   
45169       /* If this transaction has made the database smaller, then all pages
45170       ** being discarded by the truncation must be written to the journal
45171       ** file. This can only happen in auto-vacuum mode.
45172       **
45173       ** Before reading the pages with page numbers larger than the 
45174       ** current value of Pager.dbSize, set dbSize back to the value
45175       ** that it took at the start of the transaction. Otherwise, the
45176       ** calls to sqlcipher3PagerGet() return zeroed pages instead of 
45177       ** reading data from the database file.
45178       */
45179   #ifndef SQLCIPHER_OMIT_AUTOVACUUM
45180       if( pPager->dbSize<pPager->dbOrigSize 
45181        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
45182       ){
45183         Pgno i;                                   /* Iterator variable */
45184         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
45185         const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
45186         pPager->dbSize = pPager->dbOrigSize;
45187         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
45188           if( !sqlcipher3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
45189             PgHdr *pPage;             /* Page to journal */
45190             rc = sqlcipher3PagerGet(pPager, i, &pPage);
45191             if( rc!=SQLCIPHER_OK ) goto commit_phase_one_exit;
45192             rc = sqlcipher3PagerWrite(pPage);
45193             sqlcipher3PagerUnref(pPage);
45194             if( rc!=SQLCIPHER_OK ) goto commit_phase_one_exit;
45195           }
45196         }
45197         pPager->dbSize = dbSize;
45198       } 
45199   #endif
45200   
45201       /* Write the master journal name into the journal file. If a master 
45202       ** journal file name has already been written to the journal file, 
45203       ** or if zMaster is NULL (no master journal), then this call is a no-op.
45204       */
45205       rc = writeMasterJournal(pPager, zMaster);
45206       if( rc!=SQLCIPHER_OK ) goto commit_phase_one_exit;
45207   
45208       /* Sync the journal file and write all dirty pages to the database.
45209       ** If the atomic-update optimization is being used, this sync will not 
45210       ** create the journal file or perform any real IO.
45211       **
45212       ** Because the change-counter page was just modified, unless the
45213       ** atomic-update optimization is used it is almost certain that the
45214       ** journal requires a sync here. However, in locking_mode=exclusive
45215       ** on a system under memory pressure it is just possible that this is 
45216       ** not the case. In this case it is likely enough that the redundant
45217       ** xSync() call will be changed to a no-op by the OS anyhow. 
45218       */
45219       rc = syncJournal(pPager, 0);
45220       if( rc!=SQLCIPHER_OK ) goto commit_phase_one_exit;
45221   
45222       rc = pager_write_pagelist(pPager,sqlcipher3PcacheDirtyList(pPager->pPCache));
45223       if( rc!=SQLCIPHER_OK ){
45224         assert( rc!=SQLCIPHER_IOERR_BLOCKED );
45225         goto commit_phase_one_exit;
45226       }
45227       sqlcipher3PcacheCleanAll(pPager->pPCache);
45228   
45229       /* If the file on disk is not the same size as the database image,
45230       ** then use pager_truncate to grow or shrink the file here.
45231       */
45232       if( pPager->dbSize!=pPager->dbFileSize ){
45233         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
45234         assert( pPager->eState==PAGER_WRITER_DBMOD );
45235         rc = pager_truncate(pPager, nNew);
45236         if( rc!=SQLCIPHER_OK ) goto commit_phase_one_exit;
45237       }
45238   
45239       /* Finally, sync the database file. */
45240       if( !noSync ){
45241         rc = sqlcipher3PagerSync(pPager);
45242       }
45243       IOTRACE(("DBSYNC %p\n", pPager))
45244     }
45245   }
45246
45247 commit_phase_one_exit:
45248   if( rc==SQLCIPHER_OK && !pagerUseWal(pPager) ){
45249     pPager->eState = PAGER_WRITER_FINISHED;
45250   }
45251   return rc;
45252 }
45253
45254
45255 /*
45256 ** When this function is called, the database file has been completely
45257 ** updated to reflect the changes made by the current transaction and
45258 ** synced to disk. The journal file still exists in the file-system 
45259 ** though, and if a failure occurs at this point it will eventually
45260 ** be used as a hot-journal and the current transaction rolled back.
45261 **
45262 ** This function finalizes the journal file, either by deleting, 
45263 ** truncating or partially zeroing it, so that it cannot be used 
45264 ** for hot-journal rollback. Once this is done the transaction is
45265 ** irrevocably committed.
45266 **
45267 ** If an error occurs, an IO error code is returned and the pager
45268 ** moves into the error state. Otherwise, SQLCIPHER_OK is returned.
45269 */
45270 SQLCIPHER_PRIVATE int sqlcipher3PagerCommitPhaseTwo(Pager *pPager){
45271   int rc = SQLCIPHER_OK;                  /* Return code */
45272
45273   /* This routine should not be called if a prior error has occurred.
45274   ** But if (due to a coding error elsewhere in the system) it does get
45275   ** called, just return the same error code without doing anything. */
45276   if( NEVER(pPager->errCode) ) return pPager->errCode;
45277
45278   assert( pPager->eState==PAGER_WRITER_LOCKED
45279        || pPager->eState==PAGER_WRITER_FINISHED
45280        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
45281   );
45282   assert( assert_pager_state(pPager) );
45283
45284   /* An optimization. If the database was not actually modified during
45285   ** this transaction, the pager is running in exclusive-mode and is
45286   ** using persistent journals, then this function is a no-op.
45287   **
45288   ** The start of the journal file currently contains a single journal 
45289   ** header with the nRec field set to 0. If such a journal is used as
45290   ** a hot-journal during hot-journal rollback, 0 changes will be made
45291   ** to the database file. So there is no need to zero the journal 
45292   ** header. Since the pager is in exclusive mode, there is no need
45293   ** to drop any locks either.
45294   */
45295   if( pPager->eState==PAGER_WRITER_LOCKED 
45296    && pPager->exclusiveMode 
45297    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
45298   ){
45299     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
45300     pPager->eState = PAGER_READER;
45301     return SQLCIPHER_OK;
45302   }
45303
45304   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
45305   rc = pager_end_transaction(pPager, pPager->setMaster);
45306   return pager_error(pPager, rc);
45307 }
45308
45309 /*
45310 ** If a write transaction is open, then all changes made within the 
45311 ** transaction are reverted and the current write-transaction is closed.
45312 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
45313 ** state if an error occurs.
45314 **
45315 ** If the pager is already in PAGER_ERROR state when this function is called,
45316 ** it returns Pager.errCode immediately. No work is performed in this case.
45317 **
45318 ** Otherwise, in rollback mode, this function performs two functions:
45319 **
45320 **   1) It rolls back the journal file, restoring all database file and 
45321 **      in-memory cache pages to the state they were in when the transaction
45322 **      was opened, and
45323 **
45324 **   2) It finalizes the journal file, so that it is not used for hot
45325 **      rollback at any point in the future.
45326 **
45327 ** Finalization of the journal file (task 2) is only performed if the 
45328 ** rollback is successful.
45329 **
45330 ** In WAL mode, all cache-entries containing data modified within the
45331 ** current transaction are either expelled from the cache or reverted to
45332 ** their pre-transaction state by re-reading data from the database or
45333 ** WAL files. The WAL transaction is then closed.
45334 */
45335 SQLCIPHER_PRIVATE int sqlcipher3PagerRollback(Pager *pPager){
45336   int rc = SQLCIPHER_OK;                  /* Return code */
45337   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
45338
45339   /* PagerRollback() is a no-op if called in READER or OPEN state. If
45340   ** the pager is already in the ERROR state, the rollback is not 
45341   ** attempted here. Instead, the error code is returned to the caller.
45342   */
45343   assert( assert_pager_state(pPager) );
45344   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
45345   if( pPager->eState<=PAGER_READER ) return SQLCIPHER_OK;
45346
45347   if( pagerUseWal(pPager) ){
45348     int rc2;
45349     rc = sqlcipher3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
45350     rc2 = pager_end_transaction(pPager, pPager->setMaster);
45351     if( rc==SQLCIPHER_OK ) rc = rc2;
45352   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
45353     int eState = pPager->eState;
45354     rc = pager_end_transaction(pPager, 0);
45355     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
45356       /* This can happen using journal_mode=off. Move the pager to the error 
45357       ** state to indicate that the contents of the cache may not be trusted.
45358       ** Any active readers will get SQLCIPHER_ABORT.
45359       */
45360       pPager->errCode = SQLCIPHER_ABORT;
45361       pPager->eState = PAGER_ERROR;
45362       return rc;
45363     }
45364   }else{
45365     rc = pager_playback(pPager, 0);
45366   }
45367
45368   assert( pPager->eState==PAGER_READER || rc!=SQLCIPHER_OK );
45369   assert( rc==SQLCIPHER_OK || rc==SQLCIPHER_FULL || (rc&0xFF)==SQLCIPHER_IOERR );
45370
45371   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
45372   ** cache. So call pager_error() on the way out to make any error persistent.
45373   */
45374   return pager_error(pPager, rc);
45375 }
45376
45377 /*
45378 ** Return TRUE if the database file is opened read-only.  Return FALSE
45379 ** if the database is (in theory) writable.
45380 */
45381 SQLCIPHER_PRIVATE u8 sqlcipher3PagerIsreadonly(Pager *pPager){
45382   return pPager->readOnly;
45383 }
45384
45385 /*
45386 ** Return the number of references to the pager.
45387 */
45388 SQLCIPHER_PRIVATE int sqlcipher3PagerRefcount(Pager *pPager){
45389   return sqlcipher3PcacheRefCount(pPager->pPCache);
45390 }
45391
45392 /*
45393 ** Return the approximate number of bytes of memory currently
45394 ** used by the pager and its associated cache.
45395 */
45396 SQLCIPHER_PRIVATE int sqlcipher3PagerMemUsed(Pager *pPager){
45397   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
45398                                      + 5*sizeof(void*);
45399   return perPageSize*sqlcipher3PcachePagecount(pPager->pPCache)
45400            + sqlcipher3MallocSize(pPager)
45401            + pPager->pageSize;
45402 }
45403
45404 /*
45405 ** Return the number of references to the specified page.
45406 */
45407 SQLCIPHER_PRIVATE int sqlcipher3PagerPageRefcount(DbPage *pPage){
45408   return sqlcipher3PcachePageRefcount(pPage);
45409 }
45410
45411 #ifdef SQLCIPHER_TEST
45412 /*
45413 ** This routine is used for testing and analysis only.
45414 */
45415 SQLCIPHER_PRIVATE int *sqlcipher3PagerStats(Pager *pPager){
45416   static int a[11];
45417   a[0] = sqlcipher3PcacheRefCount(pPager->pPCache);
45418   a[1] = sqlcipher3PcachePagecount(pPager->pPCache);
45419   a[2] = sqlcipher3PcacheGetCachesize(pPager->pPCache);
45420   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
45421   a[4] = pPager->eState;
45422   a[5] = pPager->errCode;
45423   a[6] = pPager->nHit;
45424   a[7] = pPager->nMiss;
45425   a[8] = 0;  /* Used to be pPager->nOvfl */
45426   a[9] = pPager->nRead;
45427   a[10] = pPager->nWrite;
45428   return a;
45429 }
45430 #endif
45431
45432 /*
45433 ** Parameter eStat must be either SQLCIPHER_DBSTATUS_CACHE_HIT or
45434 ** SQLCIPHER_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
45435 ** current cache hit or miss count, according to the value of eStat. If the 
45436 ** reset parameter is non-zero, the cache hit or miss count is zeroed before 
45437 ** returning.
45438 */
45439 SQLCIPHER_PRIVATE void sqlcipher3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
45440   int *piStat;
45441
45442   assert( eStat==SQLCIPHER_DBSTATUS_CACHE_HIT
45443        || eStat==SQLCIPHER_DBSTATUS_CACHE_MISS
45444   );
45445   if( eStat==SQLCIPHER_DBSTATUS_CACHE_HIT ){
45446     piStat = &pPager->nHit;
45447   }else{
45448     piStat = &pPager->nMiss;
45449   }
45450
45451   *pnVal += *piStat;
45452   if( reset ){
45453     *piStat = 0;
45454   }
45455 }
45456
45457 /*
45458 ** Return true if this is an in-memory pager.
45459 */
45460 SQLCIPHER_PRIVATE int sqlcipher3PagerIsMemdb(Pager *pPager){
45461   return MEMDB;
45462 }
45463
45464 /*
45465 ** Check that there are at least nSavepoint savepoints open. If there are
45466 ** currently less than nSavepoints open, then open one or more savepoints
45467 ** to make up the difference. If the number of savepoints is already
45468 ** equal to nSavepoint, then this function is a no-op.
45469 **
45470 ** If a memory allocation fails, SQLCIPHER_NOMEM is returned. If an error 
45471 ** occurs while opening the sub-journal file, then an IO error code is
45472 ** returned. Otherwise, SQLCIPHER_OK.
45473 */
45474 SQLCIPHER_PRIVATE int sqlcipher3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
45475   int rc = SQLCIPHER_OK;                       /* Return code */
45476   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
45477
45478   assert( pPager->eState>=PAGER_WRITER_LOCKED );
45479   assert( assert_pager_state(pPager) );
45480
45481   if( nSavepoint>nCurrent && pPager->useJournal ){
45482     int ii;                                 /* Iterator variable */
45483     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
45484
45485     /* Grow the Pager.aSavepoint array using realloc(). Return SQLCIPHER_NOMEM
45486     ** if the allocation fails. Otherwise, zero the new portion in case a 
45487     ** malloc failure occurs while populating it in the for(...) loop below.
45488     */
45489     aNew = (PagerSavepoint *)sqlcipher3Realloc(
45490         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
45491     );
45492     if( !aNew ){
45493       return SQLCIPHER_NOMEM;
45494     }
45495     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
45496     pPager->aSavepoint = aNew;
45497
45498     /* Populate the PagerSavepoint structures just allocated. */
45499     for(ii=nCurrent; ii<nSavepoint; ii++){
45500       aNew[ii].nOrig = pPager->dbSize;
45501       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
45502         aNew[ii].iOffset = pPager->journalOff;
45503       }else{
45504         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
45505       }
45506       aNew[ii].iSubRec = pPager->nSubRec;
45507       aNew[ii].pInSavepoint = sqlcipher3BitvecCreate(pPager->dbSize);
45508       if( !aNew[ii].pInSavepoint ){
45509         return SQLCIPHER_NOMEM;
45510       }
45511       if( pagerUseWal(pPager) ){
45512         sqlcipher3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
45513       }
45514       pPager->nSavepoint = ii+1;
45515     }
45516     assert( pPager->nSavepoint==nSavepoint );
45517     assertTruncateConstraint(pPager);
45518   }
45519
45520   return rc;
45521 }
45522
45523 /*
45524 ** This function is called to rollback or release (commit) a savepoint.
45525 ** The savepoint to release or rollback need not be the most recently 
45526 ** created savepoint.
45527 **
45528 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
45529 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
45530 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
45531 ** that have occurred since the specified savepoint was created.
45532 **
45533 ** The savepoint to rollback or release is identified by parameter 
45534 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
45535 ** (the first created). A value of (Pager.nSavepoint-1) means operate
45536 ** on the most recently created savepoint. If iSavepoint is greater than
45537 ** (Pager.nSavepoint-1), then this function is a no-op.
45538 **
45539 ** If a negative value is passed to this function, then the current
45540 ** transaction is rolled back. This is different to calling 
45541 ** sqlcipher3PagerRollback() because this function does not terminate
45542 ** the transaction or unlock the database, it just restores the 
45543 ** contents of the database to its original state. 
45544 **
45545 ** In any case, all savepoints with an index greater than iSavepoint 
45546 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
45547 ** then savepoint iSavepoint is also destroyed.
45548 **
45549 ** This function may return SQLCIPHER_NOMEM if a memory allocation fails,
45550 ** or an IO error code if an IO error occurs while rolling back a 
45551 ** savepoint. If no errors occur, SQLCIPHER_OK is returned.
45552 */ 
45553 SQLCIPHER_PRIVATE int sqlcipher3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
45554   int rc = pPager->errCode;       /* Return code */
45555
45556   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
45557   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
45558
45559   if( rc==SQLCIPHER_OK && iSavepoint<pPager->nSavepoint ){
45560     int ii;            /* Iterator variable */
45561     int nNew;          /* Number of remaining savepoints after this op. */
45562
45563     /* Figure out how many savepoints will still be active after this
45564     ** operation. Store this value in nNew. Then free resources associated 
45565     ** with any savepoints that are destroyed by this operation.
45566     */
45567     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
45568     for(ii=nNew; ii<pPager->nSavepoint; ii++){
45569       sqlcipher3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
45570     }
45571     pPager->nSavepoint = nNew;
45572
45573     /* If this is a release of the outermost savepoint, truncate 
45574     ** the sub-journal to zero bytes in size. */
45575     if( op==SAVEPOINT_RELEASE ){
45576       if( nNew==0 && isOpen(pPager->sjfd) ){
45577         /* Only truncate if it is an in-memory sub-journal. */
45578         if( sqlcipher3IsMemJournal(pPager->sjfd) ){
45579           rc = sqlcipher3OsTruncate(pPager->sjfd, 0);
45580           assert( rc==SQLCIPHER_OK );
45581         }
45582         pPager->nSubRec = 0;
45583       }
45584     }
45585     /* Else this is a rollback operation, playback the specified savepoint.
45586     ** If this is a temp-file, it is possible that the journal file has
45587     ** not yet been opened. In this case there have been no changes to
45588     ** the database file, so the playback operation can be skipped.
45589     */
45590     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
45591       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
45592       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
45593       assert(rc!=SQLCIPHER_DONE);
45594     }
45595   }
45596
45597   return rc;
45598 }
45599
45600 /*
45601 ** Return the full pathname of the database file.
45602 */
45603 SQLCIPHER_PRIVATE const char *sqlcipher3PagerFilename(Pager *pPager){
45604   return pPager->zFilename;
45605 }
45606
45607 /*
45608 ** Return the VFS structure for the pager.
45609 */
45610 SQLCIPHER_PRIVATE const sqlcipher3_vfs *sqlcipher3PagerVfs(Pager *pPager){
45611   return pPager->pVfs;
45612 }
45613
45614 /*
45615 ** Return the file handle for the database file associated
45616 ** with the pager.  This might return NULL if the file has
45617 ** not yet been opened.
45618 */
45619 SQLCIPHER_PRIVATE sqlcipher3_file *sqlcipher3PagerFile(Pager *pPager){
45620   return pPager->fd;
45621 }
45622
45623 /*
45624 ** Return the full pathname of the journal file.
45625 */
45626 SQLCIPHER_PRIVATE const char *sqlcipher3PagerJournalname(Pager *pPager){
45627   return pPager->zJournal;
45628 }
45629
45630 /*
45631 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
45632 ** if fsync()s are executed normally.
45633 */
45634 SQLCIPHER_PRIVATE int sqlcipher3PagerNosync(Pager *pPager){
45635   return pPager->noSync;
45636 }
45637
45638 #ifdef SQLCIPHER_HAS_CODEC
45639 /*
45640 ** Set or retrieve the codec for this pager
45641 */
45642 SQLCIPHER_PRIVATE void sqlcipher3PagerSetCodec(
45643   Pager *pPager,
45644   void *(*xCodec)(void*,void*,Pgno,int),
45645   void (*xCodecSizeChng)(void*,int,int),
45646   void (*xCodecFree)(void*),
45647   void *pCodec
45648 ){
45649   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
45650   pPager->xCodec = pPager->memDb ? 0 : xCodec;
45651   pPager->xCodecSizeChng = xCodecSizeChng;
45652   pPager->xCodecFree = xCodecFree;
45653   pPager->pCodec = pCodec;
45654   pagerReportSize(pPager);
45655 }
45656 SQLCIPHER_PRIVATE void *sqlcipher3PagerGetCodec(Pager *pPager){
45657   return pPager->pCodec;
45658 }
45659 #endif
45660
45661 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
45662 /*
45663 ** Move the page pPg to location pgno in the file.
45664 **
45665 ** There must be no references to the page previously located at
45666 ** pgno (which we call pPgOld) though that page is allowed to be
45667 ** in cache.  If the page previously located at pgno is not already
45668 ** in the rollback journal, it is not put there by by this routine.
45669 **
45670 ** References to the page pPg remain valid. Updating any
45671 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
45672 ** allocated along with the page) is the responsibility of the caller.
45673 **
45674 ** A transaction must be active when this routine is called. It used to be
45675 ** required that a statement transaction was not active, but this restriction
45676 ** has been removed (CREATE INDEX needs to move a page when a statement
45677 ** transaction is active).
45678 **
45679 ** If the fourth argument, isCommit, is non-zero, then this page is being
45680 ** moved as part of a database reorganization just before the transaction 
45681 ** is being committed. In this case, it is guaranteed that the database page 
45682 ** pPg refers to will not be written to again within this transaction.
45683 **
45684 ** This function may return SQLCIPHER_NOMEM or an IO error code if an error
45685 ** occurs. Otherwise, it returns SQLCIPHER_OK.
45686 */
45687 SQLCIPHER_PRIVATE int sqlcipher3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
45688   PgHdr *pPgOld;               /* The page being overwritten. */
45689   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
45690   int rc;                      /* Return code */
45691   Pgno origPgno;               /* The original page number */
45692
45693   assert( pPg->nRef>0 );
45694   assert( pPager->eState==PAGER_WRITER_CACHEMOD
45695        || pPager->eState==PAGER_WRITER_DBMOD
45696   );
45697   assert( assert_pager_state(pPager) );
45698
45699   /* In order to be able to rollback, an in-memory database must journal
45700   ** the page we are moving from.
45701   */
45702   if( MEMDB ){
45703     rc = sqlcipher3PagerWrite(pPg);
45704     if( rc ) return rc;
45705   }
45706
45707   /* If the page being moved is dirty and has not been saved by the latest
45708   ** savepoint, then save the current contents of the page into the 
45709   ** sub-journal now. This is required to handle the following scenario:
45710   **
45711   **   BEGIN;
45712   **     <journal page X, then modify it in memory>
45713   **     SAVEPOINT one;
45714   **       <Move page X to location Y>
45715   **     ROLLBACK TO one;
45716   **
45717   ** If page X were not written to the sub-journal here, it would not
45718   ** be possible to restore its contents when the "ROLLBACK TO one"
45719   ** statement were is processed.
45720   **
45721   ** subjournalPage() may need to allocate space to store pPg->pgno into
45722   ** one or more savepoint bitvecs. This is the reason this function
45723   ** may return SQLCIPHER_NOMEM.
45724   */
45725   if( pPg->flags&PGHDR_DIRTY
45726    && subjRequiresPage(pPg)
45727    && SQLCIPHER_OK!=(rc = subjournalPage(pPg))
45728   ){
45729     return rc;
45730   }
45731
45732   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
45733       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
45734   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
45735
45736   /* If the journal needs to be sync()ed before page pPg->pgno can
45737   ** be written to, store pPg->pgno in local variable needSyncPgno.
45738   **
45739   ** If the isCommit flag is set, there is no need to remember that
45740   ** the journal needs to be sync()ed before database page pPg->pgno 
45741   ** can be written to. The caller has already promised not to write to it.
45742   */
45743   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
45744     needSyncPgno = pPg->pgno;
45745     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
45746     assert( pPg->flags&PGHDR_DIRTY );
45747   }
45748
45749   /* If the cache contains a page with page-number pgno, remove it
45750   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
45751   ** page pgno before the 'move' operation, it needs to be retained 
45752   ** for the page moved there.
45753   */
45754   pPg->flags &= ~PGHDR_NEED_SYNC;
45755   pPgOld = pager_lookup(pPager, pgno);
45756   assert( !pPgOld || pPgOld->nRef==1 );
45757   if( pPgOld ){
45758     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
45759     if( MEMDB ){
45760       /* Do not discard pages from an in-memory database since we might
45761       ** need to rollback later.  Just move the page out of the way. */
45762       sqlcipher3PcacheMove(pPgOld, pPager->dbSize+1);
45763     }else{
45764       sqlcipher3PcacheDrop(pPgOld);
45765     }
45766   }
45767
45768   origPgno = pPg->pgno;
45769   sqlcipher3PcacheMove(pPg, pgno);
45770   sqlcipher3PcacheMakeDirty(pPg);
45771
45772   /* For an in-memory database, make sure the original page continues
45773   ** to exist, in case the transaction needs to roll back.  Use pPgOld
45774   ** as the original page since it has already been allocated.
45775   */
45776   if( MEMDB ){
45777     assert( pPgOld );
45778     sqlcipher3PcacheMove(pPgOld, origPgno);
45779     sqlcipher3PagerUnref(pPgOld);
45780   }
45781
45782   if( needSyncPgno ){
45783     /* If needSyncPgno is non-zero, then the journal file needs to be 
45784     ** sync()ed before any data is written to database file page needSyncPgno.
45785     ** Currently, no such page exists in the page-cache and the 
45786     ** "is journaled" bitvec flag has been set. This needs to be remedied by
45787     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
45788     ** flag.
45789     **
45790     ** If the attempt to load the page into the page-cache fails, (due
45791     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
45792     ** array. Otherwise, if the page is loaded and written again in
45793     ** this transaction, it may be written to the database file before
45794     ** it is synced into the journal file. This way, it may end up in
45795     ** the journal file twice, but that is not a problem.
45796     */
45797     PgHdr *pPgHdr;
45798     rc = sqlcipher3PagerGet(pPager, needSyncPgno, &pPgHdr);
45799     if( rc!=SQLCIPHER_OK ){
45800       if( needSyncPgno<=pPager->dbOrigSize ){
45801         assert( pPager->pTmpSpace!=0 );
45802         sqlcipher3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
45803       }
45804       return rc;
45805     }
45806     pPgHdr->flags |= PGHDR_NEED_SYNC;
45807     sqlcipher3PcacheMakeDirty(pPgHdr);
45808     sqlcipher3PagerUnref(pPgHdr);
45809   }
45810
45811   return SQLCIPHER_OK;
45812 }
45813 #endif
45814
45815 /*
45816 ** Return a pointer to the data for the specified page.
45817 */
45818 SQLCIPHER_PRIVATE void *sqlcipher3PagerGetData(DbPage *pPg){
45819   assert( pPg->nRef>0 || pPg->pPager->memDb );
45820   return pPg->pData;
45821 }
45822
45823 /*
45824 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
45825 ** allocated along with the specified page.
45826 */
45827 SQLCIPHER_PRIVATE void *sqlcipher3PagerGetExtra(DbPage *pPg){
45828   return pPg->pExtra;
45829 }
45830
45831 /*
45832 ** Get/set the locking-mode for this pager. Parameter eMode must be one
45833 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
45834 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
45835 ** the locking-mode is set to the value specified.
45836 **
45837 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
45838 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
45839 ** locking-mode.
45840 */
45841 SQLCIPHER_PRIVATE int sqlcipher3PagerLockingMode(Pager *pPager, int eMode){
45842   assert( eMode==PAGER_LOCKINGMODE_QUERY
45843             || eMode==PAGER_LOCKINGMODE_NORMAL
45844             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
45845   assert( PAGER_LOCKINGMODE_QUERY<0 );
45846   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
45847   assert( pPager->exclusiveMode || 0==sqlcipher3WalHeapMemory(pPager->pWal) );
45848   if( eMode>=0 && !pPager->tempFile && !sqlcipher3WalHeapMemory(pPager->pWal) ){
45849     pPager->exclusiveMode = (u8)eMode;
45850   }
45851   return (int)pPager->exclusiveMode;
45852 }
45853
45854 /*
45855 ** Set the journal-mode for this pager. Parameter eMode must be one of:
45856 **
45857 **    PAGER_JOURNALMODE_DELETE
45858 **    PAGER_JOURNALMODE_TRUNCATE
45859 **    PAGER_JOURNALMODE_PERSIST
45860 **    PAGER_JOURNALMODE_OFF
45861 **    PAGER_JOURNALMODE_MEMORY
45862 **    PAGER_JOURNALMODE_WAL
45863 **
45864 ** The journalmode is set to the value specified if the change is allowed.
45865 ** The change may be disallowed for the following reasons:
45866 **
45867 **   *  An in-memory database can only have its journal_mode set to _OFF
45868 **      or _MEMORY.
45869 **
45870 **   *  Temporary databases cannot have _WAL journalmode.
45871 **
45872 ** The returned indicate the current (possibly updated) journal-mode.
45873 */
45874 SQLCIPHER_PRIVATE int sqlcipher3PagerSetJournalMode(Pager *pPager, int eMode){
45875   u8 eOld = pPager->journalMode;    /* Prior journalmode */
45876
45877 #ifdef SQLCIPHER_DEBUG
45878   /* The print_pager_state() routine is intended to be used by the debugger
45879   ** only.  We invoke it once here to suppress a compiler warning. */
45880   print_pager_state(pPager);
45881 #endif
45882
45883
45884   /* The eMode parameter is always valid */
45885   assert(      eMode==PAGER_JOURNALMODE_DELETE
45886             || eMode==PAGER_JOURNALMODE_TRUNCATE
45887             || eMode==PAGER_JOURNALMODE_PERSIST
45888             || eMode==PAGER_JOURNALMODE_OFF 
45889             || eMode==PAGER_JOURNALMODE_WAL 
45890             || eMode==PAGER_JOURNALMODE_MEMORY );
45891
45892   /* This routine is only called from the OP_JournalMode opcode, and
45893   ** the logic there will never allow a temporary file to be changed
45894   ** to WAL mode.
45895   */
45896   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
45897
45898   /* Do allow the journalmode of an in-memory database to be set to
45899   ** anything other than MEMORY or OFF
45900   */
45901   if( MEMDB ){
45902     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
45903     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
45904       eMode = eOld;
45905     }
45906   }
45907
45908   if( eMode!=eOld ){
45909
45910     /* Change the journal mode. */
45911     assert( pPager->eState!=PAGER_ERROR );
45912     pPager->journalMode = (u8)eMode;
45913
45914     /* When transistioning from TRUNCATE or PERSIST to any other journal
45915     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
45916     ** delete the journal file.
45917     */
45918     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
45919     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
45920     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
45921     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
45922     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
45923     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
45924
45925     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
45926     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
45927
45928       /* In this case we would like to delete the journal file. If it is
45929       ** not possible, then that is not a problem. Deleting the journal file
45930       ** here is an optimization only.
45931       **
45932       ** Before deleting the journal file, obtain a RESERVED lock on the
45933       ** database file. This ensures that the journal file is not deleted
45934       ** while it is in use by some other client.
45935       */
45936       sqlcipher3OsClose(pPager->jfd);
45937       if( pPager->eLock>=RESERVED_LOCK ){
45938         sqlcipher3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45939       }else{
45940         int rc = SQLCIPHER_OK;
45941         int state = pPager->eState;
45942         assert( state==PAGER_OPEN || state==PAGER_READER );
45943         if( state==PAGER_OPEN ){
45944           rc = sqlcipher3PagerSharedLock(pPager);
45945         }
45946         if( pPager->eState==PAGER_READER ){
45947           assert( rc==SQLCIPHER_OK );
45948           rc = pagerLockDb(pPager, RESERVED_LOCK);
45949         }
45950         if( rc==SQLCIPHER_OK ){
45951           sqlcipher3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45952         }
45953         if( rc==SQLCIPHER_OK && state==PAGER_READER ){
45954           pagerUnlockDb(pPager, SHARED_LOCK);
45955         }else if( state==PAGER_OPEN ){
45956           pager_unlock(pPager);
45957         }
45958         assert( state==pPager->eState );
45959       }
45960     }
45961   }
45962
45963   /* Return the new journal mode */
45964   return (int)pPager->journalMode;
45965 }
45966
45967 /*
45968 ** Return the current journal mode.
45969 */
45970 SQLCIPHER_PRIVATE int sqlcipher3PagerGetJournalMode(Pager *pPager){
45971   return (int)pPager->journalMode;
45972 }
45973
45974 /*
45975 ** Return TRUE if the pager is in a state where it is OK to change the
45976 ** journalmode.  Journalmode changes can only happen when the database
45977 ** is unmodified.
45978 */
45979 SQLCIPHER_PRIVATE int sqlcipher3PagerOkToChangeJournalMode(Pager *pPager){
45980   assert( assert_pager_state(pPager) );
45981   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
45982   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
45983   return 1;
45984 }
45985
45986 /*
45987 ** Get/set the size-limit used for persistent journal files.
45988 **
45989 ** Setting the size limit to -1 means no limit is enforced.
45990 ** An attempt to set a limit smaller than -1 is a no-op.
45991 */
45992 SQLCIPHER_PRIVATE i64 sqlcipher3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
45993   if( iLimit>=-1 ){
45994     pPager->journalSizeLimit = iLimit;
45995     sqlcipher3WalLimit(pPager->pWal, iLimit);
45996   }
45997   return pPager->journalSizeLimit;
45998 }
45999
46000 /*
46001 ** Return a pointer to the pPager->pBackup variable. The backup module
46002 ** in backup.c maintains the content of this variable. This module
46003 ** uses it opaquely as an argument to sqlcipher3BackupRestart() and
46004 ** sqlcipher3BackupUpdate() only.
46005 */
46006 SQLCIPHER_PRIVATE sqlcipher3_backup **sqlcipher3PagerBackupPtr(Pager *pPager){
46007   return &pPager->pBackup;
46008 }
46009
46010 #ifndef SQLCIPHER_OMIT_WAL
46011 /*
46012 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
46013 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlcipher3_wal_checkpoint()
46014 ** or wal_blocking_checkpoint() API functions.
46015 **
46016 ** Parameter eMode is one of SQLCIPHER_CHECKPOINT_PASSIVE, FULL or RESTART.
46017 */
46018 SQLCIPHER_PRIVATE int sqlcipher3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
46019   int rc = SQLCIPHER_OK;
46020   if( pPager->pWal ){
46021     rc = sqlcipher3WalCheckpoint(pPager->pWal, eMode,
46022         pPager->xBusyHandler, pPager->pBusyHandlerArg,
46023         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
46024         pnLog, pnCkpt
46025     );
46026   }
46027   return rc;
46028 }
46029
46030 SQLCIPHER_PRIVATE int sqlcipher3PagerWalCallback(Pager *pPager){
46031   return sqlcipher3WalCallback(pPager->pWal);
46032 }
46033
46034 /*
46035 ** Return true if the underlying VFS for the given pager supports the
46036 ** primitives necessary for write-ahead logging.
46037 */
46038 SQLCIPHER_PRIVATE int sqlcipher3PagerWalSupported(Pager *pPager){
46039   const sqlcipher3_io_methods *pMethods = pPager->fd->pMethods;
46040   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
46041 }
46042
46043 /*
46044 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
46045 ** is obtained instead, immediately release it.
46046 */
46047 static int pagerExclusiveLock(Pager *pPager){
46048   int rc;                         /* Return code */
46049
46050   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
46051   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
46052   if( rc!=SQLCIPHER_OK ){
46053     /* If the attempt to grab the exclusive lock failed, release the 
46054     ** pending lock that may have been obtained instead.  */
46055     pagerUnlockDb(pPager, SHARED_LOCK);
46056   }
46057
46058   return rc;
46059 }
46060
46061 /*
46062 ** Call sqlcipher3WalOpen() to open the WAL handle. If the pager is in 
46063 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
46064 ** lock on the database file and use heap-memory to store the wal-index
46065 ** in. Otherwise, use the normal shared-memory.
46066 */
46067 static int pagerOpenWal(Pager *pPager){
46068   int rc = SQLCIPHER_OK;
46069
46070   assert( pPager->pWal==0 && pPager->tempFile==0 );
46071   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
46072
46073   /* If the pager is already in exclusive-mode, the WAL module will use 
46074   ** heap-memory for the wal-index instead of the VFS shared-memory 
46075   ** implementation. Take the exclusive lock now, before opening the WAL
46076   ** file, to make sure this is safe.
46077   */
46078   if( pPager->exclusiveMode ){
46079     rc = pagerExclusiveLock(pPager);
46080   }
46081
46082   /* Open the connection to the log file. If this operation fails, 
46083   ** (e.g. due to malloc() failure), return an error code.
46084   */
46085   if( rc==SQLCIPHER_OK ){
46086     rc = sqlcipher3WalOpen(pPager->pVfs, 
46087         pPager->fd, pPager->zWal, pPager->exclusiveMode,
46088         pPager->journalSizeLimit, &pPager->pWal
46089     );
46090   }
46091
46092   return rc;
46093 }
46094
46095
46096 /*
46097 ** The caller must be holding a SHARED lock on the database file to call
46098 ** this function.
46099 **
46100 ** If the pager passed as the first argument is open on a real database
46101 ** file (not a temp file or an in-memory database), and the WAL file
46102 ** is not already open, make an attempt to open it now. If successful,
46103 ** return SQLCIPHER_OK. If an error occurs or the VFS used by the pager does 
46104 ** not support the xShmXXX() methods, return an error code. *pbOpen is
46105 ** not modified in either case.
46106 **
46107 ** If the pager is open on a temp-file (or in-memory database), or if
46108 ** the WAL file is already open, set *pbOpen to 1 and return SQLCIPHER_OK
46109 ** without doing anything.
46110 */
46111 SQLCIPHER_PRIVATE int sqlcipher3PagerOpenWal(
46112   Pager *pPager,                  /* Pager object */
46113   int *pbOpen                     /* OUT: Set to true if call is a no-op */
46114 ){
46115   int rc = SQLCIPHER_OK;             /* Return code */
46116
46117   assert( assert_pager_state(pPager) );
46118   assert( pPager->eState==PAGER_OPEN   || pbOpen );
46119   assert( pPager->eState==PAGER_READER || !pbOpen );
46120   assert( pbOpen==0 || *pbOpen==0 );
46121   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
46122
46123   if( !pPager->tempFile && !pPager->pWal ){
46124     if( !sqlcipher3PagerWalSupported(pPager) ) return SQLCIPHER_CANTOPEN;
46125
46126     /* Close any rollback journal previously open */
46127     sqlcipher3OsClose(pPager->jfd);
46128
46129     rc = pagerOpenWal(pPager);
46130     if( rc==SQLCIPHER_OK ){
46131       pPager->journalMode = PAGER_JOURNALMODE_WAL;
46132       pPager->eState = PAGER_OPEN;
46133     }
46134   }else{
46135     *pbOpen = 1;
46136   }
46137
46138   return rc;
46139 }
46140
46141 /*
46142 ** This function is called to close the connection to the log file prior
46143 ** to switching from WAL to rollback mode.
46144 **
46145 ** Before closing the log file, this function attempts to take an 
46146 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
46147 ** error (SQLCIPHER_BUSY) is returned and the log connection is not closed.
46148 ** If successful, the EXCLUSIVE lock is not released before returning.
46149 */
46150 SQLCIPHER_PRIVATE int sqlcipher3PagerCloseWal(Pager *pPager){
46151   int rc = SQLCIPHER_OK;
46152
46153   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
46154
46155   /* If the log file is not already open, but does exist in the file-system,
46156   ** it may need to be checkpointed before the connection can switch to
46157   ** rollback mode. Open it now so this can happen.
46158   */
46159   if( !pPager->pWal ){
46160     int logexists = 0;
46161     rc = pagerLockDb(pPager, SHARED_LOCK);
46162     if( rc==SQLCIPHER_OK ){
46163       rc = sqlcipher3OsAccess(
46164           pPager->pVfs, pPager->zWal, SQLCIPHER_ACCESS_EXISTS, &logexists
46165       );
46166     }
46167     if( rc==SQLCIPHER_OK && logexists ){
46168       rc = pagerOpenWal(pPager);
46169     }
46170   }
46171     
46172   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
46173   ** the database file, the log and log-summary files will be deleted.
46174   */
46175   if( rc==SQLCIPHER_OK && pPager->pWal ){
46176     rc = pagerExclusiveLock(pPager);
46177     if( rc==SQLCIPHER_OK ){
46178       rc = sqlcipher3WalClose(pPager->pWal, pPager->ckptSyncFlags,
46179                            pPager->pageSize, (u8*)pPager->pTmpSpace);
46180       pPager->pWal = 0;
46181     }
46182   }
46183   return rc;
46184 }
46185
46186 /*
46187 ** Unless this is an in-memory or temporary database, clear the pager cache.
46188 */
46189 SQLCIPHER_PRIVATE void sqlcipher3PagerClearCache(Pager *pPager){
46190   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
46191 }
46192
46193 #ifdef SQLCIPHER_HAS_CODEC
46194 /*
46195 ** This function is called by the wal module when writing page content
46196 ** into the log file.
46197 **
46198 ** This function returns a pointer to a buffer containing the encrypted
46199 ** page content. If a malloc fails, this function may return NULL.
46200 */
46201 SQLCIPHER_PRIVATE void *sqlcipher3PagerCodec(PgHdr *pPg){
46202   void *aData = 0;
46203   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
46204   return aData;
46205 }
46206 #endif /* SQLCIPHER_HAS_CODEC */
46207
46208 #endif /* !SQLCIPHER_OMIT_WAL */
46209
46210 #endif /* SQLCIPHER_OMIT_DISKIO */
46211
46212 /* BEGIN CRYPTO */
46213 #ifdef SQLCIPHER_HAS_CODEC
46214 SQLCIPHER_PRIVATE void sqlcipher3pager_get_codec(Pager *pPager, void **ctx) {
46215   *ctx = pPager->pCodec;
46216 }
46217
46218 SQLCIPHER_PRIVATE int sqlcipher3pager_is_mj_pgno(Pager *pPager, Pgno pgno) {
46219   return (PAGER_MJ_PGNO(pPager) == pgno) ? 1 : 0;
46220 }
46221
46222 SQLCIPHER_PRIVATE sqlcipher3_file *sqlcipher3Pager_get_fd(Pager *pPager) {
46223   return (isOpen(pPager->fd)) ? pPager->fd : NULL;
46224 }
46225
46226 SQLCIPHER_PRIVATE void sqlcipher3pager_sqlcipher3PagerSetCodec(
46227   Pager *pPager,
46228   void *(*xCodec)(void*,void*,Pgno,int),
46229   void (*xCodecSizeChng)(void*,int,int),
46230   void (*xCodecFree)(void*),
46231   void *pCodec
46232 ){
46233   sqlcipher3PagerSetCodec(pPager, xCodec, xCodecSizeChng, xCodecFree, pCodec); 
46234 }
46235
46236
46237 #endif
46238 /* END CRYPTO */
46239
46240
46241 /************** End of pager.c ***********************************************/
46242 /************** Begin file wal.c *********************************************/
46243 /*
46244 ** 2010 February 1
46245 **
46246 ** The author disclaims copyright to this source code.  In place of
46247 ** a legal notice, here is a blessing:
46248 **
46249 **    May you do good and not evil.
46250 **    May you find forgiveness for yourself and forgive others.
46251 **    May you share freely, never taking more than you give.
46252 **
46253 *************************************************************************
46254 **
46255 ** This file contains the implementation of a write-ahead log (WAL) used in 
46256 ** "journal_mode=WAL" mode.
46257 **
46258 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
46259 **
46260 ** A WAL file consists of a header followed by zero or more "frames".
46261 ** Each frame records the revised content of a single page from the
46262 ** database file.  All changes to the database are recorded by writing
46263 ** frames into the WAL.  Transactions commit when a frame is written that
46264 ** contains a commit marker.  A single WAL can and usually does record 
46265 ** multiple transactions.  Periodically, the content of the WAL is
46266 ** transferred back into the database file in an operation called a
46267 ** "checkpoint".
46268 **
46269 ** A single WAL file can be used multiple times.  In other words, the
46270 ** WAL can fill up with frames and then be checkpointed and then new
46271 ** frames can overwrite the old ones.  A WAL always grows from beginning
46272 ** toward the end.  Checksums and counters attached to each frame are
46273 ** used to determine which frames within the WAL are valid and which
46274 ** are leftovers from prior checkpoints.
46275 **
46276 ** The WAL header is 32 bytes in size and consists of the following eight
46277 ** big-endian 32-bit unsigned integer values:
46278 **
46279 **     0: Magic number.  0x377f0682 or 0x377f0683
46280 **     4: File format version.  Currently 3007000
46281 **     8: Database page size.  Example: 1024
46282 **    12: Checkpoint sequence number
46283 **    16: Salt-1, random integer incremented with each checkpoint
46284 **    20: Salt-2, a different random integer changing with each ckpt
46285 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
46286 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
46287 **
46288 ** Immediately following the wal-header are zero or more frames. Each
46289 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
46290 ** of page data. The frame-header is six big-endian 32-bit unsigned 
46291 ** integer values, as follows:
46292 **
46293 **     0: Page number.
46294 **     4: For commit records, the size of the database image in pages 
46295 **        after the commit. For all other records, zero.
46296 **     8: Salt-1 (copied from the header)
46297 **    12: Salt-2 (copied from the header)
46298 **    16: Checksum-1.
46299 **    20: Checksum-2.
46300 **
46301 ** A frame is considered valid if and only if the following conditions are
46302 ** true:
46303 **
46304 **    (1) The salt-1 and salt-2 values in the frame-header match
46305 **        salt values in the wal-header
46306 **
46307 **    (2) The checksum values in the final 8 bytes of the frame-header
46308 **        exactly match the checksum computed consecutively on the
46309 **        WAL header and the first 8 bytes and the content of all frames
46310 **        up to and including the current frame.
46311 **
46312 ** The checksum is computed using 32-bit big-endian integers if the
46313 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
46314 ** is computed using little-endian if the magic number is 0x377f0682.
46315 ** The checksum values are always stored in the frame header in a
46316 ** big-endian format regardless of which byte order is used to compute
46317 ** the checksum.  The checksum is computed by interpreting the input as
46318 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
46319 ** algorithm used for the checksum is as follows:
46320 ** 
46321 **   for i from 0 to n-1 step 2:
46322 **     s0 += x[i] + s1;
46323 **     s1 += x[i+1] + s0;
46324 **   endfor
46325 **
46326 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
46327 ** in reverse order (the largest fibonacci weight occurs on the first element
46328 ** of the sequence being summed.)  The s1 value spans all 32-bit 
46329 ** terms of the sequence whereas s0 omits the final term.
46330 **
46331 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
46332 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
46333 ** The VFS.xSync operations serve as write barriers - all writes launched
46334 ** before the xSync must complete before any write that launches after the
46335 ** xSync begins.
46336 **
46337 ** After each checkpoint, the salt-1 value is incremented and the salt-2
46338 ** value is randomized.  This prevents old and new frames in the WAL from
46339 ** being considered valid at the same time and being checkpointing together
46340 ** following a crash.
46341 **
46342 ** READER ALGORITHM
46343 **
46344 ** To read a page from the database (call it page number P), a reader
46345 ** first checks the WAL to see if it contains page P.  If so, then the
46346 ** last valid instance of page P that is a followed by a commit frame
46347 ** or is a commit frame itself becomes the value read.  If the WAL
46348 ** contains no copies of page P that are valid and which are a commit
46349 ** frame or are followed by a commit frame, then page P is read from
46350 ** the database file.
46351 **
46352 ** To start a read transaction, the reader records the index of the last
46353 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
46354 ** for all subsequent read operations.  New transactions can be appended
46355 ** to the WAL, but as long as the reader uses its original mxFrame value
46356 ** and ignores the newly appended content, it will see a consistent snapshot
46357 ** of the database from a single point in time.  This technique allows
46358 ** multiple concurrent readers to view different versions of the database
46359 ** content simultaneously.
46360 **
46361 ** The reader algorithm in the previous paragraphs works correctly, but 
46362 ** because frames for page P can appear anywhere within the WAL, the
46363 ** reader has to scan the entire WAL looking for page P frames.  If the
46364 ** WAL is large (multiple megabytes is typical) that scan can be slow,
46365 ** and read performance suffers.  To overcome this problem, a separate
46366 ** data structure called the wal-index is maintained to expedite the
46367 ** search for frames of a particular page.
46368 ** 
46369 ** WAL-INDEX FORMAT
46370 **
46371 ** Conceptually, the wal-index is shared memory, though VFS implementations
46372 ** might choose to implement the wal-index using a mmapped file.  Because
46373 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
46374 ** on a network filesystem.  All users of the database must be able to
46375 ** share memory.
46376 **
46377 ** The wal-index is transient.  After a crash, the wal-index can (and should
46378 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
46379 ** to either truncate or zero the header of the wal-index when the last
46380 ** connection to it closes.  Because the wal-index is transient, it can
46381 ** use an architecture-specific format; it does not have to be cross-platform.
46382 ** Hence, unlike the database and WAL file formats which store all values
46383 ** as big endian, the wal-index can store multi-byte values in the native
46384 ** byte order of the host computer.
46385 **
46386 ** The purpose of the wal-index is to answer this question quickly:  Given
46387 ** a page number P, return the index of the last frame for page P in the WAL,
46388 ** or return NULL if there are no frames for page P in the WAL.
46389 **
46390 ** The wal-index consists of a header region, followed by an one or
46391 ** more index blocks.  
46392 **
46393 ** The wal-index header contains the total number of frames within the WAL
46394 ** in the the mxFrame field.  
46395 **
46396 ** Each index block except for the first contains information on 
46397 ** HASHTABLE_NPAGE frames. The first index block contains information on
46398 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
46399 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
46400 ** first index block are the same size as all other index blocks in the
46401 ** wal-index.
46402 **
46403 ** Each index block contains two sections, a page-mapping that contains the
46404 ** database page number associated with each wal frame, and a hash-table 
46405 ** that allows readers to query an index block for a specific page number.
46406 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
46407 ** for the first index block) 32-bit page numbers. The first entry in the 
46408 ** first index-block contains the database page number corresponding to the
46409 ** first frame in the WAL file. The first entry in the second index block
46410 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
46411 ** the log, and so on.
46412 **
46413 ** The last index block in a wal-index usually contains less than the full
46414 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
46415 ** depending on the contents of the WAL file. This does not change the
46416 ** allocated size of the page-mapping array - the page-mapping array merely
46417 ** contains unused entries.
46418 **
46419 ** Even without using the hash table, the last frame for page P
46420 ** can be found by scanning the page-mapping sections of each index block
46421 ** starting with the last index block and moving toward the first, and
46422 ** within each index block, starting at the end and moving toward the
46423 ** beginning.  The first entry that equals P corresponds to the frame
46424 ** holding the content for that page.
46425 **
46426 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
46427 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
46428 ** hash table for each page number in the mapping section, so the hash 
46429 ** table is never more than half full.  The expected number of collisions 
46430 ** prior to finding a match is 1.  Each entry of the hash table is an
46431 ** 1-based index of an entry in the mapping section of the same
46432 ** index block.   Let K be the 1-based index of the largest entry in
46433 ** the mapping section.  (For index blocks other than the last, K will
46434 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
46435 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
46436 ** contain a value of 0.
46437 **
46438 ** To look for page P in the hash table, first compute a hash iKey on
46439 ** P as follows:
46440 **
46441 **      iKey = (P * 383) % HASHTABLE_NSLOT
46442 **
46443 ** Then start scanning entries of the hash table, starting with iKey
46444 ** (wrapping around to the beginning when the end of the hash table is
46445 ** reached) until an unused hash slot is found. Let the first unused slot
46446 ** be at index iUnused.  (iUnused might be less than iKey if there was
46447 ** wrap-around.) Because the hash table is never more than half full,
46448 ** the search is guaranteed to eventually hit an unused entry.  Let 
46449 ** iMax be the value between iKey and iUnused, closest to iUnused,
46450 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
46451 ** no hash slot such that aHash[i]==p) then page P is not in the
46452 ** current index block.  Otherwise the iMax-th mapping entry of the
46453 ** current index block corresponds to the last entry that references 
46454 ** page P.
46455 **
46456 ** A hash search begins with the last index block and moves toward the
46457 ** first index block, looking for entries corresponding to page P.  On
46458 ** average, only two or three slots in each index block need to be
46459 ** examined in order to either find the last entry for page P, or to
46460 ** establish that no such entry exists in the block.  Each index block
46461 ** holds over 4000 entries.  So two or three index blocks are sufficient
46462 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
46463 ** comparisons (on average) suffice to either locate a frame in the
46464 ** WAL or to establish that the frame does not exist in the WAL.  This
46465 ** is much faster than scanning the entire 10MB WAL.
46466 **
46467 ** Note that entries are added in order of increasing K.  Hence, one
46468 ** reader might be using some value K0 and a second reader that started
46469 ** at a later time (after additional transactions were added to the WAL
46470 ** and to the wal-index) might be using a different value K1, where K1>K0.
46471 ** Both readers can use the same hash table and mapping section to get
46472 ** the correct result.  There may be entries in the hash table with
46473 ** K>K0 but to the first reader, those entries will appear to be unused
46474 ** slots in the hash table and so the first reader will get an answer as
46475 ** if no values greater than K0 had ever been inserted into the hash table
46476 ** in the first place - which is what reader one wants.  Meanwhile, the
46477 ** second reader using K1 will see additional values that were inserted
46478 ** later, which is exactly what reader two wants.  
46479 **
46480 ** When a rollback occurs, the value of K is decreased. Hash table entries
46481 ** that correspond to frames greater than the new K value are removed
46482 ** from the hash table at this point.
46483 */
46484 #ifndef SQLCIPHER_OMIT_WAL
46485
46486
46487 /*
46488 ** Trace output macros
46489 */
46490 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
46491 SQLCIPHER_PRIVATE int sqlcipher3WalTrace = 0;
46492 # define WALTRACE(X)  if(sqlcipher3WalTrace) sqlcipher3DebugPrintf X
46493 #else
46494 # define WALTRACE(X)
46495 #endif
46496
46497 /*
46498 ** The maximum (and only) versions of the wal and wal-index formats
46499 ** that may be interpreted by this version of SQLite.
46500 **
46501 ** If a client begins recovering a WAL file and finds that (a) the checksum
46502 ** values in the wal-header are correct and (b) the version field is not
46503 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLCIPHER_CANTOPEN.
46504 **
46505 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
46506 ** checksum test is successful) and finds that the version field is not
46507 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
46508 ** returns SQLCIPHER_CANTOPEN.
46509 */
46510 #define WAL_MAX_VERSION      3007000
46511 #define WALINDEX_MAX_VERSION 3007000
46512
46513 /*
46514 ** Indices of various locking bytes.   WAL_NREADER is the number
46515 ** of available reader locks and should be at least 3.
46516 */
46517 #define WAL_WRITE_LOCK         0
46518 #define WAL_ALL_BUT_WRITE      1
46519 #define WAL_CKPT_LOCK          1
46520 #define WAL_RECOVER_LOCK       2
46521 #define WAL_READ_LOCK(I)       (3+(I))
46522 #define WAL_NREADER            (SQLCIPHER_SHM_NLOCK-3)
46523
46524
46525 /* Object declarations */
46526 typedef struct WalIndexHdr WalIndexHdr;
46527 typedef struct WalIterator WalIterator;
46528 typedef struct WalCkptInfo WalCkptInfo;
46529
46530
46531 /*
46532 ** The following object holds a copy of the wal-index header content.
46533 **
46534 ** The actual header in the wal-index consists of two copies of this
46535 ** object.
46536 **
46537 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
46538 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
46539 ** added in 3.7.1 when support for 64K pages was added.  
46540 */
46541 struct WalIndexHdr {
46542   u32 iVersion;                   /* Wal-index version */
46543   u32 unused;                     /* Unused (padding) field */
46544   u32 iChange;                    /* Counter incremented each transaction */
46545   u8 isInit;                      /* 1 when initialized */
46546   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
46547   u16 szPage;                     /* Database page size in bytes. 1==64K */
46548   u32 mxFrame;                    /* Index of last valid frame in the WAL */
46549   u32 nPage;                      /* Size of database in pages */
46550   u32 aFrameCksum[2];             /* Checksum of last frame in log */
46551   u32 aSalt[2];                   /* Two salt values copied from WAL header */
46552   u32 aCksum[2];                  /* Checksum over all prior fields */
46553 };
46554
46555 /*
46556 ** A copy of the following object occurs in the wal-index immediately
46557 ** following the second copy of the WalIndexHdr.  This object stores
46558 ** information used by checkpoint.
46559 **
46560 ** nBackfill is the number of frames in the WAL that have been written
46561 ** back into the database. (We call the act of moving content from WAL to
46562 ** database "backfilling".)  The nBackfill number is never greater than
46563 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
46564 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
46565 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
46566 ** mxFrame back to zero when the WAL is reset.
46567 **
46568 ** There is one entry in aReadMark[] for each reader lock.  If a reader
46569 ** holds read-lock K, then the value in aReadMark[K] is no greater than
46570 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
46571 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
46572 ** a special case; its value is never used and it exists as a place-holder
46573 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
46574 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
46575 ** directly from the database.
46576 **
46577 ** The value of aReadMark[K] may only be changed by a thread that
46578 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
46579 ** aReadMark[K] cannot changed while there is a reader is using that mark
46580 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
46581 **
46582 ** The checkpointer may only transfer frames from WAL to database where
46583 ** the frame numbers are less than or equal to every aReadMark[] that is
46584 ** in use (that is, every aReadMark[j] for which there is a corresponding
46585 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
46586 ** largest value and will increase an unused aReadMark[] to mxFrame if there
46587 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
46588 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
46589 ** in the WAL has been backfilled into the database) then new readers
46590 ** will choose aReadMark[0] which has value 0 and hence such reader will
46591 ** get all their all content directly from the database file and ignore 
46592 ** the WAL.
46593 **
46594 ** Writers normally append new frames to the end of the WAL.  However,
46595 ** if nBackfill equals mxFrame (meaning that all WAL content has been
46596 ** written back into the database) and if no readers are using the WAL
46597 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
46598 ** the writer will first "reset" the WAL back to the beginning and start
46599 ** writing new content beginning at frame 1.
46600 **
46601 ** We assume that 32-bit loads are atomic and so no locks are needed in
46602 ** order to read from any aReadMark[] entries.
46603 */
46604 struct WalCkptInfo {
46605   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
46606   u32 aReadMark[WAL_NREADER];     /* Reader marks */
46607 };
46608 #define READMARK_NOT_USED  0xffffffff
46609
46610
46611 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
46612 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
46613 ** only support mandatory file-locks, we do not read or write data
46614 ** from the region of the file on which locks are applied.
46615 */
46616 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
46617 #define WALINDEX_LOCK_RESERVED 16
46618 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
46619
46620 /* Size of header before each frame in wal */
46621 #define WAL_FRAME_HDRSIZE 24
46622
46623 /* Size of write ahead log header, including checksum. */
46624 /* #define WAL_HDRSIZE 24 */
46625 #define WAL_HDRSIZE 32
46626
46627 /* WAL magic value. Either this value, or the same value with the least
46628 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
46629 ** big-endian format in the first 4 bytes of a WAL file.
46630 **
46631 ** If the LSB is set, then the checksums for each frame within the WAL
46632 ** file are calculated by treating all data as an array of 32-bit 
46633 ** big-endian words. Otherwise, they are calculated by interpreting 
46634 ** all data as 32-bit little-endian words.
46635 */
46636 #define WAL_MAGIC 0x377f0682
46637
46638 /*
46639 ** Return the offset of frame iFrame in the write-ahead log file, 
46640 ** assuming a database page size of szPage bytes. The offset returned
46641 ** is to the start of the write-ahead log frame-header.
46642 */
46643 #define walFrameOffset(iFrame, szPage) (                               \
46644   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
46645 )
46646
46647 /*
46648 ** An open write-ahead log file is represented by an instance of the
46649 ** following object.
46650 */
46651 struct Wal {
46652   sqlcipher3_vfs *pVfs;         /* The VFS used to create pDbFd */
46653   sqlcipher3_file *pDbFd;       /* File handle for the database file */
46654   sqlcipher3_file *pWalFd;      /* File handle for WAL file */
46655   u32 iCallback;             /* Value to pass to log callback (or 0) */
46656   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
46657   int nWiData;               /* Size of array apWiData */
46658   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
46659   u32 szPage;                /* Database page size */
46660   i16 readLock;              /* Which read lock is being held.  -1 for none */
46661   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
46662   u8 writeLock;              /* True if in a write transaction */
46663   u8 ckptLock;               /* True if holding a checkpoint lock */
46664   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
46665   WalIndexHdr hdr;           /* Wal-index header for current transaction */
46666   const char *zWalName;      /* Name of WAL file */
46667   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
46668 #ifdef SQLCIPHER_DEBUG
46669   u8 lockError;              /* True if a locking error has occurred */
46670 #endif
46671 };
46672
46673 /*
46674 ** Candidate values for Wal.exclusiveMode.
46675 */
46676 #define WAL_NORMAL_MODE     0
46677 #define WAL_EXCLUSIVE_MODE  1     
46678 #define WAL_HEAPMEMORY_MODE 2
46679
46680 /*
46681 ** Possible values for WAL.readOnly
46682 */
46683 #define WAL_RDWR        0    /* Normal read/write connection */
46684 #define WAL_RDONLY      1    /* The WAL file is readonly */
46685 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
46686
46687 /*
46688 ** Each page of the wal-index mapping contains a hash-table made up of
46689 ** an array of HASHTABLE_NSLOT elements of the following type.
46690 */
46691 typedef u16 ht_slot;
46692
46693 /*
46694 ** This structure is used to implement an iterator that loops through
46695 ** all frames in the WAL in database page order. Where two or more frames
46696 ** correspond to the same database page, the iterator visits only the 
46697 ** frame most recently written to the WAL (in other words, the frame with
46698 ** the largest index).
46699 **
46700 ** The internals of this structure are only accessed by:
46701 **
46702 **   walIteratorInit() - Create a new iterator,
46703 **   walIteratorNext() - Step an iterator,
46704 **   walIteratorFree() - Free an iterator.
46705 **
46706 ** This functionality is used by the checkpoint code (see walCheckpoint()).
46707 */
46708 struct WalIterator {
46709   int iPrior;                     /* Last result returned from the iterator */
46710   int nSegment;                   /* Number of entries in aSegment[] */
46711   struct WalSegment {
46712     int iNext;                    /* Next slot in aIndex[] not yet returned */
46713     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
46714     u32 *aPgno;                   /* Array of page numbers. */
46715     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
46716     int iZero;                    /* Frame number associated with aPgno[0] */
46717   } aSegment[1];                  /* One for every 32KB page in the wal-index */
46718 };
46719
46720 /*
46721 ** Define the parameters of the hash tables in the wal-index file. There
46722 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
46723 ** wal-index.
46724 **
46725 ** Changing any of these constants will alter the wal-index format and
46726 ** create incompatibilities.
46727 */
46728 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
46729 #define HASHTABLE_HASH_1     383                  /* Should be prime */
46730 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
46731
46732 /* 
46733 ** The block of page numbers associated with the first hash-table in a
46734 ** wal-index is smaller than usual. This is so that there is a complete
46735 ** hash-table on each aligned 32KB page of the wal-index.
46736 */
46737 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
46738
46739 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
46740 #define WALINDEX_PGSZ   (                                         \
46741     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
46742 )
46743
46744 /*
46745 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
46746 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
46747 ** numbered from zero.
46748 **
46749 ** If this call is successful, *ppPage is set to point to the wal-index
46750 ** page and SQLCIPHER_OK is returned. If an error (an OOM or VFS error) occurs,
46751 ** then an SQLite error code is returned and *ppPage is set to 0.
46752 */
46753 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
46754   int rc = SQLCIPHER_OK;
46755
46756   /* Enlarge the pWal->apWiData[] array if required */
46757   if( pWal->nWiData<=iPage ){
46758     int nByte = sizeof(u32*)*(iPage+1);
46759     volatile u32 **apNew;
46760     apNew = (volatile u32 **)sqlcipher3_realloc((void *)pWal->apWiData, nByte);
46761     if( !apNew ){
46762       *ppPage = 0;
46763       return SQLCIPHER_NOMEM;
46764     }
46765     memset((void*)&apNew[pWal->nWiData], 0,
46766            sizeof(u32*)*(iPage+1-pWal->nWiData));
46767     pWal->apWiData = apNew;
46768     pWal->nWiData = iPage+1;
46769   }
46770
46771   /* Request a pointer to the required page from the VFS */
46772   if( pWal->apWiData[iPage]==0 ){
46773     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
46774       pWal->apWiData[iPage] = (u32 volatile *)sqlcipher3MallocZero(WALINDEX_PGSZ);
46775       if( !pWal->apWiData[iPage] ) rc = SQLCIPHER_NOMEM;
46776     }else{
46777       rc = sqlcipher3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
46778           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
46779       );
46780       if( rc==SQLCIPHER_READONLY ){
46781         pWal->readOnly |= WAL_SHM_RDONLY;
46782         rc = SQLCIPHER_OK;
46783       }
46784     }
46785   }
46786
46787   *ppPage = pWal->apWiData[iPage];
46788   assert( iPage==0 || *ppPage || rc!=SQLCIPHER_OK );
46789   return rc;
46790 }
46791
46792 /*
46793 ** Return a pointer to the WalCkptInfo structure in the wal-index.
46794 */
46795 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
46796   assert( pWal->nWiData>0 && pWal->apWiData[0] );
46797   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
46798 }
46799
46800 /*
46801 ** Return a pointer to the WalIndexHdr structure in the wal-index.
46802 */
46803 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
46804   assert( pWal->nWiData>0 && pWal->apWiData[0] );
46805   return (volatile WalIndexHdr*)pWal->apWiData[0];
46806 }
46807
46808 /*
46809 ** The argument to this macro must be of type u32. On a little-endian
46810 ** architecture, it returns the u32 value that results from interpreting
46811 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
46812 ** returns the value that would be produced by intepreting the 4 bytes
46813 ** of the input value as a little-endian integer.
46814 */
46815 #define BYTESWAP32(x) ( \
46816     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
46817   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
46818 )
46819
46820 /*
46821 ** Generate or extend an 8 byte checksum based on the data in 
46822 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
46823 ** initial values of 0 and 0 if aIn==NULL).
46824 **
46825 ** The checksum is written back into aOut[] before returning.
46826 **
46827 ** nByte must be a positive multiple of 8.
46828 */
46829 static void walChecksumBytes(
46830   int nativeCksum, /* True for native byte-order, false for non-native */
46831   u8 *a,           /* Content to be checksummed */
46832   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
46833   const u32 *aIn,  /* Initial checksum value input */
46834   u32 *aOut        /* OUT: Final checksum value output */
46835 ){
46836   u32 s1, s2;
46837   u32 *aData = (u32 *)a;
46838   u32 *aEnd = (u32 *)&a[nByte];
46839
46840   if( aIn ){
46841     s1 = aIn[0];
46842     s2 = aIn[1];
46843   }else{
46844     s1 = s2 = 0;
46845   }
46846
46847   assert( nByte>=8 );
46848   assert( (nByte&0x00000007)==0 );
46849
46850   if( nativeCksum ){
46851     do {
46852       s1 += *aData++ + s2;
46853       s2 += *aData++ + s1;
46854     }while( aData<aEnd );
46855   }else{
46856     do {
46857       s1 += BYTESWAP32(aData[0]) + s2;
46858       s2 += BYTESWAP32(aData[1]) + s1;
46859       aData += 2;
46860     }while( aData<aEnd );
46861   }
46862
46863   aOut[0] = s1;
46864   aOut[1] = s2;
46865 }
46866
46867 static void walShmBarrier(Wal *pWal){
46868   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
46869     sqlcipher3OsShmBarrier(pWal->pDbFd);
46870   }
46871 }
46872
46873 /*
46874 ** Write the header information in pWal->hdr into the wal-index.
46875 **
46876 ** The checksum on pWal->hdr is updated before it is written.
46877 */
46878 static void walIndexWriteHdr(Wal *pWal){
46879   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
46880   const int nCksum = offsetof(WalIndexHdr, aCksum);
46881
46882   assert( pWal->writeLock );
46883   pWal->hdr.isInit = 1;
46884   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
46885   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
46886   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
46887   walShmBarrier(pWal);
46888   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
46889 }
46890
46891 /*
46892 ** This function encodes a single frame header and writes it to a buffer
46893 ** supplied by the caller. A frame-header is made up of a series of 
46894 ** 4-byte big-endian integers, as follows:
46895 **
46896 **     0: Page number.
46897 **     4: For commit records, the size of the database image in pages 
46898 **        after the commit. For all other records, zero.
46899 **     8: Salt-1 (copied from the wal-header)
46900 **    12: Salt-2 (copied from the wal-header)
46901 **    16: Checksum-1.
46902 **    20: Checksum-2.
46903 */
46904 static void walEncodeFrame(
46905   Wal *pWal,                      /* The write-ahead log */
46906   u32 iPage,                      /* Database page number for frame */
46907   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
46908   u8 *aData,                      /* Pointer to page data */
46909   u8 *aFrame                      /* OUT: Write encoded frame here */
46910 ){
46911   int nativeCksum;                /* True for native byte-order checksums */
46912   u32 *aCksum = pWal->hdr.aFrameCksum;
46913   assert( WAL_FRAME_HDRSIZE==24 );
46914   sqlcipher3Put4byte(&aFrame[0], iPage);
46915   sqlcipher3Put4byte(&aFrame[4], nTruncate);
46916   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
46917
46918   nativeCksum = (pWal->hdr.bigEndCksum==SQLCIPHER_BIGENDIAN);
46919   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46920   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46921
46922   sqlcipher3Put4byte(&aFrame[16], aCksum[0]);
46923   sqlcipher3Put4byte(&aFrame[20], aCksum[1]);
46924 }
46925
46926 /*
46927 ** Check to see if the frame with header in aFrame[] and content
46928 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
46929 ** *pnTruncate and return true.  Return if the frame is not valid.
46930 */
46931 static int walDecodeFrame(
46932   Wal *pWal,                      /* The write-ahead log */
46933   u32 *piPage,                    /* OUT: Database page number for frame */
46934   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
46935   u8 *aData,                      /* Pointer to page data (for checksum) */
46936   u8 *aFrame                      /* Frame data */
46937 ){
46938   int nativeCksum;                /* True for native byte-order checksums */
46939   u32 *aCksum = pWal->hdr.aFrameCksum;
46940   u32 pgno;                       /* Page number of the frame */
46941   assert( WAL_FRAME_HDRSIZE==24 );
46942
46943   /* A frame is only valid if the salt values in the frame-header
46944   ** match the salt values in the wal-header. 
46945   */
46946   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
46947     return 0;
46948   }
46949
46950   /* A frame is only valid if the page number is creater than zero.
46951   */
46952   pgno = sqlcipher3Get4byte(&aFrame[0]);
46953   if( pgno==0 ){
46954     return 0;
46955   }
46956
46957   /* A frame is only valid if a checksum of the WAL header,
46958   ** all prior frams, the first 16 bytes of this frame-header, 
46959   ** and the frame-data matches the checksum in the last 8 
46960   ** bytes of this frame-header.
46961   */
46962   nativeCksum = (pWal->hdr.bigEndCksum==SQLCIPHER_BIGENDIAN);
46963   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46964   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46965   if( aCksum[0]!=sqlcipher3Get4byte(&aFrame[16]) 
46966    || aCksum[1]!=sqlcipher3Get4byte(&aFrame[20]) 
46967   ){
46968     /* Checksum failed. */
46969     return 0;
46970   }
46971
46972   /* If we reach this point, the frame is valid.  Return the page number
46973   ** and the new database size.
46974   */
46975   *piPage = pgno;
46976   *pnTruncate = sqlcipher3Get4byte(&aFrame[4]);
46977   return 1;
46978 }
46979
46980
46981 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
46982 /*
46983 ** Names of locks.  This routine is used to provide debugging output and is not
46984 ** a part of an ordinary build.
46985 */
46986 static const char *walLockName(int lockIdx){
46987   if( lockIdx==WAL_WRITE_LOCK ){
46988     return "WRITE-LOCK";
46989   }else if( lockIdx==WAL_CKPT_LOCK ){
46990     return "CKPT-LOCK";
46991   }else if( lockIdx==WAL_RECOVER_LOCK ){
46992     return "RECOVER-LOCK";
46993   }else{
46994     static char zName[15];
46995     sqlcipher3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
46996                      lockIdx-WAL_READ_LOCK(0));
46997     return zName;
46998   }
46999 }
47000 #endif /*defined(SQLCIPHER_TEST) || defined(SQLCIPHER_DEBUG) */
47001     
47002
47003 /*
47004 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
47005 ** A lock cannot be moved directly between shared and exclusive - it must go
47006 ** through the unlocked state first.
47007 **
47008 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
47009 */
47010 static int walLockShared(Wal *pWal, int lockIdx){
47011   int rc;
47012   if( pWal->exclusiveMode ) return SQLCIPHER_OK;
47013   rc = sqlcipher3OsShmLock(pWal->pDbFd, lockIdx, 1,
47014                         SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_SHARED);
47015   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
47016             walLockName(lockIdx), rc ? "failed" : "ok"));
47017   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLCIPHER_OK && rc!=SQLCIPHER_BUSY); )
47018   return rc;
47019 }
47020 static void walUnlockShared(Wal *pWal, int lockIdx){
47021   if( pWal->exclusiveMode ) return;
47022   (void)sqlcipher3OsShmLock(pWal->pDbFd, lockIdx, 1,
47023                          SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_SHARED);
47024   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
47025 }
47026 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
47027   int rc;
47028   if( pWal->exclusiveMode ) return SQLCIPHER_OK;
47029   rc = sqlcipher3OsShmLock(pWal->pDbFd, lockIdx, n,
47030                         SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_EXCLUSIVE);
47031   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
47032             walLockName(lockIdx), n, rc ? "failed" : "ok"));
47033   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLCIPHER_OK && rc!=SQLCIPHER_BUSY); )
47034   return rc;
47035 }
47036 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
47037   if( pWal->exclusiveMode ) return;
47038   (void)sqlcipher3OsShmLock(pWal->pDbFd, lockIdx, n,
47039                          SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_EXCLUSIVE);
47040   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
47041              walLockName(lockIdx), n));
47042 }
47043
47044 /*
47045 ** Compute a hash on a page number.  The resulting hash value must land
47046 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
47047 ** the hash to the next value in the event of a collision.
47048 */
47049 static int walHash(u32 iPage){
47050   assert( iPage>0 );
47051   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
47052   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
47053 }
47054 static int walNextHash(int iPriorHash){
47055   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
47056 }
47057
47058 /* 
47059 ** Return pointers to the hash table and page number array stored on
47060 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
47061 ** numbered starting from 0.
47062 **
47063 ** Set output variable *paHash to point to the start of the hash table
47064 ** in the wal-index file. Set *piZero to one less than the frame 
47065 ** number of the first frame indexed by this hash table. If a
47066 ** slot in the hash table is set to N, it refers to frame number 
47067 ** (*piZero+N) in the log.
47068 **
47069 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
47070 ** first frame indexed by the hash table, frame (*piZero+1).
47071 */
47072 static int walHashGet(
47073   Wal *pWal,                      /* WAL handle */
47074   int iHash,                      /* Find the iHash'th table */
47075   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
47076   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
47077   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
47078 ){
47079   int rc;                         /* Return code */
47080   volatile u32 *aPgno;
47081
47082   rc = walIndexPage(pWal, iHash, &aPgno);
47083   assert( rc==SQLCIPHER_OK || iHash>0 );
47084
47085   if( rc==SQLCIPHER_OK ){
47086     u32 iZero;
47087     volatile ht_slot *aHash;
47088
47089     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
47090     if( iHash==0 ){
47091       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
47092       iZero = 0;
47093     }else{
47094       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
47095     }
47096   
47097     *paPgno = &aPgno[-1];
47098     *paHash = aHash;
47099     *piZero = iZero;
47100   }
47101   return rc;
47102 }
47103
47104 /*
47105 ** Return the number of the wal-index page that contains the hash-table
47106 ** and page-number array that contain entries corresponding to WAL frame
47107 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
47108 ** are numbered starting from 0.
47109 */
47110 static int walFramePage(u32 iFrame){
47111   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
47112   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
47113        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
47114        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
47115        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
47116        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
47117   );
47118   return iHash;
47119 }
47120
47121 /*
47122 ** Return the page number associated with frame iFrame in this WAL.
47123 */
47124 static u32 walFramePgno(Wal *pWal, u32 iFrame){
47125   int iHash = walFramePage(iFrame);
47126   if( iHash==0 ){
47127     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
47128   }
47129   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
47130 }
47131
47132 /*
47133 ** Remove entries from the hash table that point to WAL slots greater
47134 ** than pWal->hdr.mxFrame.
47135 **
47136 ** This function is called whenever pWal->hdr.mxFrame is decreased due
47137 ** to a rollback or savepoint.
47138 **
47139 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
47140 ** updated.  Any later hash tables will be automatically cleared when
47141 ** pWal->hdr.mxFrame advances to the point where those hash tables are
47142 ** actually needed.
47143 */
47144 static void walCleanupHash(Wal *pWal){
47145   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
47146   volatile u32 *aPgno = 0;        /* Page number array for hash table */
47147   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
47148   int iLimit = 0;                 /* Zero values greater than this */
47149   int nByte;                      /* Number of bytes to zero in aPgno[] */
47150   int i;                          /* Used to iterate through aHash[] */
47151
47152   assert( pWal->writeLock );
47153   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
47154   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
47155   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
47156
47157   if( pWal->hdr.mxFrame==0 ) return;
47158
47159   /* Obtain pointers to the hash-table and page-number array containing 
47160   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
47161   ** that the page said hash-table and array reside on is already mapped.
47162   */
47163   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
47164   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
47165   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
47166
47167   /* Zero all hash-table entries that correspond to frame numbers greater
47168   ** than pWal->hdr.mxFrame.
47169   */
47170   iLimit = pWal->hdr.mxFrame - iZero;
47171   assert( iLimit>0 );
47172   for(i=0; i<HASHTABLE_NSLOT; i++){
47173     if( aHash[i]>iLimit ){
47174       aHash[i] = 0;
47175     }
47176   }
47177   
47178   /* Zero the entries in the aPgno array that correspond to frames with
47179   ** frame numbers greater than pWal->hdr.mxFrame. 
47180   */
47181   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
47182   memset((void *)&aPgno[iLimit+1], 0, nByte);
47183
47184 #ifdef SQLCIPHER_ENABLE_EXPENSIVE_ASSERT
47185   /* Verify that the every entry in the mapping region is still reachable
47186   ** via the hash table even after the cleanup.
47187   */
47188   if( iLimit ){
47189     int i;           /* Loop counter */
47190     int iKey;        /* Hash key */
47191     for(i=1; i<=iLimit; i++){
47192       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
47193         if( aHash[iKey]==i ) break;
47194       }
47195       assert( aHash[iKey]==i );
47196     }
47197   }
47198 #endif /* SQLCIPHER_ENABLE_EXPENSIVE_ASSERT */
47199 }
47200
47201
47202 /*
47203 ** Set an entry in the wal-index that will map database page number
47204 ** pPage into WAL frame iFrame.
47205 */
47206 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
47207   int rc;                         /* Return code */
47208   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
47209   volatile u32 *aPgno = 0;        /* Page number array */
47210   volatile ht_slot *aHash = 0;    /* Hash table */
47211
47212   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
47213
47214   /* Assuming the wal-index file was successfully mapped, populate the
47215   ** page number array and hash table entry.
47216   */
47217   if( rc==SQLCIPHER_OK ){
47218     int iKey;                     /* Hash table key */
47219     int idx;                      /* Value to write to hash-table slot */
47220     int nCollide;                 /* Number of hash collisions */
47221
47222     idx = iFrame - iZero;
47223     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
47224     
47225     /* If this is the first entry to be added to this hash-table, zero the
47226     ** entire hash table and aPgno[] array before proceding. 
47227     */
47228     if( idx==1 ){
47229       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
47230       memset((void*)&aPgno[1], 0, nByte);
47231     }
47232
47233     /* If the entry in aPgno[] is already set, then the previous writer
47234     ** must have exited unexpectedly in the middle of a transaction (after
47235     ** writing one or more dirty pages to the WAL to free up memory). 
47236     ** Remove the remnants of that writers uncommitted transaction from 
47237     ** the hash-table before writing any new entries.
47238     */
47239     if( aPgno[idx] ){
47240       walCleanupHash(pWal);
47241       assert( !aPgno[idx] );
47242     }
47243
47244     /* Write the aPgno[] array entry and the hash-table slot. */
47245     nCollide = idx;
47246     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
47247       if( (nCollide--)==0 ) return SQLCIPHER_CORRUPT_BKPT;
47248     }
47249     aPgno[idx] = iPage;
47250     aHash[iKey] = (ht_slot)idx;
47251
47252 #ifdef SQLCIPHER_ENABLE_EXPENSIVE_ASSERT
47253     /* Verify that the number of entries in the hash table exactly equals
47254     ** the number of entries in the mapping region.
47255     */
47256     {
47257       int i;           /* Loop counter */
47258       int nEntry = 0;  /* Number of entries in the hash table */
47259       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
47260       assert( nEntry==idx );
47261     }
47262
47263     /* Verify that the every entry in the mapping region is reachable
47264     ** via the hash table.  This turns out to be a really, really expensive
47265     ** thing to check, so only do this occasionally - not on every
47266     ** iteration.
47267     */
47268     if( (idx&0x3ff)==0 ){
47269       int i;           /* Loop counter */
47270       for(i=1; i<=idx; i++){
47271         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
47272           if( aHash[iKey]==i ) break;
47273         }
47274         assert( aHash[iKey]==i );
47275       }
47276     }
47277 #endif /* SQLCIPHER_ENABLE_EXPENSIVE_ASSERT */
47278   }
47279
47280
47281   return rc;
47282 }
47283
47284
47285 /*
47286 ** Recover the wal-index by reading the write-ahead log file. 
47287 **
47288 ** This routine first tries to establish an exclusive lock on the
47289 ** wal-index to prevent other threads/processes from doing anything
47290 ** with the WAL or wal-index while recovery is running.  The
47291 ** WAL_RECOVER_LOCK is also held so that other threads will know
47292 ** that this thread is running recovery.  If unable to establish
47293 ** the necessary locks, this routine returns SQLCIPHER_BUSY.
47294 */
47295 static int walIndexRecover(Wal *pWal){
47296   int rc;                         /* Return Code */
47297   i64 nSize;                      /* Size of log file */
47298   u32 aFrameCksum[2] = {0, 0};
47299   int iLock;                      /* Lock offset to lock for checkpoint */
47300   int nLock;                      /* Number of locks to hold */
47301
47302   /* Obtain an exclusive lock on all byte in the locking range not already
47303   ** locked by the caller. The caller is guaranteed to have locked the
47304   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
47305   ** If successful, the same bytes that are locked here are unlocked before
47306   ** this function returns.
47307   */
47308   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
47309   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
47310   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
47311   assert( pWal->writeLock );
47312   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
47313   nLock = SQLCIPHER_SHM_NLOCK - iLock;
47314   rc = walLockExclusive(pWal, iLock, nLock);
47315   if( rc ){
47316     return rc;
47317   }
47318   WALTRACE(("WAL%p: recovery begin...\n", pWal));
47319
47320   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
47321
47322   rc = sqlcipher3OsFileSize(pWal->pWalFd, &nSize);
47323   if( rc!=SQLCIPHER_OK ){
47324     goto recovery_error;
47325   }
47326
47327   if( nSize>WAL_HDRSIZE ){
47328     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
47329     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
47330     int szFrame;                  /* Number of bytes in buffer aFrame[] */
47331     u8 *aData;                    /* Pointer to data part of aFrame buffer */
47332     int iFrame;                   /* Index of last frame read */
47333     i64 iOffset;                  /* Next offset to read from log file */
47334     int szPage;                   /* Page size according to the log */
47335     u32 magic;                    /* Magic value read from WAL header */
47336     u32 version;                  /* Magic value read from WAL header */
47337
47338     /* Read in the WAL header. */
47339     rc = sqlcipher3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
47340     if( rc!=SQLCIPHER_OK ){
47341       goto recovery_error;
47342     }
47343
47344     /* If the database page size is not a power of two, or is greater than
47345     ** SQLCIPHER_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
47346     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
47347     ** WAL file.
47348     */
47349     magic = sqlcipher3Get4byte(&aBuf[0]);
47350     szPage = sqlcipher3Get4byte(&aBuf[8]);
47351     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
47352      || szPage&(szPage-1) 
47353      || szPage>SQLCIPHER_MAX_PAGE_SIZE 
47354      || szPage<512 
47355     ){
47356       goto finished;
47357     }
47358     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
47359     pWal->szPage = szPage;
47360     pWal->nCkpt = sqlcipher3Get4byte(&aBuf[12]);
47361     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
47362
47363     /* Verify that the WAL header checksum is correct */
47364     walChecksumBytes(pWal->hdr.bigEndCksum==SQLCIPHER_BIGENDIAN, 
47365         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
47366     );
47367     if( pWal->hdr.aFrameCksum[0]!=sqlcipher3Get4byte(&aBuf[24])
47368      || pWal->hdr.aFrameCksum[1]!=sqlcipher3Get4byte(&aBuf[28])
47369     ){
47370       goto finished;
47371     }
47372
47373     /* Verify that the version number on the WAL format is one that
47374     ** are able to understand */
47375     version = sqlcipher3Get4byte(&aBuf[4]);
47376     if( version!=WAL_MAX_VERSION ){
47377       rc = SQLCIPHER_CANTOPEN_BKPT;
47378       goto finished;
47379     }
47380
47381     /* Malloc a buffer to read frames into. */
47382     szFrame = szPage + WAL_FRAME_HDRSIZE;
47383     aFrame = (u8 *)sqlcipher3_malloc(szFrame);
47384     if( !aFrame ){
47385       rc = SQLCIPHER_NOMEM;
47386       goto recovery_error;
47387     }
47388     aData = &aFrame[WAL_FRAME_HDRSIZE];
47389
47390     /* Read all frames from the log file. */
47391     iFrame = 0;
47392     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
47393       u32 pgno;                   /* Database page number for frame */
47394       u32 nTruncate;              /* dbsize field from frame header */
47395       int isValid;                /* True if this frame is valid */
47396
47397       /* Read and decode the next log frame. */
47398       rc = sqlcipher3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
47399       if( rc!=SQLCIPHER_OK ) break;
47400       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
47401       if( !isValid ) break;
47402       rc = walIndexAppend(pWal, ++iFrame, pgno);
47403       if( rc!=SQLCIPHER_OK ) break;
47404
47405       /* If nTruncate is non-zero, this is a commit record. */
47406       if( nTruncate ){
47407         pWal->hdr.mxFrame = iFrame;
47408         pWal->hdr.nPage = nTruncate;
47409         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
47410         testcase( szPage<=32768 );
47411         testcase( szPage>=65536 );
47412         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
47413         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
47414       }
47415     }
47416
47417     sqlcipher3_free(aFrame);
47418   }
47419
47420 finished:
47421   if( rc==SQLCIPHER_OK ){
47422     volatile WalCkptInfo *pInfo;
47423     int i;
47424     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
47425     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
47426     walIndexWriteHdr(pWal);
47427
47428     /* Reset the checkpoint-header. This is safe because this thread is 
47429     ** currently holding locks that exclude all other readers, writers and
47430     ** checkpointers.
47431     */
47432     pInfo = walCkptInfo(pWal);
47433     pInfo->nBackfill = 0;
47434     pInfo->aReadMark[0] = 0;
47435     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
47436
47437     /* If more than one frame was recovered from the log file, report an
47438     ** event via sqlcipher3_log(). This is to help with identifying performance
47439     ** problems caused by applications routinely shutting down without
47440     ** checkpointing the log file.
47441     */
47442     if( pWal->hdr.nPage ){
47443       sqlcipher3_log(SQLCIPHER_OK, "Recovered %d frames from WAL file %s",
47444           pWal->hdr.nPage, pWal->zWalName
47445       );
47446     }
47447   }
47448
47449 recovery_error:
47450   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
47451   walUnlockExclusive(pWal, iLock, nLock);
47452   return rc;
47453 }
47454
47455 /*
47456 ** Close an open wal-index.
47457 */
47458 static void walIndexClose(Wal *pWal, int isDelete){
47459   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
47460     int i;
47461     for(i=0; i<pWal->nWiData; i++){
47462       sqlcipher3_free((void *)pWal->apWiData[i]);
47463       pWal->apWiData[i] = 0;
47464     }
47465   }else{
47466     sqlcipher3OsShmUnmap(pWal->pDbFd, isDelete);
47467   }
47468 }
47469
47470 /* 
47471 ** Open a connection to the WAL file zWalName. The database file must 
47472 ** already be opened on connection pDbFd. The buffer that zWalName points
47473 ** to must remain valid for the lifetime of the returned Wal* handle.
47474 **
47475 ** A SHARED lock should be held on the database file when this function
47476 ** is called. The purpose of this SHARED lock is to prevent any other
47477 ** client from unlinking the WAL or wal-index file. If another process
47478 ** were to do this just after this client opened one of these files, the
47479 ** system would be badly broken.
47480 **
47481 ** If the log file is successfully opened, SQLCIPHER_OK is returned and 
47482 ** *ppWal is set to point to a new WAL handle. If an error occurs,
47483 ** an SQLite error code is returned and *ppWal is left unmodified.
47484 */
47485 SQLCIPHER_PRIVATE int sqlcipher3WalOpen(
47486   sqlcipher3_vfs *pVfs,              /* vfs module to open wal and wal-index */
47487   sqlcipher3_file *pDbFd,            /* The open database file */
47488   const char *zWalName,           /* Name of the WAL file */
47489   int bNoShm,                     /* True to run in heap-memory mode */
47490   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
47491   Wal **ppWal                     /* OUT: Allocated Wal handle */
47492 ){
47493   int rc;                         /* Return Code */
47494   Wal *pRet;                      /* Object to allocate and return */
47495   int flags;                      /* Flags passed to OsOpen() */
47496
47497   assert( zWalName && zWalName[0] );
47498   assert( pDbFd );
47499
47500   /* In the amalgamation, the os_unix.c and os_win.c source files come before
47501   ** this source file.  Verify that the #defines of the locking byte offsets
47502   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
47503   */
47504 #ifdef WIN_SHM_BASE
47505   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
47506 #endif
47507 #ifdef UNIX_SHM_BASE
47508   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
47509 #endif
47510
47511
47512   /* Allocate an instance of struct Wal to return. */
47513   *ppWal = 0;
47514   pRet = (Wal*)sqlcipher3MallocZero(sizeof(Wal) + pVfs->szOsFile);
47515   if( !pRet ){
47516     return SQLCIPHER_NOMEM;
47517   }
47518
47519   pRet->pVfs = pVfs;
47520   pRet->pWalFd = (sqlcipher3_file *)&pRet[1];
47521   pRet->pDbFd = pDbFd;
47522   pRet->readLock = -1;
47523   pRet->mxWalSize = mxWalSize;
47524   pRet->zWalName = zWalName;
47525   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
47526
47527   /* Open file handle on the write-ahead log file. */
47528   flags = (SQLCIPHER_OPEN_READWRITE|SQLCIPHER_OPEN_CREATE|SQLCIPHER_OPEN_WAL);
47529   rc = sqlcipher3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
47530   if( rc==SQLCIPHER_OK && flags&SQLCIPHER_OPEN_READONLY ){
47531     pRet->readOnly = WAL_RDONLY;
47532   }
47533
47534   if( rc!=SQLCIPHER_OK ){
47535     walIndexClose(pRet, 0);
47536     sqlcipher3OsClose(pRet->pWalFd);
47537     sqlcipher3_free(pRet);
47538   }else{
47539     *ppWal = pRet;
47540     WALTRACE(("WAL%d: opened\n", pRet));
47541   }
47542   return rc;
47543 }
47544
47545 /*
47546 ** Change the size to which the WAL file is trucated on each reset.
47547 */
47548 SQLCIPHER_PRIVATE void sqlcipher3WalLimit(Wal *pWal, i64 iLimit){
47549   if( pWal ) pWal->mxWalSize = iLimit;
47550 }
47551
47552 /*
47553 ** Find the smallest page number out of all pages held in the WAL that
47554 ** has not been returned by any prior invocation of this method on the
47555 ** same WalIterator object.   Write into *piFrame the frame index where
47556 ** that page was last written into the WAL.  Write into *piPage the page
47557 ** number.
47558 **
47559 ** Return 0 on success.  If there are no pages in the WAL with a page
47560 ** number larger than *piPage, then return 1.
47561 */
47562 static int walIteratorNext(
47563   WalIterator *p,               /* Iterator */
47564   u32 *piPage,                  /* OUT: The page number of the next page */
47565   u32 *piFrame                  /* OUT: Wal frame index of next page */
47566 ){
47567   u32 iMin;                     /* Result pgno must be greater than iMin */
47568   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
47569   int i;                        /* For looping through segments */
47570
47571   iMin = p->iPrior;
47572   assert( iMin<0xffffffff );
47573   for(i=p->nSegment-1; i>=0; i--){
47574     struct WalSegment *pSegment = &p->aSegment[i];
47575     while( pSegment->iNext<pSegment->nEntry ){
47576       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
47577       if( iPg>iMin ){
47578         if( iPg<iRet ){
47579           iRet = iPg;
47580           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
47581         }
47582         break;
47583       }
47584       pSegment->iNext++;
47585     }
47586   }
47587
47588   *piPage = p->iPrior = iRet;
47589   return (iRet==0xFFFFFFFF);
47590 }
47591
47592 /*
47593 ** This function merges two sorted lists into a single sorted list.
47594 **
47595 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
47596 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
47597 ** is guaranteed for all J<K:
47598 **
47599 **        aContent[aLeft[J]] < aContent[aLeft[K]]
47600 **        aContent[aRight[J]] < aContent[aRight[K]]
47601 **
47602 ** This routine overwrites aRight[] with a new (probably longer) sequence
47603 ** of indices such that the aRight[] contains every index that appears in
47604 ** either aLeft[] or the old aRight[] and such that the second condition
47605 ** above is still met.
47606 **
47607 ** The aContent[aLeft[X]] values will be unique for all X.  And the
47608 ** aContent[aRight[X]] values will be unique too.  But there might be
47609 ** one or more combinations of X and Y such that
47610 **
47611 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
47612 **
47613 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
47614 */
47615 static void walMerge(
47616   const u32 *aContent,            /* Pages in wal - keys for the sort */
47617   ht_slot *aLeft,                 /* IN: Left hand input list */
47618   int nLeft,                      /* IN: Elements in array *paLeft */
47619   ht_slot **paRight,              /* IN/OUT: Right hand input list */
47620   int *pnRight,                   /* IN/OUT: Elements in *paRight */
47621   ht_slot *aTmp                   /* Temporary buffer */
47622 ){
47623   int iLeft = 0;                  /* Current index in aLeft */
47624   int iRight = 0;                 /* Current index in aRight */
47625   int iOut = 0;                   /* Current index in output buffer */
47626   int nRight = *pnRight;
47627   ht_slot *aRight = *paRight;
47628
47629   assert( nLeft>0 && nRight>0 );
47630   while( iRight<nRight || iLeft<nLeft ){
47631     ht_slot logpage;
47632     Pgno dbpage;
47633
47634     if( (iLeft<nLeft) 
47635      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
47636     ){
47637       logpage = aLeft[iLeft++];
47638     }else{
47639       logpage = aRight[iRight++];
47640     }
47641     dbpage = aContent[logpage];
47642
47643     aTmp[iOut++] = logpage;
47644     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
47645
47646     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
47647     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
47648   }
47649
47650   *paRight = aLeft;
47651   *pnRight = iOut;
47652   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
47653 }
47654
47655 /*
47656 ** Sort the elements in list aList using aContent[] as the sort key.
47657 ** Remove elements with duplicate keys, preferring to keep the
47658 ** larger aList[] values.
47659 **
47660 ** The aList[] entries are indices into aContent[].  The values in
47661 ** aList[] are to be sorted so that for all J<K:
47662 **
47663 **      aContent[aList[J]] < aContent[aList[K]]
47664 **
47665 ** For any X and Y such that
47666 **
47667 **      aContent[aList[X]] == aContent[aList[Y]]
47668 **
47669 ** Keep the larger of the two values aList[X] and aList[Y] and discard
47670 ** the smaller.
47671 */
47672 static void walMergesort(
47673   const u32 *aContent,            /* Pages in wal */
47674   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
47675   ht_slot *aList,                 /* IN/OUT: List to sort */
47676   int *pnList                     /* IN/OUT: Number of elements in aList[] */
47677 ){
47678   struct Sublist {
47679     int nList;                    /* Number of elements in aList */
47680     ht_slot *aList;               /* Pointer to sub-list content */
47681   };
47682
47683   const int nList = *pnList;      /* Size of input list */
47684   int nMerge = 0;                 /* Number of elements in list aMerge */
47685   ht_slot *aMerge = 0;            /* List to be merged */
47686   int iList;                      /* Index into input list */
47687   int iSub = 0;                   /* Index into aSub array */
47688   struct Sublist aSub[13];        /* Array of sub-lists */
47689
47690   memset(aSub, 0, sizeof(aSub));
47691   assert( nList<=HASHTABLE_NPAGE && nList>0 );
47692   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
47693
47694   for(iList=0; iList<nList; iList++){
47695     nMerge = 1;
47696     aMerge = &aList[iList];
47697     for(iSub=0; iList & (1<<iSub); iSub++){
47698       struct Sublist *p = &aSub[iSub];
47699       assert( p->aList && p->nList<=(1<<iSub) );
47700       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
47701       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
47702     }
47703     aSub[iSub].aList = aMerge;
47704     aSub[iSub].nList = nMerge;
47705   }
47706
47707   for(iSub++; iSub<ArraySize(aSub); iSub++){
47708     if( nList & (1<<iSub) ){
47709       struct Sublist *p = &aSub[iSub];
47710       assert( p->nList<=(1<<iSub) );
47711       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
47712       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
47713     }
47714   }
47715   assert( aMerge==aList );
47716   *pnList = nMerge;
47717
47718 #ifdef SQLCIPHER_DEBUG
47719   {
47720     int i;
47721     for(i=1; i<*pnList; i++){
47722       assert( aContent[aList[i]] > aContent[aList[i-1]] );
47723     }
47724   }
47725 #endif
47726 }
47727
47728 /* 
47729 ** Free an iterator allocated by walIteratorInit().
47730 */
47731 static void walIteratorFree(WalIterator *p){
47732   sqlcipher3ScratchFree(p);
47733 }
47734
47735 /*
47736 ** Construct a WalInterator object that can be used to loop over all 
47737 ** pages in the WAL in ascending order. The caller must hold the checkpoint
47738 ** lock.
47739 **
47740 ** On success, make *pp point to the newly allocated WalInterator object
47741 ** return SQLCIPHER_OK. Otherwise, return an error code. If this routine
47742 ** returns an error, the value of *pp is undefined.
47743 **
47744 ** The calling routine should invoke walIteratorFree() to destroy the
47745 ** WalIterator object when it has finished with it.
47746 */
47747 static int walIteratorInit(Wal *pWal, WalIterator **pp){
47748   WalIterator *p;                 /* Return value */
47749   int nSegment;                   /* Number of segments to merge */
47750   u32 iLast;                      /* Last frame in log */
47751   int nByte;                      /* Number of bytes to allocate */
47752   int i;                          /* Iterator variable */
47753   ht_slot *aTmp;                  /* Temp space used by merge-sort */
47754   int rc = SQLCIPHER_OK;             /* Return Code */
47755
47756   /* This routine only runs while holding the checkpoint lock. And
47757   ** it only runs if there is actually content in the log (mxFrame>0).
47758   */
47759   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
47760   iLast = pWal->hdr.mxFrame;
47761
47762   /* Allocate space for the WalIterator object. */
47763   nSegment = walFramePage(iLast) + 1;
47764   nByte = sizeof(WalIterator) 
47765         + (nSegment-1)*sizeof(struct WalSegment)
47766         + iLast*sizeof(ht_slot);
47767   p = (WalIterator *)sqlcipher3ScratchMalloc(nByte);
47768   if( !p ){
47769     return SQLCIPHER_NOMEM;
47770   }
47771   memset(p, 0, nByte);
47772   p->nSegment = nSegment;
47773
47774   /* Allocate temporary space used by the merge-sort routine. This block
47775   ** of memory will be freed before this function returns.
47776   */
47777   aTmp = (ht_slot *)sqlcipher3ScratchMalloc(
47778       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
47779   );
47780   if( !aTmp ){
47781     rc = SQLCIPHER_NOMEM;
47782   }
47783
47784   for(i=0; rc==SQLCIPHER_OK && i<nSegment; i++){
47785     volatile ht_slot *aHash;
47786     u32 iZero;
47787     volatile u32 *aPgno;
47788
47789     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
47790     if( rc==SQLCIPHER_OK ){
47791       int j;                      /* Counter variable */
47792       int nEntry;                 /* Number of entries in this segment */
47793       ht_slot *aIndex;            /* Sorted index for this segment */
47794
47795       aPgno++;
47796       if( (i+1)==nSegment ){
47797         nEntry = (int)(iLast - iZero);
47798       }else{
47799         nEntry = (int)((u32*)aHash - (u32*)aPgno);
47800       }
47801       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
47802       iZero++;
47803   
47804       for(j=0; j<nEntry; j++){
47805         aIndex[j] = (ht_slot)j;
47806       }
47807       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
47808       p->aSegment[i].iZero = iZero;
47809       p->aSegment[i].nEntry = nEntry;
47810       p->aSegment[i].aIndex = aIndex;
47811       p->aSegment[i].aPgno = (u32 *)aPgno;
47812     }
47813   }
47814   sqlcipher3ScratchFree(aTmp);
47815
47816   if( rc!=SQLCIPHER_OK ){
47817     walIteratorFree(p);
47818   }
47819   *pp = p;
47820   return rc;
47821 }
47822
47823 /*
47824 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
47825 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
47826 ** busy-handler function. Invoke it and retry the lock until either the
47827 ** lock is successfully obtained or the busy-handler returns 0.
47828 */
47829 static int walBusyLock(
47830   Wal *pWal,                      /* WAL connection */
47831   int (*xBusy)(void*),            /* Function to call when busy */
47832   void *pBusyArg,                 /* Context argument for xBusyHandler */
47833   int lockIdx,                    /* Offset of first byte to lock */
47834   int n                           /* Number of bytes to lock */
47835 ){
47836   int rc;
47837   do {
47838     rc = walLockExclusive(pWal, lockIdx, n);
47839   }while( xBusy && rc==SQLCIPHER_BUSY && xBusy(pBusyArg) );
47840   return rc;
47841 }
47842
47843 /*
47844 ** The cache of the wal-index header must be valid to call this function.
47845 ** Return the page-size in bytes used by the database.
47846 */
47847 static int walPagesize(Wal *pWal){
47848   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
47849 }
47850
47851 /*
47852 ** Copy as much content as we can from the WAL back into the database file
47853 ** in response to an sqlcipher3_wal_checkpoint() request or the equivalent.
47854 **
47855 ** The amount of information copies from WAL to database might be limited
47856 ** by active readers.  This routine will never overwrite a database page
47857 ** that a concurrent reader might be using.
47858 **
47859 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
47860 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
47861 ** checkpoints are always run by a background thread or background 
47862 ** process, foreground threads will never block on a lengthy fsync call.
47863 **
47864 ** Fsync is called on the WAL before writing content out of the WAL and
47865 ** into the database.  This ensures that if the new content is persistent
47866 ** in the WAL and can be recovered following a power-loss or hard reset.
47867 **
47868 ** Fsync is also called on the database file if (and only if) the entire
47869 ** WAL content is copied into the database file.  This second fsync makes
47870 ** it safe to delete the WAL since the new content will persist in the
47871 ** database file.
47872 **
47873 ** This routine uses and updates the nBackfill field of the wal-index header.
47874 ** This is the only routine tha will increase the value of nBackfill.  
47875 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
47876 ** its value.)
47877 **
47878 ** The caller must be holding sufficient locks to ensure that no other
47879 ** checkpoint is running (in any other thread or process) at the same
47880 ** time.
47881 */
47882 static int walCheckpoint(
47883   Wal *pWal,                      /* Wal connection */
47884   int eMode,                      /* One of PASSIVE, FULL or RESTART */
47885   int (*xBusyCall)(void*),        /* Function to call when busy */
47886   void *pBusyArg,                 /* Context argument for xBusyHandler */
47887   int sync_flags,                 /* Flags for OsSync() (or 0) */
47888   u8 *zBuf                        /* Temporary buffer to use */
47889 ){
47890   int rc;                         /* Return code */
47891   int szPage;                     /* Database page-size */
47892   WalIterator *pIter = 0;         /* Wal iterator context */
47893   u32 iDbpage = 0;                /* Next database page to write */
47894   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
47895   u32 mxSafeFrame;                /* Max frame that can be backfilled */
47896   u32 mxPage;                     /* Max database page to write */
47897   int i;                          /* Loop counter */
47898   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
47899   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
47900
47901   szPage = walPagesize(pWal);
47902   testcase( szPage<=32768 );
47903   testcase( szPage>=65536 );
47904   pInfo = walCkptInfo(pWal);
47905   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLCIPHER_OK;
47906
47907   /* Allocate the iterator */
47908   rc = walIteratorInit(pWal, &pIter);
47909   if( rc!=SQLCIPHER_OK ){
47910     return rc;
47911   }
47912   assert( pIter );
47913
47914   if( eMode!=SQLCIPHER_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
47915
47916   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
47917   ** safe to write into the database.  Frames beyond mxSafeFrame might
47918   ** overwrite database pages that are in use by active readers and thus
47919   ** cannot be backfilled from the WAL.
47920   */
47921   mxSafeFrame = pWal->hdr.mxFrame;
47922   mxPage = pWal->hdr.nPage;
47923   for(i=1; i<WAL_NREADER; i++){
47924     u32 y = pInfo->aReadMark[i];
47925     if( mxSafeFrame>y ){
47926       assert( y<=pWal->hdr.mxFrame );
47927       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
47928       if( rc==SQLCIPHER_OK ){
47929         pInfo->aReadMark[i] = READMARK_NOT_USED;
47930         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
47931       }else if( rc==SQLCIPHER_BUSY ){
47932         mxSafeFrame = y;
47933         xBusy = 0;
47934       }else{
47935         goto walcheckpoint_out;
47936       }
47937     }
47938   }
47939
47940   if( pInfo->nBackfill<mxSafeFrame
47941    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLCIPHER_OK
47942   ){
47943     i64 nSize;                    /* Current size of database file */
47944     u32 nBackfill = pInfo->nBackfill;
47945
47946     /* Sync the WAL to disk */
47947     if( sync_flags ){
47948       rc = sqlcipher3OsSync(pWal->pWalFd, sync_flags);
47949     }
47950
47951     /* If the database file may grow as a result of this checkpoint, hint
47952     ** about the eventual size of the db file to the VFS layer. 
47953     */
47954     if( rc==SQLCIPHER_OK ){
47955       i64 nReq = ((i64)mxPage * szPage);
47956       rc = sqlcipher3OsFileSize(pWal->pDbFd, &nSize);
47957       if( rc==SQLCIPHER_OK && nSize<nReq ){
47958         sqlcipher3OsFileControl(pWal->pDbFd, SQLCIPHER_FCNTL_SIZE_HINT, &nReq);
47959       }
47960     }
47961
47962     /* Iterate through the contents of the WAL, copying data to the db file. */
47963     while( rc==SQLCIPHER_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
47964       i64 iOffset;
47965       assert( walFramePgno(pWal, iFrame)==iDbpage );
47966       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
47967       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
47968       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
47969       rc = sqlcipher3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
47970       if( rc!=SQLCIPHER_OK ) break;
47971       iOffset = (iDbpage-1)*(i64)szPage;
47972       testcase( IS_BIG_INT(iOffset) );
47973       rc = sqlcipher3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
47974       if( rc!=SQLCIPHER_OK ) break;
47975     }
47976
47977     /* If work was actually accomplished... */
47978     if( rc==SQLCIPHER_OK ){
47979       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
47980         i64 szDb = pWal->hdr.nPage*(i64)szPage;
47981         testcase( IS_BIG_INT(szDb) );
47982         rc = sqlcipher3OsTruncate(pWal->pDbFd, szDb);
47983         if( rc==SQLCIPHER_OK && sync_flags ){
47984           rc = sqlcipher3OsSync(pWal->pDbFd, sync_flags);
47985         }
47986       }
47987       if( rc==SQLCIPHER_OK ){
47988         pInfo->nBackfill = mxSafeFrame;
47989       }
47990     }
47991
47992     /* Release the reader lock held while backfilling */
47993     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
47994   }
47995
47996   if( rc==SQLCIPHER_BUSY ){
47997     /* Reset the return code so as not to report a checkpoint failure
47998     ** just because there are active readers.  */
47999     rc = SQLCIPHER_OK;
48000   }
48001
48002   /* If this is an SQLCIPHER_CHECKPOINT_RESTART operation, and the entire wal
48003   ** file has been copied into the database file, then block until all
48004   ** readers have finished using the wal file. This ensures that the next
48005   ** process to write to the database restarts the wal file.
48006   */
48007   if( rc==SQLCIPHER_OK && eMode!=SQLCIPHER_CHECKPOINT_PASSIVE ){
48008     assert( pWal->writeLock );
48009     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
48010       rc = SQLCIPHER_BUSY;
48011     }else if( eMode==SQLCIPHER_CHECKPOINT_RESTART ){
48012       assert( mxSafeFrame==pWal->hdr.mxFrame );
48013       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
48014       if( rc==SQLCIPHER_OK ){
48015         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48016       }
48017     }
48018   }
48019
48020  walcheckpoint_out:
48021   walIteratorFree(pIter);
48022   return rc;
48023 }
48024
48025 /*
48026 ** Close a connection to a log file.
48027 */
48028 SQLCIPHER_PRIVATE int sqlcipher3WalClose(
48029   Wal *pWal,                      /* Wal to close */
48030   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
48031   int nBuf,
48032   u8 *zBuf                        /* Buffer of at least nBuf bytes */
48033 ){
48034   int rc = SQLCIPHER_OK;
48035   if( pWal ){
48036     int isDelete = 0;             /* True to unlink wal and wal-index files */
48037
48038     /* If an EXCLUSIVE lock can be obtained on the database file (using the
48039     ** ordinary, rollback-mode locking methods, this guarantees that the
48040     ** connection associated with this log file is the only connection to
48041     ** the database. In this case checkpoint the database and unlink both
48042     ** the wal and wal-index files.
48043     **
48044     ** The EXCLUSIVE lock is not released before returning.
48045     */
48046     rc = sqlcipher3OsLock(pWal->pDbFd, SQLCIPHER_LOCK_EXCLUSIVE);
48047     if( rc==SQLCIPHER_OK ){
48048       int bPersistWal = -1;
48049       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
48050         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
48051       }
48052       rc = sqlcipher3WalCheckpoint(
48053           pWal, SQLCIPHER_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
48054       );
48055       sqlcipher3OsFileControl(pWal->pDbFd, SQLCIPHER_FCNTL_PERSIST_WAL, &bPersistWal);
48056       if( rc==SQLCIPHER_OK && bPersistWal!=1 ){
48057         isDelete = 1;
48058       }
48059     }
48060
48061     walIndexClose(pWal, isDelete);
48062     sqlcipher3OsClose(pWal->pWalFd);
48063     if( isDelete ){
48064       sqlcipher3OsDelete(pWal->pVfs, pWal->zWalName, 0);
48065     }
48066     WALTRACE(("WAL%p: closed\n", pWal));
48067     sqlcipher3_free((void *)pWal->apWiData);
48068     sqlcipher3_free(pWal);
48069   }
48070   return rc;
48071 }
48072
48073 /*
48074 ** Try to read the wal-index header.  Return 0 on success and 1 if
48075 ** there is a problem.
48076 **
48077 ** The wal-index is in shared memory.  Another thread or process might
48078 ** be writing the header at the same time this procedure is trying to
48079 ** read it, which might result in inconsistency.  A dirty read is detected
48080 ** by verifying that both copies of the header are the same and also by
48081 ** a checksum on the header.
48082 **
48083 ** If and only if the read is consistent and the header is different from
48084 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
48085 ** and *pChanged is set to 1.
48086 **
48087 ** If the checksum cannot be verified return non-zero. If the header
48088 ** is read successfully and the checksum verified, return zero.
48089 */
48090 static int walIndexTryHdr(Wal *pWal, int *pChanged){
48091   u32 aCksum[2];                  /* Checksum on the header content */
48092   WalIndexHdr h1, h2;             /* Two copies of the header content */
48093   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
48094
48095   /* The first page of the wal-index must be mapped at this point. */
48096   assert( pWal->nWiData>0 && pWal->apWiData[0] );
48097
48098   /* Read the header. This might happen concurrently with a write to the
48099   ** same area of shared memory on a different CPU in a SMP,
48100   ** meaning it is possible that an inconsistent snapshot is read
48101   ** from the file. If this happens, return non-zero.
48102   **
48103   ** There are two copies of the header at the beginning of the wal-index.
48104   ** When reading, read [0] first then [1].  Writes are in the reverse order.
48105   ** Memory barriers are used to prevent the compiler or the hardware from
48106   ** reordering the reads and writes.
48107   */
48108   aHdr = walIndexHdr(pWal);
48109   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
48110   walShmBarrier(pWal);
48111   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
48112
48113   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
48114     return 1;   /* Dirty read */
48115   }  
48116   if( h1.isInit==0 ){
48117     return 1;   /* Malformed header - probably all zeros */
48118   }
48119   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
48120   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
48121     return 1;   /* Checksum does not match */
48122   }
48123
48124   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
48125     *pChanged = 1;
48126     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
48127     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
48128     testcase( pWal->szPage<=32768 );
48129     testcase( pWal->szPage>=65536 );
48130   }
48131
48132   /* The header was successfully read. Return zero. */
48133   return 0;
48134 }
48135
48136 /*
48137 ** Read the wal-index header from the wal-index and into pWal->hdr.
48138 ** If the wal-header appears to be corrupt, try to reconstruct the
48139 ** wal-index from the WAL before returning.
48140 **
48141 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
48142 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
48143 ** to 0.
48144 **
48145 ** If the wal-index header is successfully read, return SQLCIPHER_OK. 
48146 ** Otherwise an SQLite error code.
48147 */
48148 static int walIndexReadHdr(Wal *pWal, int *pChanged){
48149   int rc;                         /* Return code */
48150   int badHdr;                     /* True if a header read failed */
48151   volatile u32 *page0;            /* Chunk of wal-index containing header */
48152
48153   /* Ensure that page 0 of the wal-index (the page that contains the 
48154   ** wal-index header) is mapped. Return early if an error occurs here.
48155   */
48156   assert( pChanged );
48157   rc = walIndexPage(pWal, 0, &page0);
48158   if( rc!=SQLCIPHER_OK ){
48159     return rc;
48160   };
48161   assert( page0 || pWal->writeLock==0 );
48162
48163   /* If the first page of the wal-index has been mapped, try to read the
48164   ** wal-index header immediately, without holding any lock. This usually
48165   ** works, but may fail if the wal-index header is corrupt or currently 
48166   ** being modified by another thread or process.
48167   */
48168   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
48169
48170   /* If the first attempt failed, it might have been due to a race
48171   ** with a writer.  So get a WRITE lock and try again.
48172   */
48173   assert( badHdr==0 || pWal->writeLock==0 );
48174   if( badHdr ){
48175     if( pWal->readOnly & WAL_SHM_RDONLY ){
48176       if( SQLCIPHER_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
48177         walUnlockShared(pWal, WAL_WRITE_LOCK);
48178         rc = SQLCIPHER_READONLY_RECOVERY;
48179       }
48180     }else if( SQLCIPHER_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
48181       pWal->writeLock = 1;
48182       if( SQLCIPHER_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
48183         badHdr = walIndexTryHdr(pWal, pChanged);
48184         if( badHdr ){
48185           /* If the wal-index header is still malformed even while holding
48186           ** a WRITE lock, it can only mean that the header is corrupted and
48187           ** needs to be reconstructed.  So run recovery to do exactly that.
48188           */
48189           rc = walIndexRecover(pWal);
48190           *pChanged = 1;
48191         }
48192       }
48193       pWal->writeLock = 0;
48194       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
48195     }
48196   }
48197
48198   /* If the header is read successfully, check the version number to make
48199   ** sure the wal-index was not constructed with some future format that
48200   ** this version of SQLite cannot understand.
48201   */
48202   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
48203     rc = SQLCIPHER_CANTOPEN_BKPT;
48204   }
48205
48206   return rc;
48207 }
48208
48209 /*
48210 ** This is the value that walTryBeginRead returns when it needs to
48211 ** be retried.
48212 */
48213 #define WAL_RETRY  (-1)
48214
48215 /*
48216 ** Attempt to start a read transaction.  This might fail due to a race or
48217 ** other transient condition.  When that happens, it returns WAL_RETRY to
48218 ** indicate to the caller that it is safe to retry immediately.
48219 **
48220 ** On success return SQLCIPHER_OK.  On a permanent failure (such an
48221 ** I/O error or an SQLCIPHER_BUSY because another process is running
48222 ** recovery) return a positive error code.
48223 **
48224 ** The useWal parameter is true to force the use of the WAL and disable
48225 ** the case where the WAL is bypassed because it has been completely
48226 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
48227 ** to make a copy of the wal-index header into pWal->hdr.  If the 
48228 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
48229 ** to the caller that the local paget cache is obsolete and needs to be 
48230 ** flushed.)  When useWal==1, the wal-index header is assumed to already
48231 ** be loaded and the pChanged parameter is unused.
48232 **
48233 ** The caller must set the cnt parameter to the number of prior calls to
48234 ** this routine during the current read attempt that returned WAL_RETRY.
48235 ** This routine will start taking more aggressive measures to clear the
48236 ** race conditions after multiple WAL_RETRY returns, and after an excessive
48237 ** number of errors will ultimately return SQLCIPHER_PROTOCOL.  The
48238 ** SQLCIPHER_PROTOCOL return indicates that some other process has gone rogue
48239 ** and is not honoring the locking protocol.  There is a vanishingly small
48240 ** chance that SQLCIPHER_PROTOCOL could be returned because of a run of really
48241 ** bad luck when there is lots of contention for the wal-index, but that
48242 ** possibility is so small that it can be safely neglected, we believe.
48243 **
48244 ** On success, this routine obtains a read lock on 
48245 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
48246 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
48247 ** that means the Wal does not hold any read lock.  The reader must not
48248 ** access any database page that is modified by a WAL frame up to and
48249 ** including frame number aReadMark[pWal->readLock].  The reader will
48250 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
48251 ** Or if pWal->readLock==0, then the reader will ignore the WAL
48252 ** completely and get all content directly from the database file.
48253 ** If the useWal parameter is 1 then the WAL will never be ignored and
48254 ** this routine will always set pWal->readLock>0 on success.
48255 ** When the read transaction is completed, the caller must release the
48256 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
48257 **
48258 ** This routine uses the nBackfill and aReadMark[] fields of the header
48259 ** to select a particular WAL_READ_LOCK() that strives to let the
48260 ** checkpoint process do as much work as possible.  This routine might
48261 ** update values of the aReadMark[] array in the header, but if it does
48262 ** so it takes care to hold an exclusive lock on the corresponding
48263 ** WAL_READ_LOCK() while changing values.
48264 */
48265 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
48266   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
48267   u32 mxReadMark;                 /* Largest aReadMark[] value */
48268   int mxI;                        /* Index of largest aReadMark[] value */
48269   int i;                          /* Loop counter */
48270   int rc = SQLCIPHER_OK;             /* Return code  */
48271
48272   assert( pWal->readLock<0 );     /* Not currently locked */
48273
48274   /* Take steps to avoid spinning forever if there is a protocol error.
48275   **
48276   ** Circumstances that cause a RETRY should only last for the briefest
48277   ** instances of time.  No I/O or other system calls are done while the
48278   ** locks are held, so the locks should not be held for very long. But 
48279   ** if we are unlucky, another process that is holding a lock might get
48280   ** paged out or take a page-fault that is time-consuming to resolve, 
48281   ** during the few nanoseconds that it is holding the lock.  In that case,
48282   ** it might take longer than normal for the lock to free.
48283   **
48284   ** After 5 RETRYs, we begin calling sqlcipher3OsSleep().  The first few
48285   ** calls to sqlcipher3OsSleep() have a delay of 1 microsecond.  Really this
48286   ** is more of a scheduler yield than an actual delay.  But on the 10th
48287   ** an subsequent retries, the delays start becoming longer and longer, 
48288   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
48289   ** The total delay time before giving up is less than 1 second.
48290   */
48291   if( cnt>5 ){
48292     int nDelay = 1;                      /* Pause time in microseconds */
48293     if( cnt>100 ){
48294       VVA_ONLY( pWal->lockError = 1; )
48295       return SQLCIPHER_PROTOCOL;
48296     }
48297     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
48298     sqlcipher3OsSleep(pWal->pVfs, nDelay);
48299   }
48300
48301   if( !useWal ){
48302     rc = walIndexReadHdr(pWal, pChanged);
48303     if( rc==SQLCIPHER_BUSY ){
48304       /* If there is not a recovery running in another thread or process
48305       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
48306       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
48307       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
48308       ** would be technically correct.  But the race is benign since with
48309       ** WAL_RETRY this routine will be called again and will probably be
48310       ** right on the second iteration.
48311       */
48312       if( pWal->apWiData[0]==0 ){
48313         /* This branch is taken when the xShmMap() method returns SQLCIPHER_BUSY.
48314         ** We assume this is a transient condition, so return WAL_RETRY. The
48315         ** xShmMap() implementation used by the default unix and win32 VFS 
48316         ** modules may return SQLCIPHER_BUSY due to a race condition in the 
48317         ** code that determines whether or not the shared-memory region 
48318         ** must be zeroed before the requested page is returned.
48319         */
48320         rc = WAL_RETRY;
48321       }else if( SQLCIPHER_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
48322         walUnlockShared(pWal, WAL_RECOVER_LOCK);
48323         rc = WAL_RETRY;
48324       }else if( rc==SQLCIPHER_BUSY ){
48325         rc = SQLCIPHER_BUSY_RECOVERY;
48326       }
48327     }
48328     if( rc!=SQLCIPHER_OK ){
48329       return rc;
48330     }
48331   }
48332
48333   pInfo = walCkptInfo(pWal);
48334   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
48335     /* The WAL has been completely backfilled (or it is empty).
48336     ** and can be safely ignored.
48337     */
48338     rc = walLockShared(pWal, WAL_READ_LOCK(0));
48339     walShmBarrier(pWal);
48340     if( rc==SQLCIPHER_OK ){
48341       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
48342         /* It is not safe to allow the reader to continue here if frames
48343         ** may have been appended to the log before READ_LOCK(0) was obtained.
48344         ** When holding READ_LOCK(0), the reader ignores the entire log file,
48345         ** which implies that the database file contains a trustworthy
48346         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
48347         ** happening, this is usually correct.
48348         **
48349         ** However, if frames have been appended to the log (or if the log 
48350         ** is wrapped and written for that matter) before the READ_LOCK(0)
48351         ** is obtained, that is not necessarily true. A checkpointer may
48352         ** have started to backfill the appended frames but crashed before
48353         ** it finished. Leaving a corrupt image in the database file.
48354         */
48355         walUnlockShared(pWal, WAL_READ_LOCK(0));
48356         return WAL_RETRY;
48357       }
48358       pWal->readLock = 0;
48359       return SQLCIPHER_OK;
48360     }else if( rc!=SQLCIPHER_BUSY ){
48361       return rc;
48362     }
48363   }
48364
48365   /* If we get this far, it means that the reader will want to use
48366   ** the WAL to get at content from recent commits.  The job now is
48367   ** to select one of the aReadMark[] entries that is closest to
48368   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
48369   */
48370   mxReadMark = 0;
48371   mxI = 0;
48372   for(i=1; i<WAL_NREADER; i++){
48373     u32 thisMark = pInfo->aReadMark[i];
48374     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
48375       assert( thisMark!=READMARK_NOT_USED );
48376       mxReadMark = thisMark;
48377       mxI = i;
48378     }
48379   }
48380   /* There was once an "if" here. The extra "{" is to preserve indentation. */
48381   {
48382     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
48383      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
48384     ){
48385       for(i=1; i<WAL_NREADER; i++){
48386         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
48387         if( rc==SQLCIPHER_OK ){
48388           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
48389           mxI = i;
48390           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
48391           break;
48392         }else if( rc!=SQLCIPHER_BUSY ){
48393           return rc;
48394         }
48395       }
48396     }
48397     if( mxI==0 ){
48398       assert( rc==SQLCIPHER_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
48399       return rc==SQLCIPHER_BUSY ? WAL_RETRY : SQLCIPHER_READONLY_CANTLOCK;
48400     }
48401
48402     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
48403     if( rc ){
48404       return rc==SQLCIPHER_BUSY ? WAL_RETRY : rc;
48405     }
48406     /* Now that the read-lock has been obtained, check that neither the
48407     ** value in the aReadMark[] array or the contents of the wal-index
48408     ** header have changed.
48409     **
48410     ** It is necessary to check that the wal-index header did not change
48411     ** between the time it was read and when the shared-lock was obtained
48412     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
48413     ** that the log file may have been wrapped by a writer, or that frames
48414     ** that occur later in the log than pWal->hdr.mxFrame may have been
48415     ** copied into the database by a checkpointer. If either of these things
48416     ** happened, then reading the database with the current value of
48417     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
48418     ** instead.
48419     **
48420     ** This does not guarantee that the copy of the wal-index header is up to
48421     ** date before proceeding. That would not be possible without somehow
48422     ** blocking writers. It only guarantees that a dangerous checkpoint or 
48423     ** log-wrap (either of which would require an exclusive lock on
48424     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
48425     */
48426     walShmBarrier(pWal);
48427     if( pInfo->aReadMark[mxI]!=mxReadMark
48428      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
48429     ){
48430       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
48431       return WAL_RETRY;
48432     }else{
48433       assert( mxReadMark<=pWal->hdr.mxFrame );
48434       pWal->readLock = (i16)mxI;
48435     }
48436   }
48437   return rc;
48438 }
48439
48440 /*
48441 ** Begin a read transaction on the database.
48442 **
48443 ** This routine used to be called sqlcipher3OpenSnapshot() and with good reason:
48444 ** it takes a snapshot of the state of the WAL and wal-index for the current
48445 ** instant in time.  The current thread will continue to use this snapshot.
48446 ** Other threads might append new content to the WAL and wal-index but
48447 ** that extra content is ignored by the current thread.
48448 **
48449 ** If the database contents have changes since the previous read
48450 ** transaction, then *pChanged is set to 1 before returning.  The
48451 ** Pager layer will use this to know that is cache is stale and
48452 ** needs to be flushed.
48453 */
48454 SQLCIPHER_PRIVATE int sqlcipher3WalBeginReadTransaction(Wal *pWal, int *pChanged){
48455   int rc;                         /* Return code */
48456   int cnt = 0;                    /* Number of TryBeginRead attempts */
48457
48458   do{
48459     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
48460   }while( rc==WAL_RETRY );
48461   testcase( (rc&0xff)==SQLCIPHER_BUSY );
48462   testcase( (rc&0xff)==SQLCIPHER_IOERR );
48463   testcase( rc==SQLCIPHER_PROTOCOL );
48464   testcase( rc==SQLCIPHER_OK );
48465   return rc;
48466 }
48467
48468 /*
48469 ** Finish with a read transaction.  All this does is release the
48470 ** read-lock.
48471 */
48472 SQLCIPHER_PRIVATE void sqlcipher3WalEndReadTransaction(Wal *pWal){
48473   sqlcipher3WalEndWriteTransaction(pWal);
48474   if( pWal->readLock>=0 ){
48475     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
48476     pWal->readLock = -1;
48477   }
48478 }
48479
48480 /*
48481 ** Read a page from the WAL, if it is present in the WAL and if the 
48482 ** current read transaction is configured to use the WAL.  
48483 **
48484 ** The *pInWal is set to 1 if the requested page is in the WAL and
48485 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
48486 ** the WAL and needs to be read out of the database.
48487 */
48488 SQLCIPHER_PRIVATE int sqlcipher3WalRead(
48489   Wal *pWal,                      /* WAL handle */
48490   Pgno pgno,                      /* Database page number to read data for */
48491   int *pInWal,                    /* OUT: True if data is read from WAL */
48492   int nOut,                       /* Size of buffer pOut in bytes */
48493   u8 *pOut                        /* Buffer to write page data to */
48494 ){
48495   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
48496   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
48497   int iHash;                      /* Used to loop through N hash tables */
48498
48499   /* This routine is only be called from within a read transaction. */
48500   assert( pWal->readLock>=0 || pWal->lockError );
48501
48502   /* If the "last page" field of the wal-index header snapshot is 0, then
48503   ** no data will be read from the wal under any circumstances. Return early
48504   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
48505   ** then the WAL is ignored by the reader so return early, as if the 
48506   ** WAL were empty.
48507   */
48508   if( iLast==0 || pWal->readLock==0 ){
48509     *pInWal = 0;
48510     return SQLCIPHER_OK;
48511   }
48512
48513   /* Search the hash table or tables for an entry matching page number
48514   ** pgno. Each iteration of the following for() loop searches one
48515   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
48516   **
48517   ** This code might run concurrently to the code in walIndexAppend()
48518   ** that adds entries to the wal-index (and possibly to this hash 
48519   ** table). This means the value just read from the hash 
48520   ** slot (aHash[iKey]) may have been added before or after the 
48521   ** current read transaction was opened. Values added after the
48522   ** read transaction was opened may have been written incorrectly -
48523   ** i.e. these slots may contain garbage data. However, we assume
48524   ** that any slots written before the current read transaction was
48525   ** opened remain unmodified.
48526   **
48527   ** For the reasons above, the if(...) condition featured in the inner
48528   ** loop of the following block is more stringent that would be required 
48529   ** if we had exclusive access to the hash-table:
48530   **
48531   **   (aPgno[iFrame]==pgno): 
48532   **     This condition filters out normal hash-table collisions.
48533   **
48534   **   (iFrame<=iLast): 
48535   **     This condition filters out entries that were added to the hash
48536   **     table after the current read-transaction had started.
48537   */
48538   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
48539     volatile ht_slot *aHash;      /* Pointer to hash table */
48540     volatile u32 *aPgno;          /* Pointer to array of page numbers */
48541     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
48542     int iKey;                     /* Hash slot index */
48543     int nCollide;                 /* Number of hash collisions remaining */
48544     int rc;                       /* Error code */
48545
48546     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
48547     if( rc!=SQLCIPHER_OK ){
48548       return rc;
48549     }
48550     nCollide = HASHTABLE_NSLOT;
48551     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
48552       u32 iFrame = aHash[iKey] + iZero;
48553       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
48554         assert( iFrame>iRead );
48555         iRead = iFrame;
48556       }
48557       if( (nCollide--)==0 ){
48558         return SQLCIPHER_CORRUPT_BKPT;
48559       }
48560     }
48561   }
48562
48563 #ifdef SQLCIPHER_ENABLE_EXPENSIVE_ASSERT
48564   /* If expensive assert() statements are available, do a linear search
48565   ** of the wal-index file content. Make sure the results agree with the
48566   ** result obtained using the hash indexes above.  */
48567   {
48568     u32 iRead2 = 0;
48569     u32 iTest;
48570     for(iTest=iLast; iTest>0; iTest--){
48571       if( walFramePgno(pWal, iTest)==pgno ){
48572         iRead2 = iTest;
48573         break;
48574       }
48575     }
48576     assert( iRead==iRead2 );
48577   }
48578 #endif
48579
48580   /* If iRead is non-zero, then it is the log frame number that contains the
48581   ** required page. Read and return data from the log file.
48582   */
48583   if( iRead ){
48584     int sz;
48585     i64 iOffset;
48586     sz = pWal->hdr.szPage;
48587     sz = (sz&0xfe00) + ((sz&0x0001)<<16);
48588     testcase( sz<=32768 );
48589     testcase( sz>=65536 );
48590     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
48591     *pInWal = 1;
48592     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
48593     return sqlcipher3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
48594   }
48595
48596   *pInWal = 0;
48597   return SQLCIPHER_OK;
48598 }
48599
48600
48601 /* 
48602 ** Return the size of the database in pages (or zero, if unknown).
48603 */
48604 SQLCIPHER_PRIVATE Pgno sqlcipher3WalDbsize(Wal *pWal){
48605   if( pWal && ALWAYS(pWal->readLock>=0) ){
48606     return pWal->hdr.nPage;
48607   }
48608   return 0;
48609 }
48610
48611
48612 /* 
48613 ** This function starts a write transaction on the WAL.
48614 **
48615 ** A read transaction must have already been started by a prior call
48616 ** to sqlcipher3WalBeginReadTransaction().
48617 **
48618 ** If another thread or process has written into the database since
48619 ** the read transaction was started, then it is not possible for this
48620 ** thread to write as doing so would cause a fork.  So this routine
48621 ** returns SQLCIPHER_BUSY in that case and no write transaction is started.
48622 **
48623 ** There can only be a single writer active at a time.
48624 */
48625 SQLCIPHER_PRIVATE int sqlcipher3WalBeginWriteTransaction(Wal *pWal){
48626   int rc;
48627
48628   /* Cannot start a write transaction without first holding a read
48629   ** transaction. */
48630   assert( pWal->readLock>=0 );
48631
48632   if( pWal->readOnly ){
48633     return SQLCIPHER_READONLY;
48634   }
48635
48636   /* Only one writer allowed at a time.  Get the write lock.  Return
48637   ** SQLCIPHER_BUSY if unable.
48638   */
48639   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
48640   if( rc ){
48641     return rc;
48642   }
48643   pWal->writeLock = 1;
48644
48645   /* If another connection has written to the database file since the
48646   ** time the read transaction on this connection was started, then
48647   ** the write is disallowed.
48648   */
48649   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
48650     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
48651     pWal->writeLock = 0;
48652     rc = SQLCIPHER_BUSY;
48653   }
48654
48655   return rc;
48656 }
48657
48658 /*
48659 ** End a write transaction.  The commit has already been done.  This
48660 ** routine merely releases the lock.
48661 */
48662 SQLCIPHER_PRIVATE int sqlcipher3WalEndWriteTransaction(Wal *pWal){
48663   if( pWal->writeLock ){
48664     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
48665     pWal->writeLock = 0;
48666   }
48667   return SQLCIPHER_OK;
48668 }
48669
48670 /*
48671 ** If any data has been written (but not committed) to the log file, this
48672 ** function moves the write-pointer back to the start of the transaction.
48673 **
48674 ** Additionally, the callback function is invoked for each frame written
48675 ** to the WAL since the start of the transaction. If the callback returns
48676 ** other than SQLCIPHER_OK, it is not invoked again and the error code is
48677 ** returned to the caller.
48678 **
48679 ** Otherwise, if the callback function does not return an error, this
48680 ** function returns SQLCIPHER_OK.
48681 */
48682 SQLCIPHER_PRIVATE int sqlcipher3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
48683   int rc = SQLCIPHER_OK;
48684   if( ALWAYS(pWal->writeLock) ){
48685     Pgno iMax = pWal->hdr.mxFrame;
48686     Pgno iFrame;
48687   
48688     /* Restore the clients cache of the wal-index header to the state it
48689     ** was in before the client began writing to the database. 
48690     */
48691     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
48692
48693     for(iFrame=pWal->hdr.mxFrame+1; 
48694         ALWAYS(rc==SQLCIPHER_OK) && iFrame<=iMax; 
48695         iFrame++
48696     ){
48697       /* This call cannot fail. Unless the page for which the page number
48698       ** is passed as the second argument is (a) in the cache and 
48699       ** (b) has an outstanding reference, then xUndo is either a no-op
48700       ** (if (a) is false) or simply expels the page from the cache (if (b)
48701       ** is false).
48702       **
48703       ** If the upper layer is doing a rollback, it is guaranteed that there
48704       ** are no outstanding references to any page other than page 1. And
48705       ** page 1 is never written to the log until the transaction is
48706       ** committed. As a result, the call to xUndo may not fail.
48707       */
48708       assert( walFramePgno(pWal, iFrame)!=1 );
48709       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
48710     }
48711     walCleanupHash(pWal);
48712   }
48713   assert( rc==SQLCIPHER_OK );
48714   return rc;
48715 }
48716
48717 /* 
48718 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
48719 ** values. This function populates the array with values required to 
48720 ** "rollback" the write position of the WAL handle back to the current 
48721 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
48722 */
48723 SQLCIPHER_PRIVATE void sqlcipher3WalSavepoint(Wal *pWal, u32 *aWalData){
48724   assert( pWal->writeLock );
48725   aWalData[0] = pWal->hdr.mxFrame;
48726   aWalData[1] = pWal->hdr.aFrameCksum[0];
48727   aWalData[2] = pWal->hdr.aFrameCksum[1];
48728   aWalData[3] = pWal->nCkpt;
48729 }
48730
48731 /* 
48732 ** Move the write position of the WAL back to the point identified by
48733 ** the values in the aWalData[] array. aWalData must point to an array
48734 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
48735 ** by a call to WalSavepoint().
48736 */
48737 SQLCIPHER_PRIVATE int sqlcipher3WalSavepointUndo(Wal *pWal, u32 *aWalData){
48738   int rc = SQLCIPHER_OK;
48739
48740   assert( pWal->writeLock );
48741   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
48742
48743   if( aWalData[3]!=pWal->nCkpt ){
48744     /* This savepoint was opened immediately after the write-transaction
48745     ** was started. Right after that, the writer decided to wrap around
48746     ** to the start of the log. Update the savepoint values to match.
48747     */
48748     aWalData[0] = 0;
48749     aWalData[3] = pWal->nCkpt;
48750   }
48751
48752   if( aWalData[0]<pWal->hdr.mxFrame ){
48753     pWal->hdr.mxFrame = aWalData[0];
48754     pWal->hdr.aFrameCksum[0] = aWalData[1];
48755     pWal->hdr.aFrameCksum[1] = aWalData[2];
48756     walCleanupHash(pWal);
48757   }
48758
48759   return rc;
48760 }
48761
48762 /*
48763 ** This function is called just before writing a set of frames to the log
48764 ** file (see sqlcipher3WalFrames()). It checks to see if, instead of appending
48765 ** to the current log file, it is possible to overwrite the start of the
48766 ** existing log file with the new frames (i.e. "reset" the log). If so,
48767 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
48768 ** unchanged.
48769 **
48770 ** SQLCIPHER_OK is returned if no error is encountered (regardless of whether
48771 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
48772 ** if an error occurs.
48773 */
48774 static int walRestartLog(Wal *pWal){
48775   int rc = SQLCIPHER_OK;
48776   int cnt;
48777
48778   if( pWal->readLock==0 ){
48779     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
48780     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
48781     if( pInfo->nBackfill>0 ){
48782       u32 salt1;
48783       sqlcipher3_randomness(4, &salt1);
48784       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48785       if( rc==SQLCIPHER_OK ){
48786         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
48787         ** readers are currently using the WAL), then the transactions
48788         ** frames will overwrite the start of the existing log. Update the
48789         ** wal-index header to reflect this.
48790         **
48791         ** In theory it would be Ok to update the cache of the header only
48792         ** at this point. But updating the actual wal-index header is also
48793         ** safe and means there is no special case for sqlcipher3WalUndo()
48794         ** to handle if this transaction is rolled back.
48795         */
48796         int i;                    /* Loop counter */
48797         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
48798
48799         /* Limit the size of WAL file if the journal_size_limit PRAGMA is
48800         ** set to a non-negative value.  Log errors encountered
48801         ** during the truncation attempt. */
48802         if( pWal->mxWalSize>=0 ){
48803           i64 sz;
48804           int rx;
48805           sqlcipher3BeginBenignMalloc();
48806           rx = sqlcipher3OsFileSize(pWal->pWalFd, &sz);
48807           if( rx==SQLCIPHER_OK && (sz > pWal->mxWalSize) ){
48808             rx = sqlcipher3OsTruncate(pWal->pWalFd, pWal->mxWalSize);
48809           }
48810           sqlcipher3EndBenignMalloc();
48811           if( rx ){
48812             sqlcipher3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
48813           }
48814         }
48815
48816         pWal->nCkpt++;
48817         pWal->hdr.mxFrame = 0;
48818         sqlcipher3Put4byte((u8*)&aSalt[0], 1 + sqlcipher3Get4byte((u8*)&aSalt[0]));
48819         aSalt[1] = salt1;
48820         walIndexWriteHdr(pWal);
48821         pInfo->nBackfill = 0;
48822         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
48823         assert( pInfo->aReadMark[0]==0 );
48824         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48825       }else if( rc!=SQLCIPHER_BUSY ){
48826         return rc;
48827       }
48828     }
48829     walUnlockShared(pWal, WAL_READ_LOCK(0));
48830     pWal->readLock = -1;
48831     cnt = 0;
48832     do{
48833       int notUsed;
48834       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
48835     }while( rc==WAL_RETRY );
48836     assert( (rc&0xff)!=SQLCIPHER_BUSY ); /* BUSY not possible when useWal==1 */
48837     testcase( (rc&0xff)==SQLCIPHER_IOERR );
48838     testcase( rc==SQLCIPHER_PROTOCOL );
48839     testcase( rc==SQLCIPHER_OK );
48840   }
48841   return rc;
48842 }
48843
48844 /* 
48845 ** Write a set of frames to the log. The caller must hold the write-lock
48846 ** on the log file (obtained using sqlcipher3WalBeginWriteTransaction()).
48847 */
48848 SQLCIPHER_PRIVATE int sqlcipher3WalFrames(
48849   Wal *pWal,                      /* Wal handle to write to */
48850   int szPage,                     /* Database page-size in bytes */
48851   PgHdr *pList,                   /* List of dirty pages to write */
48852   Pgno nTruncate,                 /* Database size after this commit */
48853   int isCommit,                   /* True if this is a commit */
48854   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
48855 ){
48856   int rc;                         /* Used to catch return codes */
48857   u32 iFrame;                     /* Next frame address */
48858   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
48859   PgHdr *p;                       /* Iterator to run through pList with. */
48860   PgHdr *pLast = 0;               /* Last frame in list */
48861   int nLast = 0;                  /* Number of extra copies of last page */
48862
48863   assert( pList );
48864   assert( pWal->writeLock );
48865
48866 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
48867   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
48868     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
48869               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
48870   }
48871 #endif
48872
48873   /* See if it is possible to write these frames into the start of the
48874   ** log file, instead of appending to it at pWal->hdr.mxFrame.
48875   */
48876   if( SQLCIPHER_OK!=(rc = walRestartLog(pWal)) ){
48877     return rc;
48878   }
48879
48880   /* If this is the first frame written into the log, write the WAL
48881   ** header to the start of the WAL file. See comments at the top of
48882   ** this source file for a description of the WAL header format.
48883   */
48884   iFrame = pWal->hdr.mxFrame;
48885   if( iFrame==0 ){
48886     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
48887     u32 aCksum[2];                /* Checksum for wal-header */
48888
48889     sqlcipher3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLCIPHER_BIGENDIAN));
48890     sqlcipher3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
48891     sqlcipher3Put4byte(&aWalHdr[8], szPage);
48892     sqlcipher3Put4byte(&aWalHdr[12], pWal->nCkpt);
48893     sqlcipher3_randomness(8, pWal->hdr.aSalt);
48894     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
48895     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
48896     sqlcipher3Put4byte(&aWalHdr[24], aCksum[0]);
48897     sqlcipher3Put4byte(&aWalHdr[28], aCksum[1]);
48898     
48899     pWal->szPage = szPage;
48900     pWal->hdr.bigEndCksum = SQLCIPHER_BIGENDIAN;
48901     pWal->hdr.aFrameCksum[0] = aCksum[0];
48902     pWal->hdr.aFrameCksum[1] = aCksum[1];
48903
48904     rc = sqlcipher3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
48905     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
48906     if( rc!=SQLCIPHER_OK ){
48907       return rc;
48908     }
48909   }
48910   assert( (int)pWal->szPage==szPage );
48911
48912   /* Write the log file. */
48913   for(p=pList; p; p=p->pDirty){
48914     u32 nDbsize;                  /* Db-size field for frame header */
48915     i64 iOffset;                  /* Write offset in log file */
48916     void *pData;
48917    
48918     iOffset = walFrameOffset(++iFrame, szPage);
48919     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
48920     
48921     /* Populate and write the frame header */
48922     nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
48923 #if defined(SQLCIPHER_HAS_CODEC)
48924     if( (pData = sqlcipher3PagerCodec(p))==0 ) return SQLCIPHER_NOMEM;
48925 #else
48926     pData = p->pData;
48927 #endif
48928     walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
48929     rc = sqlcipher3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
48930     if( rc!=SQLCIPHER_OK ){
48931       return rc;
48932     }
48933
48934     /* Write the page data */
48935     rc = sqlcipher3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
48936     if( rc!=SQLCIPHER_OK ){
48937       return rc;
48938     }
48939     pLast = p;
48940   }
48941
48942   /* Sync the log file if the 'isSync' flag was specified. */
48943   if( sync_flags ){
48944     i64 iSegment = sqlcipher3OsSectorSize(pWal->pWalFd);
48945     i64 iOffset = walFrameOffset(iFrame+1, szPage);
48946
48947     assert( isCommit );
48948     assert( iSegment>0 );
48949
48950     iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
48951     while( iOffset<iSegment ){
48952       void *pData;
48953 #if defined(SQLCIPHER_HAS_CODEC)
48954       if( (pData = sqlcipher3PagerCodec(pLast))==0 ) return SQLCIPHER_NOMEM;
48955 #else
48956       pData = pLast->pData;
48957 #endif
48958       walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
48959       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
48960       rc = sqlcipher3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
48961       if( rc!=SQLCIPHER_OK ){
48962         return rc;
48963       }
48964       iOffset += WAL_FRAME_HDRSIZE;
48965       rc = sqlcipher3OsWrite(pWal->pWalFd, pData, szPage, iOffset); 
48966       if( rc!=SQLCIPHER_OK ){
48967         return rc;
48968       }
48969       nLast++;
48970       iOffset += szPage;
48971     }
48972
48973     rc = sqlcipher3OsSync(pWal->pWalFd, sync_flags);
48974   }
48975
48976   /* Append data to the wal-index. It is not necessary to lock the 
48977   ** wal-index to do this as the SQLCIPHER_SHM_WRITE lock held on the wal-index
48978   ** guarantees that there are no other writers, and no data that may
48979   ** be in use by existing readers is being overwritten.
48980   */
48981   iFrame = pWal->hdr.mxFrame;
48982   for(p=pList; p && rc==SQLCIPHER_OK; p=p->pDirty){
48983     iFrame++;
48984     rc = walIndexAppend(pWal, iFrame, p->pgno);
48985   }
48986   while( nLast>0 && rc==SQLCIPHER_OK ){
48987     iFrame++;
48988     nLast--;
48989     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
48990   }
48991
48992   if( rc==SQLCIPHER_OK ){
48993     /* Update the private copy of the header. */
48994     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
48995     testcase( szPage<=32768 );
48996     testcase( szPage>=65536 );
48997     pWal->hdr.mxFrame = iFrame;
48998     if( isCommit ){
48999       pWal->hdr.iChange++;
49000       pWal->hdr.nPage = nTruncate;
49001     }
49002     /* If this is a commit, update the wal-index header too. */
49003     if( isCommit ){
49004       walIndexWriteHdr(pWal);
49005       pWal->iCallback = iFrame;
49006     }
49007   }
49008
49009   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
49010   return rc;
49011 }
49012
49013 /* 
49014 ** This routine is called to implement sqlcipher3_wal_checkpoint() and
49015 ** related interfaces.
49016 **
49017 ** Obtain a CHECKPOINT lock and then backfill as much information as
49018 ** we can from WAL into the database.
49019 **
49020 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
49021 ** callback. In this case this function runs a blocking checkpoint.
49022 */
49023 SQLCIPHER_PRIVATE int sqlcipher3WalCheckpoint(
49024   Wal *pWal,                      /* Wal connection */
49025   int eMode,                      /* PASSIVE, FULL or RESTART */
49026   int (*xBusy)(void*),            /* Function to call when busy */
49027   void *pBusyArg,                 /* Context argument for xBusyHandler */
49028   int sync_flags,                 /* Flags to sync db file with (or 0) */
49029   int nBuf,                       /* Size of temporary buffer */
49030   u8 *zBuf,                       /* Temporary buffer to use */
49031   int *pnLog,                     /* OUT: Number of frames in WAL */
49032   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
49033 ){
49034   int rc;                         /* Return code */
49035   int isChanged = 0;              /* True if a new wal-index header is loaded */
49036   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
49037
49038   assert( pWal->ckptLock==0 );
49039   assert( pWal->writeLock==0 );
49040
49041   if( pWal->readOnly ) return SQLCIPHER_READONLY;
49042   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
49043   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
49044   if( rc ){
49045     /* Usually this is SQLCIPHER_BUSY meaning that another thread or process
49046     ** is already running a checkpoint, or maybe a recovery.  But it might
49047     ** also be SQLCIPHER_IOERR. */
49048     return rc;
49049   }
49050   pWal->ckptLock = 1;
49051
49052   /* If this is a blocking-checkpoint, then obtain the write-lock as well
49053   ** to prevent any writers from running while the checkpoint is underway.
49054   ** This has to be done before the call to walIndexReadHdr() below.
49055   **
49056   ** If the writer lock cannot be obtained, then a passive checkpoint is
49057   ** run instead. Since the checkpointer is not holding the writer lock,
49058   ** there is no point in blocking waiting for any readers. Assuming no 
49059   ** other error occurs, this function will return SQLCIPHER_BUSY to the caller.
49060   */
49061   if( eMode!=SQLCIPHER_CHECKPOINT_PASSIVE ){
49062     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
49063     if( rc==SQLCIPHER_OK ){
49064       pWal->writeLock = 1;
49065     }else if( rc==SQLCIPHER_BUSY ){
49066       eMode2 = SQLCIPHER_CHECKPOINT_PASSIVE;
49067       rc = SQLCIPHER_OK;
49068     }
49069   }
49070
49071   /* Read the wal-index header. */
49072   if( rc==SQLCIPHER_OK ){
49073     rc = walIndexReadHdr(pWal, &isChanged);
49074   }
49075
49076   /* Copy data from the log to the database file. */
49077   if( rc==SQLCIPHER_OK ){
49078     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
49079       rc = SQLCIPHER_CORRUPT_BKPT;
49080     }else{
49081       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
49082     }
49083
49084     /* If no error occurred, set the output variables. */
49085     if( rc==SQLCIPHER_OK || rc==SQLCIPHER_BUSY ){
49086       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
49087       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
49088     }
49089   }
49090
49091   if( isChanged ){
49092     /* If a new wal-index header was loaded before the checkpoint was 
49093     ** performed, then the pager-cache associated with pWal is now
49094     ** out of date. So zero the cached wal-index header to ensure that
49095     ** next time the pager opens a snapshot on this database it knows that
49096     ** the cache needs to be reset.
49097     */
49098     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
49099   }
49100
49101   /* Release the locks. */
49102   sqlcipher3WalEndWriteTransaction(pWal);
49103   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
49104   pWal->ckptLock = 0;
49105   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
49106   return (rc==SQLCIPHER_OK && eMode!=eMode2 ? SQLCIPHER_BUSY : rc);
49107 }
49108
49109 /* Return the value to pass to a sqlcipher3_wal_hook callback, the
49110 ** number of frames in the WAL at the point of the last commit since
49111 ** sqlcipher3WalCallback() was called.  If no commits have occurred since
49112 ** the last call, then return 0.
49113 */
49114 SQLCIPHER_PRIVATE int sqlcipher3WalCallback(Wal *pWal){
49115   u32 ret = 0;
49116   if( pWal ){
49117     ret = pWal->iCallback;
49118     pWal->iCallback = 0;
49119   }
49120   return (int)ret;
49121 }
49122
49123 /*
49124 ** This function is called to change the WAL subsystem into or out
49125 ** of locking_mode=EXCLUSIVE.
49126 **
49127 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
49128 ** into locking_mode=NORMAL.  This means that we must acquire a lock
49129 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
49130 ** or if the acquisition of the lock fails, then return 0.  If the
49131 ** transition out of exclusive-mode is successful, return 1.  This
49132 ** operation must occur while the pager is still holding the exclusive
49133 ** lock on the main database file.
49134 **
49135 ** If op is one, then change from locking_mode=NORMAL into 
49136 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
49137 ** be released.  Return 1 if the transition is made and 0 if the
49138 ** WAL is already in exclusive-locking mode - meaning that this
49139 ** routine is a no-op.  The pager must already hold the exclusive lock
49140 ** on the main database file before invoking this operation.
49141 **
49142 ** If op is negative, then do a dry-run of the op==1 case but do
49143 ** not actually change anything. The pager uses this to see if it
49144 ** should acquire the database exclusive lock prior to invoking
49145 ** the op==1 case.
49146 */
49147 SQLCIPHER_PRIVATE int sqlcipher3WalExclusiveMode(Wal *pWal, int op){
49148   int rc;
49149   assert( pWal->writeLock==0 );
49150   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
49151
49152   /* pWal->readLock is usually set, but might be -1 if there was a 
49153   ** prior error while attempting to acquire are read-lock. This cannot 
49154   ** happen if the connection is actually in exclusive mode (as no xShmLock
49155   ** locks are taken in this case). Nor should the pager attempt to
49156   ** upgrade to exclusive-mode following such an error.
49157   */
49158   assert( pWal->readLock>=0 || pWal->lockError );
49159   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
49160
49161   if( op==0 ){
49162     if( pWal->exclusiveMode ){
49163       pWal->exclusiveMode = 0;
49164       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLCIPHER_OK ){
49165         pWal->exclusiveMode = 1;
49166       }
49167       rc = pWal->exclusiveMode==0;
49168     }else{
49169       /* Already in locking_mode=NORMAL */
49170       rc = 0;
49171     }
49172   }else if( op>0 ){
49173     assert( pWal->exclusiveMode==0 );
49174     assert( pWal->readLock>=0 );
49175     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
49176     pWal->exclusiveMode = 1;
49177     rc = 1;
49178   }else{
49179     rc = pWal->exclusiveMode==0;
49180   }
49181   return rc;
49182 }
49183
49184 /* 
49185 ** Return true if the argument is non-NULL and the WAL module is using
49186 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
49187 ** WAL module is using shared-memory, return false. 
49188 */
49189 SQLCIPHER_PRIVATE int sqlcipher3WalHeapMemory(Wal *pWal){
49190   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
49191 }
49192
49193 #endif /* #ifndef SQLCIPHER_OMIT_WAL */
49194
49195 /************** End of wal.c *************************************************/
49196 /************** Begin file btmutex.c *****************************************/
49197 /*
49198 ** 2007 August 27
49199 **
49200 ** The author disclaims copyright to this source code.  In place of
49201 ** a legal notice, here is a blessing:
49202 **
49203 **    May you do good and not evil.
49204 **    May you find forgiveness for yourself and forgive others.
49205 **    May you share freely, never taking more than you give.
49206 **
49207 *************************************************************************
49208 **
49209 ** This file contains code used to implement mutexes on Btree objects.
49210 ** This code really belongs in btree.c.  But btree.c is getting too
49211 ** big and we want to break it down some.  This packaged seemed like
49212 ** a good breakout.
49213 */
49214 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
49215 #if SQLCIPHER_THREADSAFE
49216
49217 /*
49218 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
49219 ** set BtShared.db to the database handle associated with p and the
49220 ** p->locked boolean to true.
49221 */
49222 static void lockBtreeMutex(Btree *p){
49223   assert( p->locked==0 );
49224   assert( sqlcipher3_mutex_notheld(p->pBt->mutex) );
49225   assert( sqlcipher3_mutex_held(p->db->mutex) );
49226
49227   sqlcipher3_mutex_enter(p->pBt->mutex);
49228   p->pBt->db = p->db;
49229   p->locked = 1;
49230 }
49231
49232 /*
49233 ** Release the BtShared mutex associated with B-Tree handle p and
49234 ** clear the p->locked boolean.
49235 */
49236 static void unlockBtreeMutex(Btree *p){
49237   BtShared *pBt = p->pBt;
49238   assert( p->locked==1 );
49239   assert( sqlcipher3_mutex_held(pBt->mutex) );
49240   assert( sqlcipher3_mutex_held(p->db->mutex) );
49241   assert( p->db==pBt->db );
49242
49243   sqlcipher3_mutex_leave(pBt->mutex);
49244   p->locked = 0;
49245 }
49246
49247 /*
49248 ** Enter a mutex on the given BTree object.
49249 **
49250 ** If the object is not sharable, then no mutex is ever required
49251 ** and this routine is a no-op.  The underlying mutex is non-recursive.
49252 ** But we keep a reference count in Btree.wantToLock so the behavior
49253 ** of this interface is recursive.
49254 **
49255 ** To avoid deadlocks, multiple Btrees are locked in the same order
49256 ** by all database connections.  The p->pNext is a list of other
49257 ** Btrees belonging to the same database connection as the p Btree
49258 ** which need to be locked after p.  If we cannot get a lock on
49259 ** p, then first unlock all of the others on p->pNext, then wait
49260 ** for the lock to become available on p, then relock all of the
49261 ** subsequent Btrees that desire a lock.
49262 */
49263 SQLCIPHER_PRIVATE void sqlcipher3BtreeEnter(Btree *p){
49264   Btree *pLater;
49265
49266   /* Some basic sanity checking on the Btree.  The list of Btrees
49267   ** connected by pNext and pPrev should be in sorted order by
49268   ** Btree.pBt value. All elements of the list should belong to
49269   ** the same connection. Only shared Btrees are on the list. */
49270   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
49271   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
49272   assert( p->pNext==0 || p->pNext->db==p->db );
49273   assert( p->pPrev==0 || p->pPrev->db==p->db );
49274   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
49275
49276   /* Check for locking consistency */
49277   assert( !p->locked || p->wantToLock>0 );
49278   assert( p->sharable || p->wantToLock==0 );
49279
49280   /* We should already hold a lock on the database connection */
49281   assert( sqlcipher3_mutex_held(p->db->mutex) );
49282
49283   /* Unless the database is sharable and unlocked, then BtShared.db
49284   ** should already be set correctly. */
49285   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
49286
49287   if( !p->sharable ) return;
49288   p->wantToLock++;
49289   if( p->locked ) return;
49290
49291   /* In most cases, we should be able to acquire the lock we
49292   ** want without having to go throught the ascending lock
49293   ** procedure that follows.  Just be sure not to block.
49294   */
49295   if( sqlcipher3_mutex_try(p->pBt->mutex)==SQLCIPHER_OK ){
49296     p->pBt->db = p->db;
49297     p->locked = 1;
49298     return;
49299   }
49300
49301   /* To avoid deadlock, first release all locks with a larger
49302   ** BtShared address.  Then acquire our lock.  Then reacquire
49303   ** the other BtShared locks that we used to hold in ascending
49304   ** order.
49305   */
49306   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49307     assert( pLater->sharable );
49308     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
49309     assert( !pLater->locked || pLater->wantToLock>0 );
49310     if( pLater->locked ){
49311       unlockBtreeMutex(pLater);
49312     }
49313   }
49314   lockBtreeMutex(p);
49315   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49316     if( pLater->wantToLock ){
49317       lockBtreeMutex(pLater);
49318     }
49319   }
49320 }
49321
49322 /*
49323 ** Exit the recursive mutex on a Btree.
49324 */
49325 SQLCIPHER_PRIVATE void sqlcipher3BtreeLeave(Btree *p){
49326   if( p->sharable ){
49327     assert( p->wantToLock>0 );
49328     p->wantToLock--;
49329     if( p->wantToLock==0 ){
49330       unlockBtreeMutex(p);
49331     }
49332   }
49333 }
49334
49335 #ifndef NDEBUG
49336 /*
49337 ** Return true if the BtShared mutex is held on the btree, or if the
49338 ** B-Tree is not marked as sharable.
49339 **
49340 ** This routine is used only from within assert() statements.
49341 */
49342 SQLCIPHER_PRIVATE int sqlcipher3BtreeHoldsMutex(Btree *p){
49343   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
49344   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
49345   assert( p->sharable==0 || p->locked==0 || sqlcipher3_mutex_held(p->pBt->mutex) );
49346   assert( p->sharable==0 || p->locked==0 || sqlcipher3_mutex_held(p->db->mutex) );
49347
49348   return (p->sharable==0 || p->locked);
49349 }
49350 #endif
49351
49352
49353 #ifndef SQLCIPHER_OMIT_INCRBLOB
49354 /*
49355 ** Enter and leave a mutex on a Btree given a cursor owned by that
49356 ** Btree.  These entry points are used by incremental I/O and can be
49357 ** omitted if that module is not used.
49358 */
49359 SQLCIPHER_PRIVATE void sqlcipher3BtreeEnterCursor(BtCursor *pCur){
49360   sqlcipher3BtreeEnter(pCur->pBtree);
49361 }
49362 SQLCIPHER_PRIVATE void sqlcipher3BtreeLeaveCursor(BtCursor *pCur){
49363   sqlcipher3BtreeLeave(pCur->pBtree);
49364 }
49365 #endif /* SQLCIPHER_OMIT_INCRBLOB */
49366
49367
49368 /*
49369 ** Enter the mutex on every Btree associated with a database
49370 ** connection.  This is needed (for example) prior to parsing
49371 ** a statement since we will be comparing table and column names
49372 ** against all schemas and we do not want those schemas being
49373 ** reset out from under us.
49374 **
49375 ** There is a corresponding leave-all procedures.
49376 **
49377 ** Enter the mutexes in accending order by BtShared pointer address
49378 ** to avoid the possibility of deadlock when two threads with
49379 ** two or more btrees in common both try to lock all their btrees
49380 ** at the same instant.
49381 */
49382 SQLCIPHER_PRIVATE void sqlcipher3BtreeEnterAll(sqlcipher3 *db){
49383   int i;
49384   Btree *p;
49385   assert( sqlcipher3_mutex_held(db->mutex) );
49386   for(i=0; i<db->nDb; i++){
49387     p = db->aDb[i].pBt;
49388     if( p ) sqlcipher3BtreeEnter(p);
49389   }
49390 }
49391 SQLCIPHER_PRIVATE void sqlcipher3BtreeLeaveAll(sqlcipher3 *db){
49392   int i;
49393   Btree *p;
49394   assert( sqlcipher3_mutex_held(db->mutex) );
49395   for(i=0; i<db->nDb; i++){
49396     p = db->aDb[i].pBt;
49397     if( p ) sqlcipher3BtreeLeave(p);
49398   }
49399 }
49400
49401 /*
49402 ** Return true if a particular Btree requires a lock.  Return FALSE if
49403 ** no lock is ever required since it is not sharable.
49404 */
49405 SQLCIPHER_PRIVATE int sqlcipher3BtreeSharable(Btree *p){
49406   return p->sharable;
49407 }
49408
49409 #ifndef NDEBUG
49410 /*
49411 ** Return true if the current thread holds the database connection
49412 ** mutex and all required BtShared mutexes.
49413 **
49414 ** This routine is used inside assert() statements only.
49415 */
49416 SQLCIPHER_PRIVATE int sqlcipher3BtreeHoldsAllMutexes(sqlcipher3 *db){
49417   int i;
49418   if( !sqlcipher3_mutex_held(db->mutex) ){
49419     return 0;
49420   }
49421   for(i=0; i<db->nDb; i++){
49422     Btree *p;
49423     p = db->aDb[i].pBt;
49424     if( p && p->sharable &&
49425          (p->wantToLock==0 || !sqlcipher3_mutex_held(p->pBt->mutex)) ){
49426       return 0;
49427     }
49428   }
49429   return 1;
49430 }
49431 #endif /* NDEBUG */
49432
49433 #ifndef NDEBUG
49434 /*
49435 ** Return true if the correct mutexes are held for accessing the
49436 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
49437 ** access are:
49438 **
49439 **   (1) The mutex on db
49440 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
49441 **
49442 ** If pSchema is not NULL, then iDb is computed from pSchema and
49443 ** db using sqlcipher3SchemaToIndex().
49444 */
49445 SQLCIPHER_PRIVATE int sqlcipher3SchemaMutexHeld(sqlcipher3 *db, int iDb, Schema *pSchema){
49446   Btree *p;
49447   assert( db!=0 );
49448   if( pSchema ) iDb = sqlcipher3SchemaToIndex(db, pSchema);
49449   assert( iDb>=0 && iDb<db->nDb );
49450   if( !sqlcipher3_mutex_held(db->mutex) ) return 0;
49451   if( iDb==1 ) return 1;
49452   p = db->aDb[iDb].pBt;
49453   assert( p!=0 );
49454   return p->sharable==0 || p->locked==1;
49455 }
49456 #endif /* NDEBUG */
49457
49458 #else /* SQLCIPHER_THREADSAFE>0 above.  SQLCIPHER_THREADSAFE==0 below */
49459 /*
49460 ** The following are special cases for mutex enter routines for use
49461 ** in single threaded applications that use shared cache.  Except for
49462 ** these two routines, all mutex operations are no-ops in that case and
49463 ** are null #defines in btree.h.
49464 **
49465 ** If shared cache is disabled, then all btree mutex routines, including
49466 ** the ones below, are no-ops and are null #defines in btree.h.
49467 */
49468
49469 SQLCIPHER_PRIVATE void sqlcipher3BtreeEnter(Btree *p){
49470   p->pBt->db = p->db;
49471 }
49472 SQLCIPHER_PRIVATE void sqlcipher3BtreeEnterAll(sqlcipher3 *db){
49473   int i;
49474   for(i=0; i<db->nDb; i++){
49475     Btree *p = db->aDb[i].pBt;
49476     if( p ){
49477       p->pBt->db = p->db;
49478     }
49479   }
49480 }
49481 #endif /* if SQLCIPHER_THREADSAFE */
49482 #endif /* ifndef SQLCIPHER_OMIT_SHARED_CACHE */
49483
49484 /************** End of btmutex.c *********************************************/
49485 /************** Begin file btree.c *******************************************/
49486 /*
49487 ** 2004 April 6
49488 **
49489 ** The author disclaims copyright to this source code.  In place of
49490 ** a legal notice, here is a blessing:
49491 **
49492 **    May you do good and not evil.
49493 **    May you find forgiveness for yourself and forgive others.
49494 **    May you share freely, never taking more than you give.
49495 **
49496 *************************************************************************
49497 ** This file implements a external (disk-based) database using BTrees.
49498 ** See the header comment on "btreeInt.h" for additional information.
49499 ** Including a description of file format and an overview of operation.
49500 */
49501
49502 /*
49503 ** The header string that appears at the beginning of every
49504 ** SQLite database.
49505 */
49506 static const char zMagicHeader[] = SQLCIPHER_FILE_HEADER;
49507
49508 /*
49509 ** Set this global variable to 1 to enable tracing using the TRACE
49510 ** macro.
49511 */
49512 #if 0
49513 int sqlcipher3BtreeTrace=1;  /* True to enable tracing */
49514 # define TRACE(X)  if(sqlcipher3BtreeTrace){printf X;fflush(stdout);}
49515 #else
49516 # define TRACE(X)
49517 #endif
49518
49519 /*
49520 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
49521 ** But if the value is zero, make it 65536.
49522 **
49523 ** This routine is used to extract the "offset to cell content area" value
49524 ** from the header of a btree page.  If the page size is 65536 and the page
49525 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
49526 ** This routine makes the necessary adjustment to 65536.
49527 */
49528 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
49529
49530 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
49531 /*
49532 ** A list of BtShared objects that are eligible for participation
49533 ** in shared cache.  This variable has file scope during normal builds,
49534 ** but the test harness needs to access it so we make it global for 
49535 ** test builds.
49536 **
49537 ** Access to this variable is protected by SQLCIPHER_MUTEX_STATIC_MASTER.
49538 */
49539 #ifdef SQLCIPHER_TEST
49540 SQLCIPHER_PRIVATE BtShared *SQLCIPHER_WSD sqlcipher3SharedCacheList = 0;
49541 #else
49542 static BtShared *SQLCIPHER_WSD sqlcipher3SharedCacheList = 0;
49543 #endif
49544 #endif /* SQLCIPHER_OMIT_SHARED_CACHE */
49545
49546 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
49547 /*
49548 ** Enable or disable the shared pager and schema features.
49549 **
49550 ** This routine has no effect on existing database connections.
49551 ** The shared cache setting effects only future calls to
49552 ** sqlcipher3_open(), sqlcipher3_open16(), or sqlcipher3_open_v2().
49553 */
49554 SQLCIPHER_API int sqlcipher3_enable_shared_cache(int enable){
49555   sqlcipher3GlobalConfig.sharedCacheEnabled = enable;
49556   return SQLCIPHER_OK;
49557 }
49558 #endif
49559
49560
49561
49562 #ifdef SQLCIPHER_OMIT_SHARED_CACHE
49563   /*
49564   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
49565   ** and clearAllSharedCacheTableLocks()
49566   ** manipulate entries in the BtShared.pLock linked list used to store
49567   ** shared-cache table level locks. If the library is compiled with the
49568   ** shared-cache feature disabled, then there is only ever one user
49569   ** of each BtShared structure and so this locking is not necessary. 
49570   ** So define the lock related functions as no-ops.
49571   */
49572   #define querySharedCacheTableLock(a,b,c) SQLCIPHER_OK
49573   #define setSharedCacheTableLock(a,b,c) SQLCIPHER_OK
49574   #define clearAllSharedCacheTableLocks(a)
49575   #define downgradeAllSharedCacheTableLocks(a)
49576   #define hasSharedCacheTableLock(a,b,c,d) 1
49577   #define hasReadConflicts(a, b) 0
49578 #endif
49579
49580 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
49581
49582 #ifdef SQLCIPHER_DEBUG
49583 /*
49584 **** This function is only used as part of an assert() statement. ***
49585 **
49586 ** Check to see if pBtree holds the required locks to read or write to the 
49587 ** table with root page iRoot.   Return 1 if it does and 0 if not.
49588 **
49589 ** For example, when writing to a table with root-page iRoot via 
49590 ** Btree connection pBtree:
49591 **
49592 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
49593 **
49594 ** When writing to an index that resides in a sharable database, the 
49595 ** caller should have first obtained a lock specifying the root page of
49596 ** the corresponding table. This makes things a bit more complicated,
49597 ** as this module treats each table as a separate structure. To determine
49598 ** the table corresponding to the index being written, this
49599 ** function has to search through the database schema.
49600 **
49601 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
49602 ** hold a write-lock on the schema table (root page 1). This is also
49603 ** acceptable.
49604 */
49605 static int hasSharedCacheTableLock(
49606   Btree *pBtree,         /* Handle that must hold lock */
49607   Pgno iRoot,            /* Root page of b-tree */
49608   int isIndex,           /* True if iRoot is the root of an index b-tree */
49609   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
49610 ){
49611   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
49612   Pgno iTab = 0;
49613   BtLock *pLock;
49614
49615   /* If this database is not shareable, or if the client is reading
49616   ** and has the read-uncommitted flag set, then no lock is required. 
49617   ** Return true immediately.
49618   */
49619   if( (pBtree->sharable==0)
49620    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLCIPHER_ReadUncommitted))
49621   ){
49622     return 1;
49623   }
49624
49625   /* If the client is reading  or writing an index and the schema is
49626   ** not loaded, then it is too difficult to actually check to see if
49627   ** the correct locks are held.  So do not bother - just return true.
49628   ** This case does not come up very often anyhow.
49629   */
49630   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
49631     return 1;
49632   }
49633
49634   /* Figure out the root-page that the lock should be held on. For table
49635   ** b-trees, this is just the root page of the b-tree being read or
49636   ** written. For index b-trees, it is the root page of the associated
49637   ** table.  */
49638   if( isIndex ){
49639     HashElem *p;
49640     for(p=sqlcipherHashFirst(&pSchema->idxHash); p; p=sqlcipherHashNext(p)){
49641       Index *pIdx = (Index *)sqlcipherHashData(p);
49642       if( pIdx->tnum==(int)iRoot ){
49643         iTab = pIdx->pTable->tnum;
49644       }
49645     }
49646   }else{
49647     iTab = iRoot;
49648   }
49649
49650   /* Search for the required lock. Either a write-lock on root-page iTab, a 
49651   ** write-lock on the schema table, or (if the client is reading) a
49652   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
49653   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
49654     if( pLock->pBtree==pBtree 
49655      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
49656      && pLock->eLock>=eLockType 
49657     ){
49658       return 1;
49659     }
49660   }
49661
49662   /* Failed to find the required lock. */
49663   return 0;
49664 }
49665 #endif /* SQLCIPHER_DEBUG */
49666
49667 #ifdef SQLCIPHER_DEBUG
49668 /*
49669 **** This function may be used as part of assert() statements only. ****
49670 **
49671 ** Return true if it would be illegal for pBtree to write into the
49672 ** table or index rooted at iRoot because other shared connections are
49673 ** simultaneously reading that same table or index.
49674 **
49675 ** It is illegal for pBtree to write if some other Btree object that
49676 ** shares the same BtShared object is currently reading or writing
49677 ** the iRoot table.  Except, if the other Btree object has the
49678 ** read-uncommitted flag set, then it is OK for the other object to
49679 ** have a read cursor.
49680 **
49681 ** For example, before writing to any part of the table or index
49682 ** rooted at page iRoot, one should call:
49683 **
49684 **    assert( !hasReadConflicts(pBtree, iRoot) );
49685 */
49686 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
49687   BtCursor *p;
49688   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
49689     if( p->pgnoRoot==iRoot 
49690      && p->pBtree!=pBtree
49691      && 0==(p->pBtree->db->flags & SQLCIPHER_ReadUncommitted)
49692     ){
49693       return 1;
49694     }
49695   }
49696   return 0;
49697 }
49698 #endif    /* #ifdef SQLCIPHER_DEBUG */
49699
49700 /*
49701 ** Query to see if Btree handle p may obtain a lock of type eLock 
49702 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
49703 ** SQLCIPHER_OK if the lock may be obtained (by calling
49704 ** setSharedCacheTableLock()), or SQLCIPHER_LOCKED if not.
49705 */
49706 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
49707   BtShared *pBt = p->pBt;
49708   BtLock *pIter;
49709
49710   assert( sqlcipher3BtreeHoldsMutex(p) );
49711   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49712   assert( p->db!=0 );
49713   assert( !(p->db->flags&SQLCIPHER_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
49714   
49715   /* If requesting a write-lock, then the Btree must have an open write
49716   ** transaction on this file. And, obviously, for this to be so there 
49717   ** must be an open write transaction on the file itself.
49718   */
49719   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
49720   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
49721   
49722   /* This routine is a no-op if the shared-cache is not enabled */
49723   if( !p->sharable ){
49724     return SQLCIPHER_OK;
49725   }
49726
49727   /* If some other connection is holding an exclusive lock, the
49728   ** requested lock may not be obtained.
49729   */
49730   if( pBt->pWriter!=p && pBt->isExclusive ){
49731     sqlcipher3ConnectionBlocked(p->db, pBt->pWriter->db);
49732     return SQLCIPHER_LOCKED_SHAREDCACHE;
49733   }
49734
49735   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49736     /* The condition (pIter->eLock!=eLock) in the following if(...) 
49737     ** statement is a simplification of:
49738     **
49739     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
49740     **
49741     ** since we know that if eLock==WRITE_LOCK, then no other connection
49742     ** may hold a WRITE_LOCK on any table in this file (since there can
49743     ** only be a single writer).
49744     */
49745     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
49746     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
49747     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
49748       sqlcipher3ConnectionBlocked(p->db, pIter->pBtree->db);
49749       if( eLock==WRITE_LOCK ){
49750         assert( p==pBt->pWriter );
49751         pBt->isPending = 1;
49752       }
49753       return SQLCIPHER_LOCKED_SHAREDCACHE;
49754     }
49755   }
49756   return SQLCIPHER_OK;
49757 }
49758 #endif /* !SQLCIPHER_OMIT_SHARED_CACHE */
49759
49760 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
49761 /*
49762 ** Add a lock on the table with root-page iTable to the shared-btree used
49763 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
49764 ** WRITE_LOCK.
49765 **
49766 ** This function assumes the following:
49767 **
49768 **   (a) The specified Btree object p is connected to a sharable
49769 **       database (one with the BtShared.sharable flag set), and
49770 **
49771 **   (b) No other Btree objects hold a lock that conflicts
49772 **       with the requested lock (i.e. querySharedCacheTableLock() has
49773 **       already been called and returned SQLCIPHER_OK).
49774 **
49775 ** SQLCIPHER_OK is returned if the lock is added successfully. SQLCIPHER_NOMEM 
49776 ** is returned if a malloc attempt fails.
49777 */
49778 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
49779   BtShared *pBt = p->pBt;
49780   BtLock *pLock = 0;
49781   BtLock *pIter;
49782
49783   assert( sqlcipher3BtreeHoldsMutex(p) );
49784   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49785   assert( p->db!=0 );
49786
49787   /* A connection with the read-uncommitted flag set will never try to
49788   ** obtain a read-lock using this function. The only read-lock obtained
49789   ** by a connection in read-uncommitted mode is on the sqlcipher_master 
49790   ** table, and that lock is obtained in BtreeBeginTrans().  */
49791   assert( 0==(p->db->flags&SQLCIPHER_ReadUncommitted) || eLock==WRITE_LOCK );
49792
49793   /* This function should only be called on a sharable b-tree after it 
49794   ** has been determined that no other b-tree holds a conflicting lock.  */
49795   assert( p->sharable );
49796   assert( SQLCIPHER_OK==querySharedCacheTableLock(p, iTable, eLock) );
49797
49798   /* First search the list for an existing lock on this table. */
49799   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49800     if( pIter->iTable==iTable && pIter->pBtree==p ){
49801       pLock = pIter;
49802       break;
49803     }
49804   }
49805
49806   /* If the above search did not find a BtLock struct associating Btree p
49807   ** with table iTable, allocate one and link it into the list.
49808   */
49809   if( !pLock ){
49810     pLock = (BtLock *)sqlcipher3MallocZero(sizeof(BtLock));
49811     if( !pLock ){
49812       return SQLCIPHER_NOMEM;
49813     }
49814     pLock->iTable = iTable;
49815     pLock->pBtree = p;
49816     pLock->pNext = pBt->pLock;
49817     pBt->pLock = pLock;
49818   }
49819
49820   /* Set the BtLock.eLock variable to the maximum of the current lock
49821   ** and the requested lock. This means if a write-lock was already held
49822   ** and a read-lock requested, we don't incorrectly downgrade the lock.
49823   */
49824   assert( WRITE_LOCK>READ_LOCK );
49825   if( eLock>pLock->eLock ){
49826     pLock->eLock = eLock;
49827   }
49828
49829   return SQLCIPHER_OK;
49830 }
49831 #endif /* !SQLCIPHER_OMIT_SHARED_CACHE */
49832
49833 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
49834 /*
49835 ** Release all the table locks (locks obtained via calls to
49836 ** the setSharedCacheTableLock() procedure) held by Btree object p.
49837 **
49838 ** This function assumes that Btree p has an open read or write 
49839 ** transaction. If it does not, then the BtShared.isPending variable
49840 ** may be incorrectly cleared.
49841 */
49842 static void clearAllSharedCacheTableLocks(Btree *p){
49843   BtShared *pBt = p->pBt;
49844   BtLock **ppIter = &pBt->pLock;
49845
49846   assert( sqlcipher3BtreeHoldsMutex(p) );
49847   assert( p->sharable || 0==*ppIter );
49848   assert( p->inTrans>0 );
49849
49850   while( *ppIter ){
49851     BtLock *pLock = *ppIter;
49852     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
49853     assert( pLock->pBtree->inTrans>=pLock->eLock );
49854     if( pLock->pBtree==p ){
49855       *ppIter = pLock->pNext;
49856       assert( pLock->iTable!=1 || pLock==&p->lock );
49857       if( pLock->iTable!=1 ){
49858         sqlcipher3_free(pLock);
49859       }
49860     }else{
49861       ppIter = &pLock->pNext;
49862     }
49863   }
49864
49865   assert( pBt->isPending==0 || pBt->pWriter );
49866   if( pBt->pWriter==p ){
49867     pBt->pWriter = 0;
49868     pBt->isExclusive = 0;
49869     pBt->isPending = 0;
49870   }else if( pBt->nTransaction==2 ){
49871     /* This function is called when Btree p is concluding its 
49872     ** transaction. If there currently exists a writer, and p is not
49873     ** that writer, then the number of locks held by connections other
49874     ** than the writer must be about to drop to zero. In this case
49875     ** set the isPending flag to 0.
49876     **
49877     ** If there is not currently a writer, then BtShared.isPending must
49878     ** be zero already. So this next line is harmless in that case.
49879     */
49880     pBt->isPending = 0;
49881   }
49882 }
49883
49884 /*
49885 ** This function changes all write-locks held by Btree p into read-locks.
49886 */
49887 static void downgradeAllSharedCacheTableLocks(Btree *p){
49888   BtShared *pBt = p->pBt;
49889   if( pBt->pWriter==p ){
49890     BtLock *pLock;
49891     pBt->pWriter = 0;
49892     pBt->isExclusive = 0;
49893     pBt->isPending = 0;
49894     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
49895       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
49896       pLock->eLock = READ_LOCK;
49897     }
49898   }
49899 }
49900
49901 #endif /* SQLCIPHER_OMIT_SHARED_CACHE */
49902
49903 static void releasePage(MemPage *pPage);  /* Forward reference */
49904
49905 /*
49906 ***** This routine is used inside of assert() only ****
49907 **
49908 ** Verify that the cursor holds the mutex on its BtShared
49909 */
49910 #ifdef SQLCIPHER_DEBUG
49911 static int cursorHoldsMutex(BtCursor *p){
49912   return sqlcipher3_mutex_held(p->pBt->mutex);
49913 }
49914 #endif
49915
49916
49917 #ifndef SQLCIPHER_OMIT_INCRBLOB
49918 /*
49919 ** Invalidate the overflow page-list cache for cursor pCur, if any.
49920 */
49921 static void invalidateOverflowCache(BtCursor *pCur){
49922   assert( cursorHoldsMutex(pCur) );
49923   sqlcipher3_free(pCur->aOverflow);
49924   pCur->aOverflow = 0;
49925 }
49926
49927 /*
49928 ** Invalidate the overflow page-list cache for all cursors opened
49929 ** on the shared btree structure pBt.
49930 */
49931 static void invalidateAllOverflowCache(BtShared *pBt){
49932   BtCursor *p;
49933   assert( sqlcipher3_mutex_held(pBt->mutex) );
49934   for(p=pBt->pCursor; p; p=p->pNext){
49935     invalidateOverflowCache(p);
49936   }
49937 }
49938
49939 /*
49940 ** This function is called before modifying the contents of a table
49941 ** to invalidate any incrblob cursors that are open on the
49942 ** row or one of the rows being modified.
49943 **
49944 ** If argument isClearTable is true, then the entire contents of the
49945 ** table is about to be deleted. In this case invalidate all incrblob
49946 ** cursors open on any row within the table with root-page pgnoRoot.
49947 **
49948 ** Otherwise, if argument isClearTable is false, then the row with
49949 ** rowid iRow is being replaced or deleted. In this case invalidate
49950 ** only those incrblob cursors open on that specific row.
49951 */
49952 static void invalidateIncrblobCursors(
49953   Btree *pBtree,          /* The database file to check */
49954   i64 iRow,               /* The rowid that might be changing */
49955   int isClearTable        /* True if all rows are being deleted */
49956 ){
49957   BtCursor *p;
49958   BtShared *pBt = pBtree->pBt;
49959   assert( sqlcipher3BtreeHoldsMutex(pBtree) );
49960   for(p=pBt->pCursor; p; p=p->pNext){
49961     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
49962       p->eState = CURSOR_INVALID;
49963     }
49964   }
49965 }
49966
49967 #else
49968   /* Stub functions when INCRBLOB is omitted */
49969   #define invalidateOverflowCache(x)
49970   #define invalidateAllOverflowCache(x)
49971   #define invalidateIncrblobCursors(x,y,z)
49972 #endif /* SQLCIPHER_OMIT_INCRBLOB */
49973
49974 /*
49975 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
49976 ** when a page that previously contained data becomes a free-list leaf 
49977 ** page.
49978 **
49979 ** The BtShared.pHasContent bitvec exists to work around an obscure
49980 ** bug caused by the interaction of two useful IO optimizations surrounding
49981 ** free-list leaf pages:
49982 **
49983 **   1) When all data is deleted from a page and the page becomes
49984 **      a free-list leaf page, the page is not written to the database
49985 **      (as free-list leaf pages contain no meaningful data). Sometimes
49986 **      such a page is not even journalled (as it will not be modified,
49987 **      why bother journalling it?).
49988 **
49989 **   2) When a free-list leaf page is reused, its content is not read
49990 **      from the database or written to the journal file (why should it
49991 **      be, if it is not at all meaningful?).
49992 **
49993 ** By themselves, these optimizations work fine and provide a handy
49994 ** performance boost to bulk delete or insert operations. However, if
49995 ** a page is moved to the free-list and then reused within the same
49996 ** transaction, a problem comes up. If the page is not journalled when
49997 ** it is moved to the free-list and it is also not journalled when it
49998 ** is extracted from the free-list and reused, then the original data
49999 ** may be lost. In the event of a rollback, it may not be possible
50000 ** to restore the database to its original configuration.
50001 **
50002 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
50003 ** moved to become a free-list leaf page, the corresponding bit is
50004 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
50005 ** optimization 2 above is omitted if the corresponding bit is already
50006 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
50007 ** at the end of every transaction.
50008 */
50009 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
50010   int rc = SQLCIPHER_OK;
50011   if( !pBt->pHasContent ){
50012     assert( pgno<=pBt->nPage );
50013     pBt->pHasContent = sqlcipher3BitvecCreate(pBt->nPage);
50014     if( !pBt->pHasContent ){
50015       rc = SQLCIPHER_NOMEM;
50016     }
50017   }
50018   if( rc==SQLCIPHER_OK && pgno<=sqlcipher3BitvecSize(pBt->pHasContent) ){
50019     rc = sqlcipher3BitvecSet(pBt->pHasContent, pgno);
50020   }
50021   return rc;
50022 }
50023
50024 /*
50025 ** Query the BtShared.pHasContent vector.
50026 **
50027 ** This function is called when a free-list leaf page is removed from the
50028 ** free-list for reuse. It returns false if it is safe to retrieve the
50029 ** page from the pager layer with the 'no-content' flag set. True otherwise.
50030 */
50031 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
50032   Bitvec *p = pBt->pHasContent;
50033   return (p && (pgno>sqlcipher3BitvecSize(p) || sqlcipher3BitvecTest(p, pgno)));
50034 }
50035
50036 /*
50037 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
50038 ** invoked at the conclusion of each write-transaction.
50039 */
50040 static void btreeClearHasContent(BtShared *pBt){
50041   sqlcipher3BitvecDestroy(pBt->pHasContent);
50042   pBt->pHasContent = 0;
50043 }
50044
50045 /*
50046 ** Save the current cursor position in the variables BtCursor.nKey 
50047 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
50048 **
50049 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
50050 ** prior to calling this routine.  
50051 */
50052 static int saveCursorPosition(BtCursor *pCur){
50053   int rc;
50054
50055   assert( CURSOR_VALID==pCur->eState );
50056   assert( 0==pCur->pKey );
50057   assert( cursorHoldsMutex(pCur) );
50058
50059   rc = sqlcipher3BtreeKeySize(pCur, &pCur->nKey);
50060   assert( rc==SQLCIPHER_OK );  /* KeySize() cannot fail */
50061
50062   /* If this is an intKey table, then the above call to BtreeKeySize()
50063   ** stores the integer key in pCur->nKey. In this case this value is
50064   ** all that is required. Otherwise, if pCur is not open on an intKey
50065   ** table, then malloc space for and store the pCur->nKey bytes of key 
50066   ** data.
50067   */
50068   if( 0==pCur->apPage[0]->intKey ){
50069     void *pKey = sqlcipher3Malloc( (int)pCur->nKey );
50070     if( pKey ){
50071       rc = sqlcipher3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
50072       if( rc==SQLCIPHER_OK ){
50073         pCur->pKey = pKey;
50074       }else{
50075         sqlcipher3_free(pKey);
50076       }
50077     }else{
50078       rc = SQLCIPHER_NOMEM;
50079     }
50080   }
50081   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
50082
50083   if( rc==SQLCIPHER_OK ){
50084     int i;
50085     for(i=0; i<=pCur->iPage; i++){
50086       releasePage(pCur->apPage[i]);
50087       pCur->apPage[i] = 0;
50088     }
50089     pCur->iPage = -1;
50090     pCur->eState = CURSOR_REQUIRESEEK;
50091   }
50092
50093   invalidateOverflowCache(pCur);
50094   return rc;
50095 }
50096
50097 /*
50098 ** Save the positions of all cursors (except pExcept) that are open on
50099 ** the table  with root-page iRoot. Usually, this is called just before cursor
50100 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
50101 */
50102 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
50103   BtCursor *p;
50104   assert( sqlcipher3_mutex_held(pBt->mutex) );
50105   assert( pExcept==0 || pExcept->pBt==pBt );
50106   for(p=pBt->pCursor; p; p=p->pNext){
50107     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
50108         p->eState==CURSOR_VALID ){
50109       int rc = saveCursorPosition(p);
50110       if( SQLCIPHER_OK!=rc ){
50111         return rc;
50112       }
50113     }
50114   }
50115   return SQLCIPHER_OK;
50116 }
50117
50118 /*
50119 ** Clear the current cursor position.
50120 */
50121 SQLCIPHER_PRIVATE void sqlcipher3BtreeClearCursor(BtCursor *pCur){
50122   assert( cursorHoldsMutex(pCur) );
50123   sqlcipher3_free(pCur->pKey);
50124   pCur->pKey = 0;
50125   pCur->eState = CURSOR_INVALID;
50126 }
50127
50128 /*
50129 ** In this version of BtreeMoveto, pKey is a packed index record
50130 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
50131 ** record and then call BtreeMovetoUnpacked() to do the work.
50132 */
50133 static int btreeMoveto(
50134   BtCursor *pCur,     /* Cursor open on the btree to be searched */
50135   const void *pKey,   /* Packed key if the btree is an index */
50136   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
50137   int bias,           /* Bias search to the high end */
50138   int *pRes           /* Write search results here */
50139 ){
50140   int rc;                    /* Status code */
50141   UnpackedRecord *pIdxKey;   /* Unpacked index key */
50142   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
50143   char *pFree = 0;
50144
50145   if( pKey ){
50146     assert( nKey==(i64)(int)nKey );
50147     pIdxKey = sqlcipher3VdbeAllocUnpackedRecord(
50148         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
50149     );
50150     if( pIdxKey==0 ) return SQLCIPHER_NOMEM;
50151     sqlcipher3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
50152   }else{
50153     pIdxKey = 0;
50154   }
50155   rc = sqlcipher3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
50156   if( pFree ){
50157     sqlcipher3DbFree(pCur->pKeyInfo->db, pFree);
50158   }
50159   return rc;
50160 }
50161
50162 /*
50163 ** Restore the cursor to the position it was in (or as close to as possible)
50164 ** when saveCursorPosition() was called. Note that this call deletes the 
50165 ** saved position info stored by saveCursorPosition(), so there can be
50166 ** at most one effective restoreCursorPosition() call after each 
50167 ** saveCursorPosition().
50168 */
50169 static int btreeRestoreCursorPosition(BtCursor *pCur){
50170   int rc;
50171   assert( cursorHoldsMutex(pCur) );
50172   assert( pCur->eState>=CURSOR_REQUIRESEEK );
50173   if( pCur->eState==CURSOR_FAULT ){
50174     return pCur->skipNext;
50175   }
50176   pCur->eState = CURSOR_INVALID;
50177   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
50178   if( rc==SQLCIPHER_OK ){
50179     sqlcipher3_free(pCur->pKey);
50180     pCur->pKey = 0;
50181     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
50182   }
50183   return rc;
50184 }
50185
50186 #define restoreCursorPosition(p) \
50187   (p->eState>=CURSOR_REQUIRESEEK ? \
50188          btreeRestoreCursorPosition(p) : \
50189          SQLCIPHER_OK)
50190
50191 /*
50192 ** Determine whether or not a cursor has moved from the position it
50193 ** was last placed at.  Cursors can move when the row they are pointing
50194 ** at is deleted out from under them.
50195 **
50196 ** This routine returns an error code if something goes wrong.  The
50197 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
50198 */
50199 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
50200   int rc;
50201
50202   rc = restoreCursorPosition(pCur);
50203   if( rc ){
50204     *pHasMoved = 1;
50205     return rc;
50206   }
50207   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
50208     *pHasMoved = 1;
50209   }else{
50210     *pHasMoved = 0;
50211   }
50212   return SQLCIPHER_OK;
50213 }
50214
50215 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
50216 /*
50217 ** Given a page number of a regular database page, return the page
50218 ** number for the pointer-map page that contains the entry for the
50219 ** input page number.
50220 **
50221 ** Return 0 (not a valid page) for pgno==1 since there is
50222 ** no pointer map associated with page 1.  The integrity_check logic
50223 ** requires that ptrmapPageno(*,1)!=1.
50224 */
50225 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
50226   int nPagesPerMapPage;
50227   Pgno iPtrMap, ret;
50228   assert( sqlcipher3_mutex_held(pBt->mutex) );
50229   if( pgno<2 ) return 0;
50230   nPagesPerMapPage = (pBt->usableSize/5)+1;
50231   iPtrMap = (pgno-2)/nPagesPerMapPage;
50232   ret = (iPtrMap*nPagesPerMapPage) + 2; 
50233   if( ret==PENDING_BYTE_PAGE(pBt) ){
50234     ret++;
50235   }
50236   return ret;
50237 }
50238
50239 /*
50240 ** Write an entry into the pointer map.
50241 **
50242 ** This routine updates the pointer map entry for page number 'key'
50243 ** so that it maps to type 'eType' and parent page number 'pgno'.
50244 **
50245 ** If *pRC is initially non-zero (non-SQLCIPHER_OK) then this routine is
50246 ** a no-op.  If an error occurs, the appropriate error code is written
50247 ** into *pRC.
50248 */
50249 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
50250   DbPage *pDbPage;  /* The pointer map page */
50251   u8 *pPtrmap;      /* The pointer map data */
50252   Pgno iPtrmap;     /* The pointer map page number */
50253   int offset;       /* Offset in pointer map page */
50254   int rc;           /* Return code from subfunctions */
50255
50256   if( *pRC ) return;
50257
50258   assert( sqlcipher3_mutex_held(pBt->mutex) );
50259   /* The master-journal page number must never be used as a pointer map page */
50260   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
50261
50262   assert( pBt->autoVacuum );
50263   if( key==0 ){
50264     *pRC = SQLCIPHER_CORRUPT_BKPT;
50265     return;
50266   }
50267   iPtrmap = PTRMAP_PAGENO(pBt, key);
50268   rc = sqlcipher3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50269   if( rc!=SQLCIPHER_OK ){
50270     *pRC = rc;
50271     return;
50272   }
50273   offset = PTRMAP_PTROFFSET(iPtrmap, key);
50274   if( offset<0 ){
50275     *pRC = SQLCIPHER_CORRUPT_BKPT;
50276     goto ptrmap_exit;
50277   }
50278   assert( offset <= (int)pBt->usableSize-5 );
50279   pPtrmap = (u8 *)sqlcipher3PagerGetData(pDbPage);
50280
50281   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
50282     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
50283     *pRC= rc = sqlcipher3PagerWrite(pDbPage);
50284     if( rc==SQLCIPHER_OK ){
50285       pPtrmap[offset] = eType;
50286       put4byte(&pPtrmap[offset+1], parent);
50287     }
50288   }
50289
50290 ptrmap_exit:
50291   sqlcipher3PagerUnref(pDbPage);
50292 }
50293
50294 /*
50295 ** Read an entry from the pointer map.
50296 **
50297 ** This routine retrieves the pointer map entry for page 'key', writing
50298 ** the type and parent page number to *pEType and *pPgno respectively.
50299 ** An error code is returned if something goes wrong, otherwise SQLCIPHER_OK.
50300 */
50301 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
50302   DbPage *pDbPage;   /* The pointer map page */
50303   int iPtrmap;       /* Pointer map page index */
50304   u8 *pPtrmap;       /* Pointer map page data */
50305   int offset;        /* Offset of entry in pointer map */
50306   int rc;
50307
50308   assert( sqlcipher3_mutex_held(pBt->mutex) );
50309
50310   iPtrmap = PTRMAP_PAGENO(pBt, key);
50311   rc = sqlcipher3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50312   if( rc!=0 ){
50313     return rc;
50314   }
50315   pPtrmap = (u8 *)sqlcipher3PagerGetData(pDbPage);
50316
50317   offset = PTRMAP_PTROFFSET(iPtrmap, key);
50318   if( offset<0 ){
50319     sqlcipher3PagerUnref(pDbPage);
50320     return SQLCIPHER_CORRUPT_BKPT;
50321   }
50322   assert( offset <= (int)pBt->usableSize-5 );
50323   assert( pEType!=0 );
50324   *pEType = pPtrmap[offset];
50325   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
50326
50327   sqlcipher3PagerUnref(pDbPage);
50328   if( *pEType<1 || *pEType>5 ) return SQLCIPHER_CORRUPT_BKPT;
50329   return SQLCIPHER_OK;
50330 }
50331
50332 #else /* if defined SQLCIPHER_OMIT_AUTOVACUUM */
50333   #define ptrmapPut(w,x,y,z,rc)
50334   #define ptrmapGet(w,x,y,z) SQLCIPHER_OK
50335   #define ptrmapPutOvflPtr(x, y, rc)
50336 #endif
50337
50338 /*
50339 ** Given a btree page and a cell index (0 means the first cell on
50340 ** the page, 1 means the second cell, and so forth) return a pointer
50341 ** to the cell content.
50342 **
50343 ** This routine works only for pages that do not contain overflow cells.
50344 */
50345 #define findCell(P,I) \
50346   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
50347 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
50348
50349
50350 /*
50351 ** This a more complex version of findCell() that works for
50352 ** pages that do contain overflow cells.
50353 */
50354 static u8 *findOverflowCell(MemPage *pPage, int iCell){
50355   int i;
50356   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50357   for(i=pPage->nOverflow-1; i>=0; i--){
50358     int k;
50359     struct _OvflCell *pOvfl;
50360     pOvfl = &pPage->aOvfl[i];
50361     k = pOvfl->idx;
50362     if( k<=iCell ){
50363       if( k==iCell ){
50364         return pOvfl->pCell;
50365       }
50366       iCell--;
50367     }
50368   }
50369   return findCell(pPage, iCell);
50370 }
50371
50372 /*
50373 ** Parse a cell content block and fill in the CellInfo structure.  There
50374 ** are two versions of this function.  btreeParseCell() takes a 
50375 ** cell index as the second argument and btreeParseCellPtr() 
50376 ** takes a pointer to the body of the cell as its second argument.
50377 **
50378 ** Within this file, the parseCell() macro can be called instead of
50379 ** btreeParseCellPtr(). Using some compilers, this will be faster.
50380 */
50381 static void btreeParseCellPtr(
50382   MemPage *pPage,         /* Page containing the cell */
50383   u8 *pCell,              /* Pointer to the cell text. */
50384   CellInfo *pInfo         /* Fill in this structure */
50385 ){
50386   u16 n;                  /* Number bytes in cell content header */
50387   u32 nPayload;           /* Number of bytes of cell payload */
50388
50389   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50390
50391   pInfo->pCell = pCell;
50392   assert( pPage->leaf==0 || pPage->leaf==1 );
50393   n = pPage->childPtrSize;
50394   assert( n==4-4*pPage->leaf );
50395   if( pPage->intKey ){
50396     if( pPage->hasData ){
50397       n += getVarint32(&pCell[n], nPayload);
50398     }else{
50399       nPayload = 0;
50400     }
50401     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
50402     pInfo->nData = nPayload;
50403   }else{
50404     pInfo->nData = 0;
50405     n += getVarint32(&pCell[n], nPayload);
50406     pInfo->nKey = nPayload;
50407   }
50408   pInfo->nPayload = nPayload;
50409   pInfo->nHeader = n;
50410   testcase( nPayload==pPage->maxLocal );
50411   testcase( nPayload==pPage->maxLocal+1 );
50412   if( likely(nPayload<=pPage->maxLocal) ){
50413     /* This is the (easy) common case where the entire payload fits
50414     ** on the local page.  No overflow is required.
50415     */
50416     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
50417     pInfo->nLocal = (u16)nPayload;
50418     pInfo->iOverflow = 0;
50419   }else{
50420     /* If the payload will not fit completely on the local page, we have
50421     ** to decide how much to store locally and how much to spill onto
50422     ** overflow pages.  The strategy is to minimize the amount of unused
50423     ** space on overflow pages while keeping the amount of local storage
50424     ** in between minLocal and maxLocal.
50425     **
50426     ** Warning:  changing the way overflow payload is distributed in any
50427     ** way will result in an incompatible file format.
50428     */
50429     int minLocal;  /* Minimum amount of payload held locally */
50430     int maxLocal;  /* Maximum amount of payload held locally */
50431     int surplus;   /* Overflow payload available for local storage */
50432
50433     minLocal = pPage->minLocal;
50434     maxLocal = pPage->maxLocal;
50435     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
50436     testcase( surplus==maxLocal );
50437     testcase( surplus==maxLocal+1 );
50438     if( surplus <= maxLocal ){
50439       pInfo->nLocal = (u16)surplus;
50440     }else{
50441       pInfo->nLocal = (u16)minLocal;
50442     }
50443     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
50444     pInfo->nSize = pInfo->iOverflow + 4;
50445   }
50446 }
50447 #define parseCell(pPage, iCell, pInfo) \
50448   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
50449 static void btreeParseCell(
50450   MemPage *pPage,         /* Page containing the cell */
50451   int iCell,              /* The cell index.  First cell is 0 */
50452   CellInfo *pInfo         /* Fill in this structure */
50453 ){
50454   parseCell(pPage, iCell, pInfo);
50455 }
50456
50457 /*
50458 ** Compute the total number of bytes that a Cell needs in the cell
50459 ** data area of the btree-page.  The return number includes the cell
50460 ** data header and the local payload, but not any overflow page or
50461 ** the space used by the cell pointer.
50462 */
50463 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
50464   u8 *pIter = &pCell[pPage->childPtrSize];
50465   u32 nSize;
50466
50467 #ifdef SQLCIPHER_DEBUG
50468   /* The value returned by this function should always be the same as
50469   ** the (CellInfo.nSize) value found by doing a full parse of the
50470   ** cell. If SQLCIPHER_DEBUG is defined, an assert() at the bottom of
50471   ** this function verifies that this invariant is not violated. */
50472   CellInfo debuginfo;
50473   btreeParseCellPtr(pPage, pCell, &debuginfo);
50474 #endif
50475
50476   if( pPage->intKey ){
50477     u8 *pEnd;
50478     if( pPage->hasData ){
50479       pIter += getVarint32(pIter, nSize);
50480     }else{
50481       nSize = 0;
50482     }
50483
50484     /* pIter now points at the 64-bit integer key value, a variable length 
50485     ** integer. The following block moves pIter to point at the first byte
50486     ** past the end of the key value. */
50487     pEnd = &pIter[9];
50488     while( (*pIter++)&0x80 && pIter<pEnd );
50489   }else{
50490     pIter += getVarint32(pIter, nSize);
50491   }
50492
50493   testcase( nSize==pPage->maxLocal );
50494   testcase( nSize==pPage->maxLocal+1 );
50495   if( nSize>pPage->maxLocal ){
50496     int minLocal = pPage->minLocal;
50497     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
50498     testcase( nSize==pPage->maxLocal );
50499     testcase( nSize==pPage->maxLocal+1 );
50500     if( nSize>pPage->maxLocal ){
50501       nSize = minLocal;
50502     }
50503     nSize += 4;
50504   }
50505   nSize += (u32)(pIter - pCell);
50506
50507   /* The minimum size of any cell is 4 bytes. */
50508   if( nSize<4 ){
50509     nSize = 4;
50510   }
50511
50512   assert( nSize==debuginfo.nSize );
50513   return (u16)nSize;
50514 }
50515
50516 #ifdef SQLCIPHER_DEBUG
50517 /* This variation on cellSizePtr() is used inside of assert() statements
50518 ** only. */
50519 static u16 cellSize(MemPage *pPage, int iCell){
50520   return cellSizePtr(pPage, findCell(pPage, iCell));
50521 }
50522 #endif
50523
50524 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
50525 /*
50526 ** If the cell pCell, part of page pPage contains a pointer
50527 ** to an overflow page, insert an entry into the pointer-map
50528 ** for the overflow page.
50529 */
50530 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
50531   CellInfo info;
50532   if( *pRC ) return;
50533   assert( pCell!=0 );
50534   btreeParseCellPtr(pPage, pCell, &info);
50535   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
50536   if( info.iOverflow ){
50537     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
50538     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
50539   }
50540 }
50541 #endif
50542
50543
50544 /*
50545 ** Defragment the page given.  All Cells are moved to the
50546 ** end of the page and all free space is collected into one
50547 ** big FreeBlk that occurs in between the header and cell
50548 ** pointer array and the cell content area.
50549 */
50550 static int defragmentPage(MemPage *pPage){
50551   int i;                     /* Loop counter */
50552   int pc;                    /* Address of a i-th cell */
50553   int hdr;                   /* Offset to the page header */
50554   int size;                  /* Size of a cell */
50555   int usableSize;            /* Number of usable bytes on a page */
50556   int cellOffset;            /* Offset to the cell pointer array */
50557   int cbrk;                  /* Offset to the cell content area */
50558   int nCell;                 /* Number of cells on the page */
50559   unsigned char *data;       /* The page data */
50560   unsigned char *temp;       /* Temp area for cell content */
50561   int iCellFirst;            /* First allowable cell index */
50562   int iCellLast;             /* Last possible cell index */
50563
50564
50565   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
50566   assert( pPage->pBt!=0 );
50567   assert( pPage->pBt->usableSize <= SQLCIPHER_MAX_PAGE_SIZE );
50568   assert( pPage->nOverflow==0 );
50569   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50570   temp = sqlcipher3PagerTempSpace(pPage->pBt->pPager);
50571   data = pPage->aData;
50572   hdr = pPage->hdrOffset;
50573   cellOffset = pPage->cellOffset;
50574   nCell = pPage->nCell;
50575   assert( nCell==get2byte(&data[hdr+3]) );
50576   usableSize = pPage->pBt->usableSize;
50577   cbrk = get2byte(&data[hdr+5]);
50578   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
50579   cbrk = usableSize;
50580   iCellFirst = cellOffset + 2*nCell;
50581   iCellLast = usableSize - 4;
50582   for(i=0; i<nCell; i++){
50583     u8 *pAddr;     /* The i-th cell pointer */
50584     pAddr = &data[cellOffset + i*2];
50585     pc = get2byte(pAddr);
50586     testcase( pc==iCellFirst );
50587     testcase( pc==iCellLast );
50588 #if !defined(SQLCIPHER_ENABLE_OVERSIZE_CELL_CHECK)
50589     /* These conditions have already been verified in btreeInitPage()
50590     ** if SQLCIPHER_ENABLE_OVERSIZE_CELL_CHECK is defined 
50591     */
50592     if( pc<iCellFirst || pc>iCellLast ){
50593       return SQLCIPHER_CORRUPT_BKPT;
50594     }
50595 #endif
50596     assert( pc>=iCellFirst && pc<=iCellLast );
50597     size = cellSizePtr(pPage, &temp[pc]);
50598     cbrk -= size;
50599 #if defined(SQLCIPHER_ENABLE_OVERSIZE_CELL_CHECK)
50600     if( cbrk<iCellFirst ){
50601       return SQLCIPHER_CORRUPT_BKPT;
50602     }
50603 #else
50604     if( cbrk<iCellFirst || pc+size>usableSize ){
50605       return SQLCIPHER_CORRUPT_BKPT;
50606     }
50607 #endif
50608     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
50609     testcase( cbrk+size==usableSize );
50610     testcase( pc+size==usableSize );
50611     memcpy(&data[cbrk], &temp[pc], size);
50612     put2byte(pAddr, cbrk);
50613   }
50614   assert( cbrk>=iCellFirst );
50615   put2byte(&data[hdr+5], cbrk);
50616   data[hdr+1] = 0;
50617   data[hdr+2] = 0;
50618   data[hdr+7] = 0;
50619   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
50620   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
50621   if( cbrk-iCellFirst!=pPage->nFree ){
50622     return SQLCIPHER_CORRUPT_BKPT;
50623   }
50624   return SQLCIPHER_OK;
50625 }
50626
50627 /*
50628 ** Allocate nByte bytes of space from within the B-Tree page passed
50629 ** as the first argument. Write into *pIdx the index into pPage->aData[]
50630 ** of the first byte of allocated space. Return either SQLCIPHER_OK or
50631 ** an error code (usually SQLCIPHER_CORRUPT).
50632 **
50633 ** The caller guarantees that there is sufficient space to make the
50634 ** allocation.  This routine might need to defragment in order to bring
50635 ** all the space together, however.  This routine will avoid using
50636 ** the first two bytes past the cell pointer area since presumably this
50637 ** allocation is being made in order to insert a new cell, so we will
50638 ** also end up needing a new cell pointer.
50639 */
50640 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
50641   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
50642   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
50643   int nFrag;                           /* Number of fragmented bytes on pPage */
50644   int top;                             /* First byte of cell content area */
50645   int gap;        /* First byte of gap between cell pointers and cell content */
50646   int rc;         /* Integer return code */
50647   int usableSize; /* Usable size of the page */
50648   
50649   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
50650   assert( pPage->pBt );
50651   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50652   assert( nByte>=0 );  /* Minimum cell size is 4 */
50653   assert( pPage->nFree>=nByte );
50654   assert( pPage->nOverflow==0 );
50655   usableSize = pPage->pBt->usableSize;
50656   assert( nByte < usableSize-8 );
50657
50658   nFrag = data[hdr+7];
50659   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
50660   gap = pPage->cellOffset + 2*pPage->nCell;
50661   top = get2byteNotZero(&data[hdr+5]);
50662   if( gap>top ) return SQLCIPHER_CORRUPT_BKPT;
50663   testcase( gap+2==top );
50664   testcase( gap+1==top );
50665   testcase( gap==top );
50666
50667   if( nFrag>=60 ){
50668     /* Always defragment highly fragmented pages */
50669     rc = defragmentPage(pPage);
50670     if( rc ) return rc;
50671     top = get2byteNotZero(&data[hdr+5]);
50672   }else if( gap+2<=top ){
50673     /* Search the freelist looking for a free slot big enough to satisfy 
50674     ** the request. The allocation is made from the first free slot in 
50675     ** the list that is large enough to accomadate it.
50676     */
50677     int pc, addr;
50678     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
50679       int size;            /* Size of the free slot */
50680       if( pc>usableSize-4 || pc<addr+4 ){
50681         return SQLCIPHER_CORRUPT_BKPT;
50682       }
50683       size = get2byte(&data[pc+2]);
50684       if( size>=nByte ){
50685         int x = size - nByte;
50686         testcase( x==4 );
50687         testcase( x==3 );
50688         if( x<4 ){
50689           /* Remove the slot from the free-list. Update the number of
50690           ** fragmented bytes within the page. */
50691           memcpy(&data[addr], &data[pc], 2);
50692           data[hdr+7] = (u8)(nFrag + x);
50693         }else if( size+pc > usableSize ){
50694           return SQLCIPHER_CORRUPT_BKPT;
50695         }else{
50696           /* The slot remains on the free-list. Reduce its size to account
50697           ** for the portion used by the new allocation. */
50698           put2byte(&data[pc+2], x);
50699         }
50700         *pIdx = pc + x;
50701         return SQLCIPHER_OK;
50702       }
50703     }
50704   }
50705
50706   /* Check to make sure there is enough space in the gap to satisfy
50707   ** the allocation.  If not, defragment.
50708   */
50709   testcase( gap+2+nByte==top );
50710   if( gap+2+nByte>top ){
50711     rc = defragmentPage(pPage);
50712     if( rc ) return rc;
50713     top = get2byteNotZero(&data[hdr+5]);
50714     assert( gap+nByte<=top );
50715   }
50716
50717
50718   /* Allocate memory from the gap in between the cell pointer array
50719   ** and the cell content area.  The btreeInitPage() call has already
50720   ** validated the freelist.  Given that the freelist is valid, there
50721   ** is no way that the allocation can extend off the end of the page.
50722   ** The assert() below verifies the previous sentence.
50723   */
50724   top -= nByte;
50725   put2byte(&data[hdr+5], top);
50726   assert( top+nByte <= (int)pPage->pBt->usableSize );
50727   *pIdx = top;
50728   return SQLCIPHER_OK;
50729 }
50730
50731 /*
50732 ** Return a section of the pPage->aData to the freelist.
50733 ** The first byte of the new free block is pPage->aDisk[start]
50734 ** and the size of the block is "size" bytes.
50735 **
50736 ** Most of the effort here is involved in coalesing adjacent
50737 ** free blocks into a single big free block.
50738 */
50739 static int freeSpace(MemPage *pPage, int start, int size){
50740   int addr, pbegin, hdr;
50741   int iLast;                        /* Largest possible freeblock offset */
50742   unsigned char *data = pPage->aData;
50743
50744   assert( pPage->pBt!=0 );
50745   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
50746   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
50747   assert( (start + size) <= (int)pPage->pBt->usableSize );
50748   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50749   assert( size>=0 );   /* Minimum cell size is 4 */
50750
50751   if( pPage->pBt->secureDelete ){
50752     /* Overwrite deleted information with zeros when the secure_delete
50753     ** option is enabled */
50754     memset(&data[start], 0, size);
50755   }
50756
50757   /* Add the space back into the linked list of freeblocks.  Note that
50758   ** even though the freeblock list was checked by btreeInitPage(),
50759   ** btreeInitPage() did not detect overlapping cells or
50760   ** freeblocks that overlapped cells.   Nor does it detect when the
50761   ** cell content area exceeds the value in the page header.  If these
50762   ** situations arise, then subsequent insert operations might corrupt
50763   ** the freelist.  So we do need to check for corruption while scanning
50764   ** the freelist.
50765   */
50766   hdr = pPage->hdrOffset;
50767   addr = hdr + 1;
50768   iLast = pPage->pBt->usableSize - 4;
50769   assert( start<=iLast );
50770   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
50771     if( pbegin<addr+4 ){
50772       return SQLCIPHER_CORRUPT_BKPT;
50773     }
50774     addr = pbegin;
50775   }
50776   if( pbegin>iLast ){
50777     return SQLCIPHER_CORRUPT_BKPT;
50778   }
50779   assert( pbegin>addr || pbegin==0 );
50780   put2byte(&data[addr], start);
50781   put2byte(&data[start], pbegin);
50782   put2byte(&data[start+2], size);
50783   pPage->nFree = pPage->nFree + (u16)size;
50784
50785   /* Coalesce adjacent free blocks */
50786   addr = hdr + 1;
50787   while( (pbegin = get2byte(&data[addr]))>0 ){
50788     int pnext, psize, x;
50789     assert( pbegin>addr );
50790     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
50791     pnext = get2byte(&data[pbegin]);
50792     psize = get2byte(&data[pbegin+2]);
50793     if( pbegin + psize + 3 >= pnext && pnext>0 ){
50794       int frag = pnext - (pbegin+psize);
50795       if( (frag<0) || (frag>(int)data[hdr+7]) ){
50796         return SQLCIPHER_CORRUPT_BKPT;
50797       }
50798       data[hdr+7] -= (u8)frag;
50799       x = get2byte(&data[pnext]);
50800       put2byte(&data[pbegin], x);
50801       x = pnext + get2byte(&data[pnext+2]) - pbegin;
50802       put2byte(&data[pbegin+2], x);
50803     }else{
50804       addr = pbegin;
50805     }
50806   }
50807
50808   /* If the cell content area begins with a freeblock, remove it. */
50809   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
50810     int top;
50811     pbegin = get2byte(&data[hdr+1]);
50812     memcpy(&data[hdr+1], &data[pbegin], 2);
50813     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
50814     put2byte(&data[hdr+5], top);
50815   }
50816   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
50817   return SQLCIPHER_OK;
50818 }
50819
50820 /*
50821 ** Decode the flags byte (the first byte of the header) for a page
50822 ** and initialize fields of the MemPage structure accordingly.
50823 **
50824 ** Only the following combinations are supported.  Anything different
50825 ** indicates a corrupt database files:
50826 **
50827 **         PTF_ZERODATA
50828 **         PTF_ZERODATA | PTF_LEAF
50829 **         PTF_LEAFDATA | PTF_INTKEY
50830 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
50831 */
50832 static int decodeFlags(MemPage *pPage, int flagByte){
50833   BtShared *pBt;     /* A copy of pPage->pBt */
50834
50835   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
50836   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50837   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
50838   flagByte &= ~PTF_LEAF;
50839   pPage->childPtrSize = 4-4*pPage->leaf;
50840   pBt = pPage->pBt;
50841   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
50842     pPage->intKey = 1;
50843     pPage->hasData = pPage->leaf;
50844     pPage->maxLocal = pBt->maxLeaf;
50845     pPage->minLocal = pBt->minLeaf;
50846   }else if( flagByte==PTF_ZERODATA ){
50847     pPage->intKey = 0;
50848     pPage->hasData = 0;
50849     pPage->maxLocal = pBt->maxLocal;
50850     pPage->minLocal = pBt->minLocal;
50851   }else{
50852     return SQLCIPHER_CORRUPT_BKPT;
50853   }
50854   return SQLCIPHER_OK;
50855 }
50856
50857 /*
50858 ** Initialize the auxiliary information for a disk block.
50859 **
50860 ** Return SQLCIPHER_OK on success.  If we see that the page does
50861 ** not contain a well-formed database page, then return 
50862 ** SQLCIPHER_CORRUPT.  Note that a return of SQLCIPHER_OK does not
50863 ** guarantee that the page is well-formed.  It only shows that
50864 ** we failed to detect any corruption.
50865 */
50866 static int btreeInitPage(MemPage *pPage){
50867
50868   assert( pPage->pBt!=0 );
50869   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50870   assert( pPage->pgno==sqlcipher3PagerPagenumber(pPage->pDbPage) );
50871   assert( pPage == sqlcipher3PagerGetExtra(pPage->pDbPage) );
50872   assert( pPage->aData == sqlcipher3PagerGetData(pPage->pDbPage) );
50873
50874   if( !pPage->isInit ){
50875     u16 pc;            /* Address of a freeblock within pPage->aData[] */
50876     u8 hdr;            /* Offset to beginning of page header */
50877     u8 *data;          /* Equal to pPage->aData */
50878     BtShared *pBt;        /* The main btree structure */
50879     int usableSize;    /* Amount of usable space on each page */
50880     u16 cellOffset;    /* Offset from start of page to first cell pointer */
50881     int nFree;         /* Number of unused bytes on the page */
50882     int top;           /* First byte of the cell content area */
50883     int iCellFirst;    /* First allowable cell or freeblock offset */
50884     int iCellLast;     /* Last possible cell or freeblock offset */
50885
50886     pBt = pPage->pBt;
50887
50888     hdr = pPage->hdrOffset;
50889     data = pPage->aData;
50890     if( decodeFlags(pPage, data[hdr]) ) return SQLCIPHER_CORRUPT_BKPT;
50891     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
50892     pPage->maskPage = (u16)(pBt->pageSize - 1);
50893     pPage->nOverflow = 0;
50894     usableSize = pBt->usableSize;
50895     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
50896     top = get2byteNotZero(&data[hdr+5]);
50897     pPage->nCell = get2byte(&data[hdr+3]);
50898     if( pPage->nCell>MX_CELL(pBt) ){
50899       /* To many cells for a single page.  The page must be corrupt */
50900       return SQLCIPHER_CORRUPT_BKPT;
50901     }
50902     testcase( pPage->nCell==MX_CELL(pBt) );
50903
50904     /* A malformed database page might cause us to read past the end
50905     ** of page when parsing a cell.  
50906     **
50907     ** The following block of code checks early to see if a cell extends
50908     ** past the end of a page boundary and causes SQLCIPHER_CORRUPT to be 
50909     ** returned if it does.
50910     */
50911     iCellFirst = cellOffset + 2*pPage->nCell;
50912     iCellLast = usableSize - 4;
50913 #if defined(SQLCIPHER_ENABLE_OVERSIZE_CELL_CHECK)
50914     {
50915       int i;            /* Index into the cell pointer array */
50916       int sz;           /* Size of a cell */
50917
50918       if( !pPage->leaf ) iCellLast--;
50919       for(i=0; i<pPage->nCell; i++){
50920         pc = get2byte(&data[cellOffset+i*2]);
50921         testcase( pc==iCellFirst );
50922         testcase( pc==iCellLast );
50923         if( pc<iCellFirst || pc>iCellLast ){
50924           return SQLCIPHER_CORRUPT_BKPT;
50925         }
50926         sz = cellSizePtr(pPage, &data[pc]);
50927         testcase( pc+sz==usableSize );
50928         if( pc+sz>usableSize ){
50929           return SQLCIPHER_CORRUPT_BKPT;
50930         }
50931       }
50932       if( !pPage->leaf ) iCellLast++;
50933     }  
50934 #endif
50935
50936     /* Compute the total free space on the page */
50937     pc = get2byte(&data[hdr+1]);
50938     nFree = data[hdr+7] + top;
50939     while( pc>0 ){
50940       u16 next, size;
50941       if( pc<iCellFirst || pc>iCellLast ){
50942         /* Start of free block is off the page */
50943         return SQLCIPHER_CORRUPT_BKPT; 
50944       }
50945       next = get2byte(&data[pc]);
50946       size = get2byte(&data[pc+2]);
50947       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
50948         /* Free blocks must be in ascending order. And the last byte of
50949         ** the free-block must lie on the database page.  */
50950         return SQLCIPHER_CORRUPT_BKPT; 
50951       }
50952       nFree = nFree + size;
50953       pc = next;
50954     }
50955
50956     /* At this point, nFree contains the sum of the offset to the start
50957     ** of the cell-content area plus the number of free bytes within
50958     ** the cell-content area. If this is greater than the usable-size
50959     ** of the page, then the page must be corrupted. This check also
50960     ** serves to verify that the offset to the start of the cell-content
50961     ** area, according to the page header, lies within the page.
50962     */
50963     if( nFree>usableSize ){
50964       return SQLCIPHER_CORRUPT_BKPT; 
50965     }
50966     pPage->nFree = (u16)(nFree - iCellFirst);
50967     pPage->isInit = 1;
50968   }
50969   return SQLCIPHER_OK;
50970 }
50971
50972 /*
50973 ** Set up a raw page so that it looks like a database page holding
50974 ** no entries.
50975 */
50976 static void zeroPage(MemPage *pPage, int flags){
50977   unsigned char *data = pPage->aData;
50978   BtShared *pBt = pPage->pBt;
50979   u8 hdr = pPage->hdrOffset;
50980   u16 first;
50981
50982   assert( sqlcipher3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
50983   assert( sqlcipher3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
50984   assert( sqlcipher3PagerGetData(pPage->pDbPage) == data );
50985   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
50986   assert( sqlcipher3_mutex_held(pBt->mutex) );
50987   if( pBt->secureDelete ){
50988     memset(&data[hdr], 0, pBt->usableSize - hdr);
50989   }
50990   data[hdr] = (char)flags;
50991   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
50992   memset(&data[hdr+1], 0, 4);
50993   data[hdr+7] = 0;
50994   put2byte(&data[hdr+5], pBt->usableSize);
50995   pPage->nFree = (u16)(pBt->usableSize - first);
50996   decodeFlags(pPage, flags);
50997   pPage->hdrOffset = hdr;
50998   pPage->cellOffset = first;
50999   pPage->nOverflow = 0;
51000   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
51001   pPage->maskPage = (u16)(pBt->pageSize - 1);
51002   pPage->nCell = 0;
51003   pPage->isInit = 1;
51004 }
51005
51006
51007 /*
51008 ** Convert a DbPage obtained from the pager into a MemPage used by
51009 ** the btree layer.
51010 */
51011 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
51012   MemPage *pPage = (MemPage*)sqlcipher3PagerGetExtra(pDbPage);
51013   pPage->aData = sqlcipher3PagerGetData(pDbPage);
51014   pPage->pDbPage = pDbPage;
51015   pPage->pBt = pBt;
51016   pPage->pgno = pgno;
51017   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
51018   return pPage; 
51019 }
51020
51021 /*
51022 ** Get a page from the pager.  Initialize the MemPage.pBt and
51023 ** MemPage.aData elements if needed.
51024 **
51025 ** If the noContent flag is set, it means that we do not care about
51026 ** the content of the page at this time.  So do not go to the disk
51027 ** to fetch the content.  Just fill in the content with zeros for now.
51028 ** If in the future we call sqlcipher3PagerWrite() on this page, that
51029 ** means we have started to be concerned about content and the disk
51030 ** read should occur at that point.
51031 */
51032 static int btreeGetPage(
51033   BtShared *pBt,       /* The btree */
51034   Pgno pgno,           /* Number of the page to fetch */
51035   MemPage **ppPage,    /* Return the page in this parameter */
51036   int noContent        /* Do not load page content if true */
51037 ){
51038   int rc;
51039   DbPage *pDbPage;
51040
51041   assert( sqlcipher3_mutex_held(pBt->mutex) );
51042   rc = sqlcipher3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
51043   if( rc ) return rc;
51044   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
51045   return SQLCIPHER_OK;
51046 }
51047
51048 /*
51049 ** Retrieve a page from the pager cache. If the requested page is not
51050 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
51051 ** MemPage.aData elements if needed.
51052 */
51053 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
51054   DbPage *pDbPage;
51055   assert( sqlcipher3_mutex_held(pBt->mutex) );
51056   pDbPage = sqlcipher3PagerLookup(pBt->pPager, pgno);
51057   if( pDbPage ){
51058     return btreePageFromDbPage(pDbPage, pgno, pBt);
51059   }
51060   return 0;
51061 }
51062
51063 /*
51064 ** Return the size of the database file in pages. If there is any kind of
51065 ** error, return ((unsigned int)-1).
51066 */
51067 static Pgno btreePagecount(BtShared *pBt){
51068   return pBt->nPage;
51069 }
51070 SQLCIPHER_PRIVATE u32 sqlcipher3BtreeLastPage(Btree *p){
51071   assert( sqlcipher3BtreeHoldsMutex(p) );
51072   assert( ((p->pBt->nPage)&0x8000000)==0 );
51073   return (int)btreePagecount(p->pBt);
51074 }
51075
51076 /*
51077 ** Get a page from the pager and initialize it.  This routine is just a
51078 ** convenience wrapper around separate calls to btreeGetPage() and 
51079 ** btreeInitPage().
51080 **
51081 ** If an error occurs, then the value *ppPage is set to is undefined. It
51082 ** may remain unchanged, or it may be set to an invalid value.
51083 */
51084 static int getAndInitPage(
51085   BtShared *pBt,          /* The database file */
51086   Pgno pgno,           /* Number of the page to get */
51087   MemPage **ppPage     /* Write the page pointer here */
51088 ){
51089   int rc;
51090   assert( sqlcipher3_mutex_held(pBt->mutex) );
51091
51092   if( pgno>btreePagecount(pBt) ){
51093     rc = SQLCIPHER_CORRUPT_BKPT;
51094   }else{
51095     rc = btreeGetPage(pBt, pgno, ppPage, 0);
51096     if( rc==SQLCIPHER_OK ){
51097       rc = btreeInitPage(*ppPage);
51098       if( rc!=SQLCIPHER_OK ){
51099         releasePage(*ppPage);
51100       }
51101     }
51102   }
51103
51104   testcase( pgno==0 );
51105   assert( pgno!=0 || rc==SQLCIPHER_CORRUPT );
51106   return rc;
51107 }
51108
51109 /*
51110 ** Release a MemPage.  This should be called once for each prior
51111 ** call to btreeGetPage.
51112 */
51113 static void releasePage(MemPage *pPage){
51114   if( pPage ){
51115     assert( pPage->aData );
51116     assert( pPage->pBt );
51117     assert( sqlcipher3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51118     assert( sqlcipher3PagerGetData(pPage->pDbPage)==pPage->aData );
51119     assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
51120     sqlcipher3PagerUnref(pPage->pDbPage);
51121   }
51122 }
51123
51124 /*
51125 ** During a rollback, when the pager reloads information into the cache
51126 ** so that the cache is restored to its original state at the start of
51127 ** the transaction, for each page restored this routine is called.
51128 **
51129 ** This routine needs to reset the extra data section at the end of the
51130 ** page to agree with the restored data.
51131 */
51132 static void pageReinit(DbPage *pData){
51133   MemPage *pPage;
51134   pPage = (MemPage *)sqlcipher3PagerGetExtra(pData);
51135   assert( sqlcipher3PagerPageRefcount(pData)>0 );
51136   if( pPage->isInit ){
51137     assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
51138     pPage->isInit = 0;
51139     if( sqlcipher3PagerPageRefcount(pData)>1 ){
51140       /* pPage might not be a btree page;  it might be an overflow page
51141       ** or ptrmap page or a free page.  In those cases, the following
51142       ** call to btreeInitPage() will likely return SQLCIPHER_CORRUPT.
51143       ** But no harm is done by this.  And it is very important that
51144       ** btreeInitPage() be called on every btree page so we make
51145       ** the call for every page that comes in for re-initing. */
51146       btreeInitPage(pPage);
51147     }
51148   }
51149 }
51150
51151 /*
51152 ** Invoke the busy handler for a btree.
51153 */
51154 static int btreeInvokeBusyHandler(void *pArg){
51155   BtShared *pBt = (BtShared*)pArg;
51156   assert( pBt->db );
51157   assert( sqlcipher3_mutex_held(pBt->db->mutex) );
51158   return sqlcipher3InvokeBusyHandler(&pBt->db->busyHandler);
51159 }
51160
51161 /*
51162 ** Open a database file.
51163 ** 
51164 ** zFilename is the name of the database file.  If zFilename is NULL
51165 ** then an ephemeral database is created.  The ephemeral database might
51166 ** be exclusively in memory, or it might use a disk-based memory cache.
51167 ** Either way, the ephemeral database will be automatically deleted 
51168 ** when sqlcipher3BtreeClose() is called.
51169 **
51170 ** If zFilename is ":memory:" then an in-memory database is created
51171 ** that is automatically destroyed when it is closed.
51172 **
51173 ** The "flags" parameter is a bitmask that might contain bits
51174 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK.  The BTREE_NO_READLOCK
51175 ** bit is also set if the SQLCIPHER_NoReadlock flags is set in db->flags.
51176 ** These flags are passed through into sqlcipher3PagerOpen() and must
51177 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
51178 **
51179 ** If the database is already opened in the same database connection
51180 ** and we are in shared cache mode, then the open will fail with an
51181 ** SQLCIPHER_CONSTRAINT error.  We cannot allow two or more BtShared
51182 ** objects in the same database connection since doing so will lead
51183 ** to problems with locking.
51184 */
51185 SQLCIPHER_PRIVATE int sqlcipher3BtreeOpen(
51186   sqlcipher3_vfs *pVfs,      /* VFS to use for this b-tree */
51187   const char *zFilename,  /* Name of the file containing the BTree database */
51188   sqlcipher3 *db,            /* Associated database handle */
51189   Btree **ppBtree,        /* Pointer to new Btree object written here */
51190   int flags,              /* Options */
51191   int vfsFlags            /* Flags passed through to sqlcipher3_vfs.xOpen() */
51192 ){
51193   BtShared *pBt = 0;             /* Shared part of btree structure */
51194   Btree *p;                      /* Handle to return */
51195   sqlcipher3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
51196   int rc = SQLCIPHER_OK;            /* Result code from this function */
51197   u8 nReserve;                   /* Byte of unused space on each page */
51198   unsigned char zDbHeader[100];  /* Database header content */
51199
51200   /* True if opening an ephemeral, temporary database */
51201   const int isTempDb = zFilename==0 || zFilename[0]==0;
51202
51203   /* Set the variable isMemdb to true for an in-memory database, or 
51204   ** false for a file-based database.
51205   */
51206 #ifdef SQLCIPHER_OMIT_MEMORYDB
51207   const int isMemdb = 0;
51208 #else
51209   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
51210                        || (isTempDb && sqlcipher3TempInMemory(db));
51211 #endif
51212
51213   assert( db!=0 );
51214   assert( pVfs!=0 );
51215   assert( sqlcipher3_mutex_held(db->mutex) );
51216   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
51217
51218   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
51219   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
51220
51221   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
51222   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
51223
51224   if( db->flags & SQLCIPHER_NoReadlock ){
51225     flags |= BTREE_NO_READLOCK;
51226   }
51227   if( isMemdb ){
51228     flags |= BTREE_MEMORY;
51229   }
51230   if( (vfsFlags & SQLCIPHER_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
51231     vfsFlags = (vfsFlags & ~SQLCIPHER_OPEN_MAIN_DB) | SQLCIPHER_OPEN_TEMP_DB;
51232   }
51233   p = sqlcipher3MallocZero(sizeof(Btree));
51234   if( !p ){
51235     return SQLCIPHER_NOMEM;
51236   }
51237   p->inTrans = TRANS_NONE;
51238   p->db = db;
51239 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
51240   p->lock.pBtree = p;
51241   p->lock.iTable = 1;
51242 #endif
51243
51244 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && !defined(SQLCIPHER_OMIT_DISKIO)
51245   /*
51246   ** If this Btree is a candidate for shared cache, try to find an
51247   ** existing BtShared object that we can share with
51248   */
51249   if( isMemdb==0 && isTempDb==0 ){
51250     if( vfsFlags & SQLCIPHER_OPEN_SHAREDCACHE ){
51251       int nFullPathname = pVfs->mxPathname+1;
51252       char *zFullPathname = sqlcipher3Malloc(nFullPathname);
51253       MUTEX_LOGIC( sqlcipher3_mutex *mutexShared; )
51254       p->sharable = 1;
51255       if( !zFullPathname ){
51256         sqlcipher3_free(p);
51257         return SQLCIPHER_NOMEM;
51258       }
51259       sqlcipher3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
51260 #if SQLCIPHER_THREADSAFE
51261       mutexOpen = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_OPEN);
51262       sqlcipher3_mutex_enter(mutexOpen);
51263       mutexShared = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
51264       sqlcipher3_mutex_enter(mutexShared);
51265 #endif
51266       for(pBt=GLOBAL(BtShared*,sqlcipher3SharedCacheList); pBt; pBt=pBt->pNext){
51267         assert( pBt->nRef>0 );
51268         if( 0==strcmp(zFullPathname, sqlcipher3PagerFilename(pBt->pPager))
51269                  && sqlcipher3PagerVfs(pBt->pPager)==pVfs ){
51270           int iDb;
51271           for(iDb=db->nDb-1; iDb>=0; iDb--){
51272             Btree *pExisting = db->aDb[iDb].pBt;
51273             if( pExisting && pExisting->pBt==pBt ){
51274               sqlcipher3_mutex_leave(mutexShared);
51275               sqlcipher3_mutex_leave(mutexOpen);
51276               sqlcipher3_free(zFullPathname);
51277               sqlcipher3_free(p);
51278               return SQLCIPHER_CONSTRAINT;
51279             }
51280           }
51281           p->pBt = pBt;
51282           pBt->nRef++;
51283           break;
51284         }
51285       }
51286       sqlcipher3_mutex_leave(mutexShared);
51287       sqlcipher3_free(zFullPathname);
51288     }
51289 #ifdef SQLCIPHER_DEBUG
51290     else{
51291       /* In debug mode, we mark all persistent databases as sharable
51292       ** even when they are not.  This exercises the locking code and
51293       ** gives more opportunity for asserts(sqlcipher3_mutex_held())
51294       ** statements to find locking problems.
51295       */
51296       p->sharable = 1;
51297     }
51298 #endif
51299   }
51300 #endif
51301   if( pBt==0 ){
51302     /*
51303     ** The following asserts make sure that structures used by the btree are
51304     ** the right size.  This is to guard against size changes that result
51305     ** when compiling on a different architecture.
51306     */
51307     assert( sizeof(i64)==8 || sizeof(i64)==4 );
51308     assert( sizeof(u64)==8 || sizeof(u64)==4 );
51309     assert( sizeof(u32)==4 );
51310     assert( sizeof(u16)==2 );
51311     assert( sizeof(Pgno)==4 );
51312   
51313     pBt = sqlcipher3MallocZero( sizeof(*pBt) );
51314     if( pBt==0 ){
51315       rc = SQLCIPHER_NOMEM;
51316       goto btree_open_out;
51317     }
51318     rc = sqlcipher3PagerOpen(pVfs, &pBt->pPager, zFilename,
51319                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
51320     if( rc==SQLCIPHER_OK ){
51321       rc = sqlcipher3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
51322     }
51323     if( rc!=SQLCIPHER_OK ){
51324       goto btree_open_out;
51325     }
51326     pBt->openFlags = (u8)flags;
51327     pBt->db = db;
51328     sqlcipher3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
51329     p->pBt = pBt;
51330   
51331     pBt->pCursor = 0;
51332     pBt->pPage1 = 0;
51333     pBt->readOnly = sqlcipher3PagerIsreadonly(pBt->pPager);
51334 #ifdef SQLCIPHER_SECURE_DELETE
51335     pBt->secureDelete = 1;
51336 #endif
51337     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
51338     if( pBt->pageSize<512 || pBt->pageSize>SQLCIPHER_MAX_PAGE_SIZE
51339          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
51340       pBt->pageSize = 0;
51341 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
51342       /* If the magic name ":memory:" will create an in-memory database, then
51343       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
51344       ** SQLCIPHER_DEFAULT_AUTOVACUUM is true. On the other hand, if
51345       ** SQLCIPHER_OMIT_MEMORYDB has been defined, then ":memory:" is just a
51346       ** regular file-name. In this case the auto-vacuum applies as per normal.
51347       */
51348       if( zFilename && !isMemdb ){
51349         pBt->autoVacuum = (SQLCIPHER_DEFAULT_AUTOVACUUM ? 1 : 0);
51350         pBt->incrVacuum = (SQLCIPHER_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
51351       }
51352 #endif
51353       nReserve = 0;
51354     }else{
51355       nReserve = zDbHeader[20];
51356       pBt->pageSizeFixed = 1;
51357 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
51358       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
51359       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
51360 #endif
51361     }
51362     rc = sqlcipher3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51363     if( rc ) goto btree_open_out;
51364     pBt->usableSize = pBt->pageSize - nReserve;
51365     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
51366    
51367 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && !defined(SQLCIPHER_OMIT_DISKIO)
51368     /* Add the new BtShared object to the linked list sharable BtShareds.
51369     */
51370     if( p->sharable ){
51371       MUTEX_LOGIC( sqlcipher3_mutex *mutexShared; )
51372       pBt->nRef = 1;
51373       MUTEX_LOGIC( mutexShared = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);)
51374       if( SQLCIPHER_THREADSAFE && sqlcipher3GlobalConfig.bCoreMutex ){
51375         pBt->mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_FAST);
51376         if( pBt->mutex==0 ){
51377           rc = SQLCIPHER_NOMEM;
51378           db->mallocFailed = 0;
51379           goto btree_open_out;
51380         }
51381       }
51382       sqlcipher3_mutex_enter(mutexShared);
51383       pBt->pNext = GLOBAL(BtShared*,sqlcipher3SharedCacheList);
51384       GLOBAL(BtShared*,sqlcipher3SharedCacheList) = pBt;
51385       sqlcipher3_mutex_leave(mutexShared);
51386     }
51387 #endif
51388   }
51389
51390 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && !defined(SQLCIPHER_OMIT_DISKIO)
51391   /* If the new Btree uses a sharable pBtShared, then link the new
51392   ** Btree into the list of all sharable Btrees for the same connection.
51393   ** The list is kept in ascending order by pBt address.
51394   */
51395   if( p->sharable ){
51396     int i;
51397     Btree *pSib;
51398     for(i=0; i<db->nDb; i++){
51399       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
51400         while( pSib->pPrev ){ pSib = pSib->pPrev; }
51401         if( p->pBt<pSib->pBt ){
51402           p->pNext = pSib;
51403           p->pPrev = 0;
51404           pSib->pPrev = p;
51405         }else{
51406           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
51407             pSib = pSib->pNext;
51408           }
51409           p->pNext = pSib->pNext;
51410           p->pPrev = pSib;
51411           if( p->pNext ){
51412             p->pNext->pPrev = p;
51413           }
51414           pSib->pNext = p;
51415         }
51416         break;
51417       }
51418     }
51419   }
51420 #endif
51421   *ppBtree = p;
51422
51423 btree_open_out:
51424   if( rc!=SQLCIPHER_OK ){
51425     if( pBt && pBt->pPager ){
51426       sqlcipher3PagerClose(pBt->pPager);
51427     }
51428     sqlcipher3_free(pBt);
51429     sqlcipher3_free(p);
51430     *ppBtree = 0;
51431   }else{
51432     /* If the B-Tree was successfully opened, set the pager-cache size to the
51433     ** default value. Except, when opening on an existing shared pager-cache,
51434     ** do not change the pager-cache size.
51435     */
51436     if( sqlcipher3BtreeSchema(p, 0, 0)==0 ){
51437       sqlcipher3PagerSetCachesize(p->pBt->pPager, SQLCIPHER_DEFAULT_CACHE_SIZE);
51438     }
51439   }
51440   if( mutexOpen ){
51441     assert( sqlcipher3_mutex_held(mutexOpen) );
51442     sqlcipher3_mutex_leave(mutexOpen);
51443   }
51444   return rc;
51445 }
51446
51447 /*
51448 ** Decrement the BtShared.nRef counter.  When it reaches zero,
51449 ** remove the BtShared structure from the sharing list.  Return
51450 ** true if the BtShared.nRef counter reaches zero and return
51451 ** false if it is still positive.
51452 */
51453 static int removeFromSharingList(BtShared *pBt){
51454 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
51455   MUTEX_LOGIC( sqlcipher3_mutex *pMaster; )
51456   BtShared *pList;
51457   int removed = 0;
51458
51459   assert( sqlcipher3_mutex_notheld(pBt->mutex) );
51460   MUTEX_LOGIC( pMaster = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER); )
51461   sqlcipher3_mutex_enter(pMaster);
51462   pBt->nRef--;
51463   if( pBt->nRef<=0 ){
51464     if( GLOBAL(BtShared*,sqlcipher3SharedCacheList)==pBt ){
51465       GLOBAL(BtShared*,sqlcipher3SharedCacheList) = pBt->pNext;
51466     }else{
51467       pList = GLOBAL(BtShared*,sqlcipher3SharedCacheList);
51468       while( ALWAYS(pList) && pList->pNext!=pBt ){
51469         pList=pList->pNext;
51470       }
51471       if( ALWAYS(pList) ){
51472         pList->pNext = pBt->pNext;
51473       }
51474     }
51475     if( SQLCIPHER_THREADSAFE ){
51476       sqlcipher3_mutex_free(pBt->mutex);
51477     }
51478     removed = 1;
51479   }
51480   sqlcipher3_mutex_leave(pMaster);
51481   return removed;
51482 #else
51483   return 1;
51484 #endif
51485 }
51486
51487 /*
51488 ** Make sure pBt->pTmpSpace points to an allocation of 
51489 ** MX_CELL_SIZE(pBt) bytes.
51490 */
51491 static void allocateTempSpace(BtShared *pBt){
51492   if( !pBt->pTmpSpace ){
51493     pBt->pTmpSpace = sqlcipher3PageMalloc( pBt->pageSize );
51494   }
51495 }
51496
51497 /*
51498 ** Free the pBt->pTmpSpace allocation
51499 */
51500 static void freeTempSpace(BtShared *pBt){
51501   sqlcipher3PageFree( pBt->pTmpSpace);
51502   pBt->pTmpSpace = 0;
51503 }
51504
51505 /*
51506 ** Close an open database and invalidate all cursors.
51507 */
51508 SQLCIPHER_PRIVATE int sqlcipher3BtreeClose(Btree *p){
51509   BtShared *pBt = p->pBt;
51510   BtCursor *pCur;
51511
51512   /* Close all cursors opened via this handle.  */
51513   assert( sqlcipher3_mutex_held(p->db->mutex) );
51514   sqlcipher3BtreeEnter(p);
51515   pCur = pBt->pCursor;
51516   while( pCur ){
51517     BtCursor *pTmp = pCur;
51518     pCur = pCur->pNext;
51519     if( pTmp->pBtree==p ){
51520       sqlcipher3BtreeCloseCursor(pTmp);
51521     }
51522   }
51523
51524   /* Rollback any active transaction and free the handle structure.
51525   ** The call to sqlcipher3BtreeRollback() drops any table-locks held by
51526   ** this handle.
51527   */
51528   sqlcipher3BtreeRollback(p);
51529   sqlcipher3BtreeLeave(p);
51530
51531   /* If there are still other outstanding references to the shared-btree
51532   ** structure, return now. The remainder of this procedure cleans 
51533   ** up the shared-btree.
51534   */
51535   assert( p->wantToLock==0 && p->locked==0 );
51536   if( !p->sharable || removeFromSharingList(pBt) ){
51537     /* The pBt is no longer on the sharing list, so we can access
51538     ** it without having to hold the mutex.
51539     **
51540     ** Clean out and delete the BtShared object.
51541     */
51542     assert( !pBt->pCursor );
51543     sqlcipher3PagerClose(pBt->pPager);
51544     if( pBt->xFreeSchema && pBt->pSchema ){
51545       pBt->xFreeSchema(pBt->pSchema);
51546     }
51547     sqlcipher3DbFree(0, pBt->pSchema);
51548     freeTempSpace(pBt);
51549     sqlcipher3_free(pBt);
51550   }
51551
51552 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
51553   assert( p->wantToLock==0 );
51554   assert( p->locked==0 );
51555   if( p->pPrev ) p->pPrev->pNext = p->pNext;
51556   if( p->pNext ) p->pNext->pPrev = p->pPrev;
51557 #endif
51558
51559   sqlcipher3_free(p);
51560   return SQLCIPHER_OK;
51561 }
51562
51563 /*
51564 ** Change the limit on the number of pages allowed in the cache.
51565 **
51566 ** The maximum number of cache pages is set to the absolute
51567 ** value of mxPage.  If mxPage is negative, the pager will
51568 ** operate asynchronously - it will not stop to do fsync()s
51569 ** to insure data is written to the disk surface before
51570 ** continuing.  Transactions still work if synchronous is off,
51571 ** and the database cannot be corrupted if this program
51572 ** crashes.  But if the operating system crashes or there is
51573 ** an abrupt power failure when synchronous is off, the database
51574 ** could be left in an inconsistent and unrecoverable state.
51575 ** Synchronous is on by default so database corruption is not
51576 ** normally a worry.
51577 */
51578 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetCacheSize(Btree *p, int mxPage){
51579   BtShared *pBt = p->pBt;
51580   assert( sqlcipher3_mutex_held(p->db->mutex) );
51581   sqlcipher3BtreeEnter(p);
51582   sqlcipher3PagerSetCachesize(pBt->pPager, mxPage);
51583   sqlcipher3BtreeLeave(p);
51584   return SQLCIPHER_OK;
51585 }
51586
51587 /*
51588 ** Change the way data is synced to disk in order to increase or decrease
51589 ** how well the database resists damage due to OS crashes and power
51590 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
51591 ** there is a high probability of damage)  Level 2 is the default.  There
51592 ** is a very low but non-zero probability of damage.  Level 3 reduces the
51593 ** probability of damage to near zero but with a write performance reduction.
51594 */
51595 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
51596 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetSafetyLevel(
51597   Btree *p,              /* The btree to set the safety level on */
51598   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
51599   int fullSync,          /* PRAGMA fullfsync. */
51600   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
51601 ){
51602   BtShared *pBt = p->pBt;
51603   assert( sqlcipher3_mutex_held(p->db->mutex) );
51604   assert( level>=1 && level<=3 );
51605   sqlcipher3BtreeEnter(p);
51606   sqlcipher3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
51607   sqlcipher3BtreeLeave(p);
51608   return SQLCIPHER_OK;
51609 }
51610 #endif
51611
51612 /*
51613 ** Return TRUE if the given btree is set to safety level 1.  In other
51614 ** words, return TRUE if no sync() occurs on the disk files.
51615 */
51616 SQLCIPHER_PRIVATE int sqlcipher3BtreeSyncDisabled(Btree *p){
51617   BtShared *pBt = p->pBt;
51618   int rc;
51619   assert( sqlcipher3_mutex_held(p->db->mutex) );  
51620   sqlcipher3BtreeEnter(p);
51621   assert( pBt && pBt->pPager );
51622   rc = sqlcipher3PagerNosync(pBt->pPager);
51623   sqlcipher3BtreeLeave(p);
51624   return rc;
51625 }
51626
51627 /*
51628 ** Change the default pages size and the number of reserved bytes per page.
51629 ** Or, if the page size has already been fixed, return SQLCIPHER_READONLY 
51630 ** without changing anything.
51631 **
51632 ** The page size must be a power of 2 between 512 and 65536.  If the page
51633 ** size supplied does not meet this constraint then the page size is not
51634 ** changed.
51635 **
51636 ** Page sizes are constrained to be a power of two so that the region
51637 ** of the database file used for locking (beginning at PENDING_BYTE,
51638 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
51639 ** at the beginning of a page.
51640 **
51641 ** If parameter nReserve is less than zero, then the number of reserved
51642 ** bytes per page is left unchanged.
51643 **
51644 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
51645 ** and autovacuum mode can no longer be changed.
51646 */
51647 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
51648   int rc = SQLCIPHER_OK;
51649   BtShared *pBt = p->pBt;
51650   assert( nReserve>=-1 && nReserve<=255 );
51651   sqlcipher3BtreeEnter(p);
51652   if( pBt->pageSizeFixed ){
51653     sqlcipher3BtreeLeave(p);
51654     return SQLCIPHER_READONLY;
51655   }
51656   if( nReserve<0 ){
51657     nReserve = pBt->pageSize - pBt->usableSize;
51658   }
51659   assert( nReserve>=0 && nReserve<=255 );
51660   if( pageSize>=512 && pageSize<=SQLCIPHER_MAX_PAGE_SIZE &&
51661         ((pageSize-1)&pageSize)==0 ){
51662     assert( (pageSize & 7)==0 );
51663     assert( !pBt->pPage1 && !pBt->pCursor );
51664     pBt->pageSize = (u32)pageSize;
51665     freeTempSpace(pBt);
51666   }
51667   rc = sqlcipher3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51668   pBt->usableSize = pBt->pageSize - (u16)nReserve;
51669   if( iFix ) pBt->pageSizeFixed = 1;
51670   sqlcipher3BtreeLeave(p);
51671   return rc;
51672 }
51673
51674 /*
51675 ** Return the currently defined page size
51676 */
51677 SQLCIPHER_PRIVATE int sqlcipher3BtreeGetPageSize(Btree *p){
51678   return p->pBt->pageSize;
51679 }
51680
51681 #if !defined(SQLCIPHER_OMIT_PAGER_PRAGMAS) || !defined(SQLCIPHER_OMIT_VACUUM)
51682 /*
51683 ** Return the number of bytes of space at the end of every page that
51684 ** are intentually left unused.  This is the "reserved" space that is
51685 ** sometimes used by extensions.
51686 */
51687 SQLCIPHER_PRIVATE int sqlcipher3BtreeGetReserve(Btree *p){
51688   int n;
51689   sqlcipher3BtreeEnter(p);
51690   n = p->pBt->pageSize - p->pBt->usableSize;
51691   sqlcipher3BtreeLeave(p);
51692   return n;
51693 }
51694
51695 /*
51696 ** Set the maximum page count for a database if mxPage is positive.
51697 ** No changes are made if mxPage is 0 or negative.
51698 ** Regardless of the value of mxPage, return the maximum page count.
51699 */
51700 SQLCIPHER_PRIVATE int sqlcipher3BtreeMaxPageCount(Btree *p, int mxPage){
51701   int n;
51702   sqlcipher3BtreeEnter(p);
51703   n = sqlcipher3PagerMaxPageCount(p->pBt->pPager, mxPage);
51704   sqlcipher3BtreeLeave(p);
51705   return n;
51706 }
51707
51708 /*
51709 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
51710 ** then make no changes.  Always return the value of the secureDelete
51711 ** setting after the change.
51712 */
51713 SQLCIPHER_PRIVATE int sqlcipher3BtreeSecureDelete(Btree *p, int newFlag){
51714   int b;
51715   if( p==0 ) return 0;
51716   sqlcipher3BtreeEnter(p);
51717   if( newFlag>=0 ){
51718     p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
51719   } 
51720   b = p->pBt->secureDelete;
51721   sqlcipher3BtreeLeave(p);
51722   return b;
51723 }
51724 #endif /* !defined(SQLCIPHER_OMIT_PAGER_PRAGMAS) || !defined(SQLCIPHER_OMIT_VACUUM) */
51725
51726 /*
51727 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
51728 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
51729 ** is disabled. The default value for the auto-vacuum property is 
51730 ** determined by the SQLCIPHER_DEFAULT_AUTOVACUUM macro.
51731 */
51732 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
51733 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
51734   return SQLCIPHER_READONLY;
51735 #else
51736   BtShared *pBt = p->pBt;
51737   int rc = SQLCIPHER_OK;
51738   u8 av = (u8)autoVacuum;
51739
51740   sqlcipher3BtreeEnter(p);
51741   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
51742     rc = SQLCIPHER_READONLY;
51743   }else{
51744     pBt->autoVacuum = av ?1:0;
51745     pBt->incrVacuum = av==2 ?1:0;
51746   }
51747   sqlcipher3BtreeLeave(p);
51748   return rc;
51749 #endif
51750 }
51751
51752 /*
51753 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
51754 ** enabled 1 is returned. Otherwise 0.
51755 */
51756 SQLCIPHER_PRIVATE int sqlcipher3BtreeGetAutoVacuum(Btree *p){
51757 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
51758   return BTREE_AUTOVACUUM_NONE;
51759 #else
51760   int rc;
51761   sqlcipher3BtreeEnter(p);
51762   rc = (
51763     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
51764     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
51765     BTREE_AUTOVACUUM_INCR
51766   );
51767   sqlcipher3BtreeLeave(p);
51768   return rc;
51769 #endif
51770 }
51771
51772
51773 /*
51774 ** Get a reference to pPage1 of the database file.  This will
51775 ** also acquire a readlock on that file.
51776 **
51777 ** SQLCIPHER_OK is returned on success.  If the file is not a
51778 ** well-formed database file, then SQLCIPHER_CORRUPT is returned.
51779 ** SQLCIPHER_BUSY is returned if the database is locked.  SQLCIPHER_NOMEM
51780 ** is returned if we run out of memory. 
51781 */
51782 static int lockBtree(BtShared *pBt){
51783   int rc;              /* Result code from subfunctions */
51784   MemPage *pPage1;     /* Page 1 of the database file */
51785   int nPage;           /* Number of pages in the database */
51786   int nPageFile = 0;   /* Number of pages in the database file */
51787   int nPageHeader;     /* Number of pages in the database according to hdr */
51788
51789   assert( sqlcipher3_mutex_held(pBt->mutex) );
51790   assert( pBt->pPage1==0 );
51791   rc = sqlcipher3PagerSharedLock(pBt->pPager);
51792   if( rc!=SQLCIPHER_OK ) return rc;
51793   rc = btreeGetPage(pBt, 1, &pPage1, 0);
51794   if( rc!=SQLCIPHER_OK ) return rc;
51795
51796   /* Do some checking to help insure the file we opened really is
51797   ** a valid database file. 
51798   */
51799   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
51800   sqlcipher3PagerPagecount(pBt->pPager, &nPageFile);
51801   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
51802     nPage = nPageFile;
51803   }
51804   if( nPage>0 ){
51805     u32 pageSize;
51806     u32 usableSize;
51807     u8 *page1 = pPage1->aData;
51808     rc = SQLCIPHER_NOTADB;
51809     if( memcmp(page1, zMagicHeader, 16)!=0 ){
51810       goto page1_init_failed;
51811     }
51812
51813 #ifdef SQLCIPHER_OMIT_WAL
51814     if( page1[18]>1 ){
51815       pBt->readOnly = 1;
51816     }
51817     if( page1[19]>1 ){
51818       goto page1_init_failed;
51819     }
51820 #else
51821     if( page1[18]>2 ){
51822       pBt->readOnly = 1;
51823     }
51824     if( page1[19]>2 ){
51825       goto page1_init_failed;
51826     }
51827
51828     /* If the write version is set to 2, this database should be accessed
51829     ** in WAL mode. If the log is not already open, open it now. Then 
51830     ** return SQLCIPHER_OK and return without populating BtShared.pPage1.
51831     ** The caller detects this and calls this function again. This is
51832     ** required as the version of page 1 currently in the page1 buffer
51833     ** may not be the latest version - there may be a newer one in the log
51834     ** file.
51835     */
51836     if( page1[19]==2 && pBt->doNotUseWAL==0 ){
51837       int isOpen = 0;
51838       rc = sqlcipher3PagerOpenWal(pBt->pPager, &isOpen);
51839       if( rc!=SQLCIPHER_OK ){
51840         goto page1_init_failed;
51841       }else if( isOpen==0 ){
51842         releasePage(pPage1);
51843         return SQLCIPHER_OK;
51844       }
51845       rc = SQLCIPHER_NOTADB;
51846     }
51847 #endif
51848
51849     /* The maximum embedded fraction must be exactly 25%.  And the minimum
51850     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
51851     ** The original design allowed these amounts to vary, but as of
51852     ** version 3.6.0, we require them to be fixed.
51853     */
51854     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
51855       goto page1_init_failed;
51856     }
51857     pageSize = (page1[16]<<8) | (page1[17]<<16);
51858     if( ((pageSize-1)&pageSize)!=0
51859      || pageSize>SQLCIPHER_MAX_PAGE_SIZE 
51860      || pageSize<=256 
51861     ){
51862       goto page1_init_failed;
51863     }
51864     assert( (pageSize & 7)==0 );
51865     usableSize = pageSize - page1[20];
51866     if( (u32)pageSize!=pBt->pageSize ){
51867       /* After reading the first page of the database assuming a page size
51868       ** of BtShared.pageSize, we have discovered that the page-size is
51869       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
51870       ** zero and return SQLCIPHER_OK. The caller will call this function
51871       ** again with the correct page-size.
51872       */
51873       releasePage(pPage1);
51874       pBt->usableSize = usableSize;
51875       pBt->pageSize = pageSize;
51876       freeTempSpace(pBt);
51877       rc = sqlcipher3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
51878                                    pageSize-usableSize);
51879       return rc;
51880     }
51881     if( (pBt->db->flags & SQLCIPHER_RecoveryMode)==0 && nPage>nPageFile ){
51882       rc = SQLCIPHER_CORRUPT_BKPT;
51883       goto page1_init_failed;
51884     }
51885     if( usableSize<480 ){
51886       goto page1_init_failed;
51887     }
51888     pBt->pageSize = pageSize;
51889     pBt->usableSize = usableSize;
51890 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
51891     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
51892     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
51893 #endif
51894   }
51895
51896   /* maxLocal is the maximum amount of payload to store locally for
51897   ** a cell.  Make sure it is small enough so that at least minFanout
51898   ** cells can will fit on one page.  We assume a 10-byte page header.
51899   ** Besides the payload, the cell must store:
51900   **     2-byte pointer to the cell
51901   **     4-byte child pointer
51902   **     9-byte nKey value
51903   **     4-byte nData value
51904   **     4-byte overflow page pointer
51905   ** So a cell consists of a 2-byte pointer, a header which is as much as
51906   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
51907   ** page pointer.
51908   */
51909   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
51910   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
51911   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
51912   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
51913   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
51914   pBt->pPage1 = pPage1;
51915   pBt->nPage = nPage;
51916   return SQLCIPHER_OK;
51917
51918 page1_init_failed:
51919   releasePage(pPage1);
51920   pBt->pPage1 = 0;
51921   return rc;
51922 }
51923
51924 /*
51925 ** If there are no outstanding cursors and we are not in the middle
51926 ** of a transaction but there is a read lock on the database, then
51927 ** this routine unrefs the first page of the database file which 
51928 ** has the effect of releasing the read lock.
51929 **
51930 ** If there is a transaction in progress, this routine is a no-op.
51931 */
51932 static void unlockBtreeIfUnused(BtShared *pBt){
51933   assert( sqlcipher3_mutex_held(pBt->mutex) );
51934   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
51935   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
51936     assert( pBt->pPage1->aData );
51937     assert( sqlcipher3PagerRefcount(pBt->pPager)==1 );
51938     assert( pBt->pPage1->aData );
51939     releasePage(pBt->pPage1);
51940     pBt->pPage1 = 0;
51941   }
51942 }
51943
51944 /*
51945 ** If pBt points to an empty file then convert that empty file
51946 ** into a new empty database by initializing the first page of
51947 ** the database.
51948 */
51949 static int newDatabase(BtShared *pBt){
51950   MemPage *pP1;
51951   unsigned char *data;
51952   int rc;
51953
51954   assert( sqlcipher3_mutex_held(pBt->mutex) );
51955   if( pBt->nPage>0 ){
51956     return SQLCIPHER_OK;
51957   }
51958   pP1 = pBt->pPage1;
51959   assert( pP1!=0 );
51960   data = pP1->aData;
51961   rc = sqlcipher3PagerWrite(pP1->pDbPage);
51962   if( rc ) return rc;
51963   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
51964   assert( sizeof(zMagicHeader)==16 );
51965   data[16] = (u8)((pBt->pageSize>>8)&0xff);
51966   data[17] = (u8)((pBt->pageSize>>16)&0xff);
51967   data[18] = 1;
51968   data[19] = 1;
51969   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
51970   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
51971   data[21] = 64;
51972   data[22] = 32;
51973   data[23] = 32;
51974   memset(&data[24], 0, 100-24);
51975   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
51976   pBt->pageSizeFixed = 1;
51977 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
51978   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
51979   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
51980   put4byte(&data[36 + 4*4], pBt->autoVacuum);
51981   put4byte(&data[36 + 7*4], pBt->incrVacuum);
51982 #endif
51983   pBt->nPage = 1;
51984   data[31] = 1;
51985   return SQLCIPHER_OK;
51986 }
51987
51988 /*
51989 ** Attempt to start a new transaction. A write-transaction
51990 ** is started if the second argument is nonzero, otherwise a read-
51991 ** transaction.  If the second argument is 2 or more and exclusive
51992 ** transaction is started, meaning that no other process is allowed
51993 ** to access the database.  A preexisting transaction may not be
51994 ** upgraded to exclusive by calling this routine a second time - the
51995 ** exclusivity flag only works for a new transaction.
51996 **
51997 ** A write-transaction must be started before attempting any 
51998 ** changes to the database.  None of the following routines 
51999 ** will work unless a transaction is started first:
52000 **
52001 **      sqlcipher3BtreeCreateTable()
52002 **      sqlcipher3BtreeCreateIndex()
52003 **      sqlcipher3BtreeClearTable()
52004 **      sqlcipher3BtreeDropTable()
52005 **      sqlcipher3BtreeInsert()
52006 **      sqlcipher3BtreeDelete()
52007 **      sqlcipher3BtreeUpdateMeta()
52008 **
52009 ** If an initial attempt to acquire the lock fails because of lock contention
52010 ** and the database was previously unlocked, then invoke the busy handler
52011 ** if there is one.  But if there was previously a read-lock, do not
52012 ** invoke the busy handler - just return SQLCIPHER_BUSY.  SQLCIPHER_BUSY is 
52013 ** returned when there is already a read-lock in order to avoid a deadlock.
52014 **
52015 ** Suppose there are two processes A and B.  A has a read lock and B has
52016 ** a reserved lock.  B tries to promote to exclusive but is blocked because
52017 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
52018 ** One or the other of the two processes must give way or there can be
52019 ** no progress.  By returning SQLCIPHER_BUSY and not invoking the busy callback
52020 ** when A already has a read lock, we encourage A to give up and let B
52021 ** proceed.
52022 */
52023 SQLCIPHER_PRIVATE int sqlcipher3BtreeBeginTrans(Btree *p, int wrflag){
52024   sqlcipher3 *pBlock = 0;
52025   BtShared *pBt = p->pBt;
52026   int rc = SQLCIPHER_OK;
52027
52028   sqlcipher3BtreeEnter(p);
52029   btreeIntegrity(p);
52030
52031   /* If the btree is already in a write-transaction, or it
52032   ** is already in a read-transaction and a read-transaction
52033   ** is requested, this is a no-op.
52034   */
52035   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
52036     goto trans_begun;
52037   }
52038
52039   /* Write transactions are not possible on a read-only database */
52040   if( pBt->readOnly && wrflag ){
52041     rc = SQLCIPHER_READONLY;
52042     goto trans_begun;
52043   }
52044
52045 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
52046   /* If another database handle has already opened a write transaction 
52047   ** on this shared-btree structure and a second write transaction is
52048   ** requested, return SQLCIPHER_LOCKED.
52049   */
52050   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
52051     pBlock = pBt->pWriter->db;
52052   }else if( wrflag>1 ){
52053     BtLock *pIter;
52054     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
52055       if( pIter->pBtree!=p ){
52056         pBlock = pIter->pBtree->db;
52057         break;
52058       }
52059     }
52060   }
52061   if( pBlock ){
52062     sqlcipher3ConnectionBlocked(p->db, pBlock);
52063     rc = SQLCIPHER_LOCKED_SHAREDCACHE;
52064     goto trans_begun;
52065   }
52066 #endif
52067
52068   /* Any read-only or read-write transaction implies a read-lock on 
52069   ** page 1. So if some other shared-cache client already has a write-lock 
52070   ** on page 1, the transaction cannot be opened. */
52071   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
52072   if( SQLCIPHER_OK!=rc ) goto trans_begun;
52073
52074   pBt->initiallyEmpty = (u8)(pBt->nPage==0);
52075   do {
52076     /* Call lockBtree() until either pBt->pPage1 is populated or
52077     ** lockBtree() returns something other than SQLCIPHER_OK. lockBtree()
52078     ** may return SQLCIPHER_OK but leave pBt->pPage1 set to 0 if after
52079     ** reading page 1 it discovers that the page-size of the database 
52080     ** file is not pBt->pageSize. In this case lockBtree() will update
52081     ** pBt->pageSize to the page-size of the file on disk.
52082     */
52083     while( pBt->pPage1==0 && SQLCIPHER_OK==(rc = lockBtree(pBt)) );
52084
52085     if( rc==SQLCIPHER_OK && wrflag ){
52086       if( pBt->readOnly ){
52087         rc = SQLCIPHER_READONLY;
52088       }else{
52089         rc = sqlcipher3PagerBegin(pBt->pPager,wrflag>1,sqlcipher3TempInMemory(p->db));
52090         if( rc==SQLCIPHER_OK ){
52091           rc = newDatabase(pBt);
52092         }
52093       }
52094     }
52095   
52096     if( rc!=SQLCIPHER_OK ){
52097       unlockBtreeIfUnused(pBt);
52098     }
52099   }while( (rc&0xFF)==SQLCIPHER_BUSY && pBt->inTransaction==TRANS_NONE &&
52100           btreeInvokeBusyHandler(pBt) );
52101
52102   if( rc==SQLCIPHER_OK ){
52103     if( p->inTrans==TRANS_NONE ){
52104       pBt->nTransaction++;
52105 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
52106       if( p->sharable ){
52107         assert( p->lock.pBtree==p && p->lock.iTable==1 );
52108         p->lock.eLock = READ_LOCK;
52109         p->lock.pNext = pBt->pLock;
52110         pBt->pLock = &p->lock;
52111       }
52112 #endif
52113     }
52114     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
52115     if( p->inTrans>pBt->inTransaction ){
52116       pBt->inTransaction = p->inTrans;
52117     }
52118     if( wrflag ){
52119       MemPage *pPage1 = pBt->pPage1;
52120 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
52121       assert( !pBt->pWriter );
52122       pBt->pWriter = p;
52123       pBt->isExclusive = (u8)(wrflag>1);
52124 #endif
52125
52126       /* If the db-size header field is incorrect (as it may be if an old
52127       ** client has been writing the database file), update it now. Doing
52128       ** this sooner rather than later means the database size can safely 
52129       ** re-read the database size from page 1 if a savepoint or transaction
52130       ** rollback occurs within the transaction.
52131       */
52132       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
52133         rc = sqlcipher3PagerWrite(pPage1->pDbPage);
52134         if( rc==SQLCIPHER_OK ){
52135           put4byte(&pPage1->aData[28], pBt->nPage);
52136         }
52137       }
52138     }
52139   }
52140
52141
52142 trans_begun:
52143   if( rc==SQLCIPHER_OK && wrflag ){
52144     /* This call makes sure that the pager has the correct number of
52145     ** open savepoints. If the second parameter is greater than 0 and
52146     ** the sub-journal is not already open, then it will be opened here.
52147     */
52148     rc = sqlcipher3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
52149   }
52150
52151   btreeIntegrity(p);
52152   sqlcipher3BtreeLeave(p);
52153   return rc;
52154 }
52155
52156 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
52157
52158 /*
52159 ** Set the pointer-map entries for all children of page pPage. Also, if
52160 ** pPage contains cells that point to overflow pages, set the pointer
52161 ** map entries for the overflow pages as well.
52162 */
52163 static int setChildPtrmaps(MemPage *pPage){
52164   int i;                             /* Counter variable */
52165   int nCell;                         /* Number of cells in page pPage */
52166   int rc;                            /* Return code */
52167   BtShared *pBt = pPage->pBt;
52168   u8 isInitOrig = pPage->isInit;
52169   Pgno pgno = pPage->pgno;
52170
52171   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
52172   rc = btreeInitPage(pPage);
52173   if( rc!=SQLCIPHER_OK ){
52174     goto set_child_ptrmaps_out;
52175   }
52176   nCell = pPage->nCell;
52177
52178   for(i=0; i<nCell; i++){
52179     u8 *pCell = findCell(pPage, i);
52180
52181     ptrmapPutOvflPtr(pPage, pCell, &rc);
52182
52183     if( !pPage->leaf ){
52184       Pgno childPgno = get4byte(pCell);
52185       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52186     }
52187   }
52188
52189   if( !pPage->leaf ){
52190     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52191     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52192   }
52193
52194 set_child_ptrmaps_out:
52195   pPage->isInit = isInitOrig;
52196   return rc;
52197 }
52198
52199 /*
52200 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
52201 ** that it points to iTo. Parameter eType describes the type of pointer to
52202 ** be modified, as  follows:
52203 **
52204 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
52205 **                   page of pPage.
52206 **
52207 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
52208 **                   page pointed to by one of the cells on pPage.
52209 **
52210 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
52211 **                   overflow page in the list.
52212 */
52213 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
52214   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
52215   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
52216   if( eType==PTRMAP_OVERFLOW2 ){
52217     /* The pointer is always the first 4 bytes of the page in this case.  */
52218     if( get4byte(pPage->aData)!=iFrom ){
52219       return SQLCIPHER_CORRUPT_BKPT;
52220     }
52221     put4byte(pPage->aData, iTo);
52222   }else{
52223     u8 isInitOrig = pPage->isInit;
52224     int i;
52225     int nCell;
52226
52227     btreeInitPage(pPage);
52228     nCell = pPage->nCell;
52229
52230     for(i=0; i<nCell; i++){
52231       u8 *pCell = findCell(pPage, i);
52232       if( eType==PTRMAP_OVERFLOW1 ){
52233         CellInfo info;
52234         btreeParseCellPtr(pPage, pCell, &info);
52235         if( info.iOverflow
52236          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
52237          && iFrom==get4byte(&pCell[info.iOverflow])
52238         ){
52239           put4byte(&pCell[info.iOverflow], iTo);
52240           break;
52241         }
52242       }else{
52243         if( get4byte(pCell)==iFrom ){
52244           put4byte(pCell, iTo);
52245           break;
52246         }
52247       }
52248     }
52249   
52250     if( i==nCell ){
52251       if( eType!=PTRMAP_BTREE || 
52252           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
52253         return SQLCIPHER_CORRUPT_BKPT;
52254       }
52255       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
52256     }
52257
52258     pPage->isInit = isInitOrig;
52259   }
52260   return SQLCIPHER_OK;
52261 }
52262
52263
52264 /*
52265 ** Move the open database page pDbPage to location iFreePage in the 
52266 ** database. The pDbPage reference remains valid.
52267 **
52268 ** The isCommit flag indicates that there is no need to remember that
52269 ** the journal needs to be sync()ed before database page pDbPage->pgno 
52270 ** can be written to. The caller has already promised not to write to that
52271 ** page.
52272 */
52273 static int relocatePage(
52274   BtShared *pBt,           /* Btree */
52275   MemPage *pDbPage,        /* Open page to move */
52276   u8 eType,                /* Pointer map 'type' entry for pDbPage */
52277   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
52278   Pgno iFreePage,          /* The location to move pDbPage to */
52279   int isCommit             /* isCommit flag passed to sqlcipher3PagerMovepage */
52280 ){
52281   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
52282   Pgno iDbPage = pDbPage->pgno;
52283   Pager *pPager = pBt->pPager;
52284   int rc;
52285
52286   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
52287       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
52288   assert( sqlcipher3_mutex_held(pBt->mutex) );
52289   assert( pDbPage->pBt==pBt );
52290
52291   /* Move page iDbPage from its current location to page number iFreePage */
52292   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
52293       iDbPage, iFreePage, iPtrPage, eType));
52294   rc = sqlcipher3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
52295   if( rc!=SQLCIPHER_OK ){
52296     return rc;
52297   }
52298   pDbPage->pgno = iFreePage;
52299
52300   /* If pDbPage was a btree-page, then it may have child pages and/or cells
52301   ** that point to overflow pages. The pointer map entries for all these
52302   ** pages need to be changed.
52303   **
52304   ** If pDbPage is an overflow page, then the first 4 bytes may store a
52305   ** pointer to a subsequent overflow page. If this is the case, then
52306   ** the pointer map needs to be updated for the subsequent overflow page.
52307   */
52308   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
52309     rc = setChildPtrmaps(pDbPage);
52310     if( rc!=SQLCIPHER_OK ){
52311       return rc;
52312     }
52313   }else{
52314     Pgno nextOvfl = get4byte(pDbPage->aData);
52315     if( nextOvfl!=0 ){
52316       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
52317       if( rc!=SQLCIPHER_OK ){
52318         return rc;
52319       }
52320     }
52321   }
52322
52323   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
52324   ** that it points at iFreePage. Also fix the pointer map entry for
52325   ** iPtrPage.
52326   */
52327   if( eType!=PTRMAP_ROOTPAGE ){
52328     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
52329     if( rc!=SQLCIPHER_OK ){
52330       return rc;
52331     }
52332     rc = sqlcipher3PagerWrite(pPtrPage->pDbPage);
52333     if( rc!=SQLCIPHER_OK ){
52334       releasePage(pPtrPage);
52335       return rc;
52336     }
52337     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
52338     releasePage(pPtrPage);
52339     if( rc==SQLCIPHER_OK ){
52340       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
52341     }
52342   }
52343   return rc;
52344 }
52345
52346 /* Forward declaration required by incrVacuumStep(). */
52347 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
52348
52349 /*
52350 ** Perform a single step of an incremental-vacuum. If successful,
52351 ** return SQLCIPHER_OK. If there is no work to do (and therefore no
52352 ** point in calling this function again), return SQLCIPHER_DONE.
52353 **
52354 ** More specificly, this function attempts to re-organize the 
52355 ** database so that the last page of the file currently in use
52356 ** is no longer in use.
52357 **
52358 ** If the nFin parameter is non-zero, this function assumes
52359 ** that the caller will keep calling incrVacuumStep() until
52360 ** it returns SQLCIPHER_DONE or an error, and that nFin is the
52361 ** number of pages the database file will contain after this 
52362 ** process is complete.  If nFin is zero, it is assumed that
52363 ** incrVacuumStep() will be called a finite amount of times
52364 ** which may or may not empty the freelist.  A full autovacuum
52365 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
52366 */
52367 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
52368   Pgno nFreeList;           /* Number of pages still on the free-list */
52369   int rc;
52370
52371   assert( sqlcipher3_mutex_held(pBt->mutex) );
52372   assert( iLastPg>nFin );
52373
52374   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
52375     u8 eType;
52376     Pgno iPtrPage;
52377
52378     nFreeList = get4byte(&pBt->pPage1->aData[36]);
52379     if( nFreeList==0 ){
52380       return SQLCIPHER_DONE;
52381     }
52382
52383     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
52384     if( rc!=SQLCIPHER_OK ){
52385       return rc;
52386     }
52387     if( eType==PTRMAP_ROOTPAGE ){
52388       return SQLCIPHER_CORRUPT_BKPT;
52389     }
52390
52391     if( eType==PTRMAP_FREEPAGE ){
52392       if( nFin==0 ){
52393         /* Remove the page from the files free-list. This is not required
52394         ** if nFin is non-zero. In that case, the free-list will be
52395         ** truncated to zero after this function returns, so it doesn't 
52396         ** matter if it still contains some garbage entries.
52397         */
52398         Pgno iFreePg;
52399         MemPage *pFreePg;
52400         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
52401         if( rc!=SQLCIPHER_OK ){
52402           return rc;
52403         }
52404         assert( iFreePg==iLastPg );
52405         releasePage(pFreePg);
52406       }
52407     } else {
52408       Pgno iFreePg;             /* Index of free page to move pLastPg to */
52409       MemPage *pLastPg;
52410
52411       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
52412       if( rc!=SQLCIPHER_OK ){
52413         return rc;
52414       }
52415
52416       /* If nFin is zero, this loop runs exactly once and page pLastPg
52417       ** is swapped with the first free page pulled off the free list.
52418       **
52419       ** On the other hand, if nFin is greater than zero, then keep
52420       ** looping until a free-page located within the first nFin pages
52421       ** of the file is found.
52422       */
52423       do {
52424         MemPage *pFreePg;
52425         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
52426         if( rc!=SQLCIPHER_OK ){
52427           releasePage(pLastPg);
52428           return rc;
52429         }
52430         releasePage(pFreePg);
52431       }while( nFin!=0 && iFreePg>nFin );
52432       assert( iFreePg<iLastPg );
52433       
52434       rc = sqlcipher3PagerWrite(pLastPg->pDbPage);
52435       if( rc==SQLCIPHER_OK ){
52436         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
52437       }
52438       releasePage(pLastPg);
52439       if( rc!=SQLCIPHER_OK ){
52440         return rc;
52441       }
52442     }
52443   }
52444
52445   if( nFin==0 ){
52446     iLastPg--;
52447     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
52448       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
52449         MemPage *pPg;
52450         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
52451         if( rc!=SQLCIPHER_OK ){
52452           return rc;
52453         }
52454         rc = sqlcipher3PagerWrite(pPg->pDbPage);
52455         releasePage(pPg);
52456         if( rc!=SQLCIPHER_OK ){
52457           return rc;
52458         }
52459       }
52460       iLastPg--;
52461     }
52462     sqlcipher3PagerTruncateImage(pBt->pPager, iLastPg);
52463     pBt->nPage = iLastPg;
52464   }
52465   return SQLCIPHER_OK;
52466 }
52467
52468 /*
52469 ** A write-transaction must be opened before calling this function.
52470 ** It performs a single unit of work towards an incremental vacuum.
52471 **
52472 ** If the incremental vacuum is finished after this function has run,
52473 ** SQLCIPHER_DONE is returned. If it is not finished, but no error occurred,
52474 ** SQLCIPHER_OK is returned. Otherwise an SQLite error code. 
52475 */
52476 SQLCIPHER_PRIVATE int sqlcipher3BtreeIncrVacuum(Btree *p){
52477   int rc;
52478   BtShared *pBt = p->pBt;
52479
52480   sqlcipher3BtreeEnter(p);
52481   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
52482   if( !pBt->autoVacuum ){
52483     rc = SQLCIPHER_DONE;
52484   }else{
52485     invalidateAllOverflowCache(pBt);
52486     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
52487     if( rc==SQLCIPHER_OK ){
52488       rc = sqlcipher3PagerWrite(pBt->pPage1->pDbPage);
52489       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
52490     }
52491   }
52492   sqlcipher3BtreeLeave(p);
52493   return rc;
52494 }
52495
52496 /*
52497 ** This routine is called prior to sqlcipher3PagerCommit when a transaction
52498 ** is commited for an auto-vacuum database.
52499 **
52500 ** If SQLCIPHER_OK is returned, then *pnTrunc is set to the number of pages
52501 ** the database file should be truncated to during the commit process. 
52502 ** i.e. the database has been reorganized so that only the first *pnTrunc
52503 ** pages are in use.
52504 */
52505 static int autoVacuumCommit(BtShared *pBt){
52506   int rc = SQLCIPHER_OK;
52507   Pager *pPager = pBt->pPager;
52508   VVA_ONLY( int nRef = sqlcipher3PagerRefcount(pPager) );
52509
52510   assert( sqlcipher3_mutex_held(pBt->mutex) );
52511   invalidateAllOverflowCache(pBt);
52512   assert(pBt->autoVacuum);
52513   if( !pBt->incrVacuum ){
52514     Pgno nFin;         /* Number of pages in database after autovacuuming */
52515     Pgno nFree;        /* Number of pages on the freelist initially */
52516     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
52517     Pgno iFree;        /* The next page to be freed */
52518     int nEntry;        /* Number of entries on one ptrmap page */
52519     Pgno nOrig;        /* Database size before freeing */
52520
52521     nOrig = btreePagecount(pBt);
52522     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
52523       /* It is not possible to create a database for which the final page
52524       ** is either a pointer-map page or the pending-byte page. If one
52525       ** is encountered, this indicates corruption.
52526       */
52527       return SQLCIPHER_CORRUPT_BKPT;
52528     }
52529
52530     nFree = get4byte(&pBt->pPage1->aData[36]);
52531     nEntry = pBt->usableSize/5;
52532     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
52533     nFin = nOrig - nFree - nPtrmap;
52534     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
52535       nFin--;
52536     }
52537     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
52538       nFin--;
52539     }
52540     if( nFin>nOrig ) return SQLCIPHER_CORRUPT_BKPT;
52541
52542     for(iFree=nOrig; iFree>nFin && rc==SQLCIPHER_OK; iFree--){
52543       rc = incrVacuumStep(pBt, nFin, iFree);
52544     }
52545     if( (rc==SQLCIPHER_DONE || rc==SQLCIPHER_OK) && nFree>0 ){
52546       rc = sqlcipher3PagerWrite(pBt->pPage1->pDbPage);
52547       put4byte(&pBt->pPage1->aData[32], 0);
52548       put4byte(&pBt->pPage1->aData[36], 0);
52549       put4byte(&pBt->pPage1->aData[28], nFin);
52550       sqlcipher3PagerTruncateImage(pBt->pPager, nFin);
52551       pBt->nPage = nFin;
52552     }
52553     if( rc!=SQLCIPHER_OK ){
52554       sqlcipher3PagerRollback(pPager);
52555     }
52556   }
52557
52558   assert( nRef==sqlcipher3PagerRefcount(pPager) );
52559   return rc;
52560 }
52561
52562 #else /* ifndef SQLCIPHER_OMIT_AUTOVACUUM */
52563 # define setChildPtrmaps(x) SQLCIPHER_OK
52564 #endif
52565
52566 /*
52567 ** This routine does the first phase of a two-phase commit.  This routine
52568 ** causes a rollback journal to be created (if it does not already exist)
52569 ** and populated with enough information so that if a power loss occurs
52570 ** the database can be restored to its original state by playing back
52571 ** the journal.  Then the contents of the journal are flushed out to
52572 ** the disk.  After the journal is safely on oxide, the changes to the
52573 ** database are written into the database file and flushed to oxide.
52574 ** At the end of this call, the rollback journal still exists on the
52575 ** disk and we are still holding all locks, so the transaction has not
52576 ** committed.  See sqlcipher3BtreeCommitPhaseTwo() for the second phase of the
52577 ** commit process.
52578 **
52579 ** This call is a no-op if no write-transaction is currently active on pBt.
52580 **
52581 ** Otherwise, sync the database file for the btree pBt. zMaster points to
52582 ** the name of a master journal file that should be written into the
52583 ** individual journal file, or is NULL, indicating no master journal file 
52584 ** (single database transaction).
52585 **
52586 ** When this is called, the master journal should already have been
52587 ** created, populated with this journal pointer and synced to disk.
52588 **
52589 ** Once this is routine has returned, the only thing required to commit
52590 ** the write-transaction for this database file is to delete the journal.
52591 */
52592 SQLCIPHER_PRIVATE int sqlcipher3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
52593   int rc = SQLCIPHER_OK;
52594   if( p->inTrans==TRANS_WRITE ){
52595     BtShared *pBt = p->pBt;
52596     sqlcipher3BtreeEnter(p);
52597 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
52598     if( pBt->autoVacuum ){
52599       rc = autoVacuumCommit(pBt);
52600       if( rc!=SQLCIPHER_OK ){
52601         sqlcipher3BtreeLeave(p);
52602         return rc;
52603       }
52604     }
52605 #endif
52606     rc = sqlcipher3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
52607     sqlcipher3BtreeLeave(p);
52608   }
52609   return rc;
52610 }
52611
52612 /*
52613 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
52614 ** at the conclusion of a transaction.
52615 */
52616 static void btreeEndTransaction(Btree *p){
52617   BtShared *pBt = p->pBt;
52618   assert( sqlcipher3BtreeHoldsMutex(p) );
52619
52620   btreeClearHasContent(pBt);
52621   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
52622     /* If there are other active statements that belong to this database
52623     ** handle, downgrade to a read-only transaction. The other statements
52624     ** may still be reading from the database.  */
52625     downgradeAllSharedCacheTableLocks(p);
52626     p->inTrans = TRANS_READ;
52627   }else{
52628     /* If the handle had any kind of transaction open, decrement the 
52629     ** transaction count of the shared btree. If the transaction count 
52630     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
52631     ** call below will unlock the pager.  */
52632     if( p->inTrans!=TRANS_NONE ){
52633       clearAllSharedCacheTableLocks(p);
52634       pBt->nTransaction--;
52635       if( 0==pBt->nTransaction ){
52636         pBt->inTransaction = TRANS_NONE;
52637       }
52638     }
52639
52640     /* Set the current transaction state to TRANS_NONE and unlock the 
52641     ** pager if this call closed the only read or write transaction.  */
52642     p->inTrans = TRANS_NONE;
52643     unlockBtreeIfUnused(pBt);
52644   }
52645
52646   btreeIntegrity(p);
52647 }
52648
52649 /*
52650 ** Commit the transaction currently in progress.
52651 **
52652 ** This routine implements the second phase of a 2-phase commit.  The
52653 ** sqlcipher3BtreeCommitPhaseOne() routine does the first phase and should
52654 ** be invoked prior to calling this routine.  The sqlcipher3BtreeCommitPhaseOne()
52655 ** routine did all the work of writing information out to disk and flushing the
52656 ** contents so that they are written onto the disk platter.  All this
52657 ** routine has to do is delete or truncate or zero the header in the
52658 ** the rollback journal (which causes the transaction to commit) and
52659 ** drop locks.
52660 **
52661 ** Normally, if an error occurs while the pager layer is attempting to 
52662 ** finalize the underlying journal file, this function returns an error and
52663 ** the upper layer will attempt a rollback. However, if the second argument
52664 ** is non-zero then this b-tree transaction is part of a multi-file 
52665 ** transaction. In this case, the transaction has already been committed 
52666 ** (by deleting a master journal file) and the caller will ignore this 
52667 ** functions return code. So, even if an error occurs in the pager layer,
52668 ** reset the b-tree objects internal state to indicate that the write
52669 ** transaction has been closed. This is quite safe, as the pager will have
52670 ** transitioned to the error state.
52671 **
52672 ** This will release the write lock on the database file.  If there
52673 ** are no active cursors, it also releases the read lock.
52674 */
52675 SQLCIPHER_PRIVATE int sqlcipher3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
52676
52677   if( p->inTrans==TRANS_NONE ) return SQLCIPHER_OK;
52678   sqlcipher3BtreeEnter(p);
52679   btreeIntegrity(p);
52680
52681   /* If the handle has a write-transaction open, commit the shared-btrees 
52682   ** transaction and set the shared state to TRANS_READ.
52683   */
52684   if( p->inTrans==TRANS_WRITE ){
52685     int rc;
52686     BtShared *pBt = p->pBt;
52687     assert( pBt->inTransaction==TRANS_WRITE );
52688     assert( pBt->nTransaction>0 );
52689     rc = sqlcipher3PagerCommitPhaseTwo(pBt->pPager);
52690     if( rc!=SQLCIPHER_OK && bCleanup==0 ){
52691       sqlcipher3BtreeLeave(p);
52692       return rc;
52693     }
52694     pBt->inTransaction = TRANS_READ;
52695   }
52696
52697   btreeEndTransaction(p);
52698   sqlcipher3BtreeLeave(p);
52699   return SQLCIPHER_OK;
52700 }
52701
52702 /*
52703 ** Do both phases of a commit.
52704 */
52705 SQLCIPHER_PRIVATE int sqlcipher3BtreeCommit(Btree *p){
52706   int rc;
52707   sqlcipher3BtreeEnter(p);
52708   rc = sqlcipher3BtreeCommitPhaseOne(p, 0);
52709   if( rc==SQLCIPHER_OK ){
52710     rc = sqlcipher3BtreeCommitPhaseTwo(p, 0);
52711   }
52712   sqlcipher3BtreeLeave(p);
52713   return rc;
52714 }
52715
52716 #ifndef NDEBUG
52717 /*
52718 ** Return the number of write-cursors open on this handle. This is for use
52719 ** in assert() expressions, so it is only compiled if NDEBUG is not
52720 ** defined.
52721 **
52722 ** For the purposes of this routine, a write-cursor is any cursor that
52723 ** is capable of writing to the databse.  That means the cursor was
52724 ** originally opened for writing and the cursor has not be disabled
52725 ** by having its state changed to CURSOR_FAULT.
52726 */
52727 static int countWriteCursors(BtShared *pBt){
52728   BtCursor *pCur;
52729   int r = 0;
52730   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
52731     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
52732   }
52733   return r;
52734 }
52735 #endif
52736
52737 /*
52738 ** This routine sets the state to CURSOR_FAULT and the error
52739 ** code to errCode for every cursor on BtShared that pBtree
52740 ** references.
52741 **
52742 ** Every cursor is tripped, including cursors that belong
52743 ** to other database connections that happen to be sharing
52744 ** the cache with pBtree.
52745 **
52746 ** This routine gets called when a rollback occurs.
52747 ** All cursors using the same cache must be tripped
52748 ** to prevent them from trying to use the btree after
52749 ** the rollback.  The rollback may have deleted tables
52750 ** or moved root pages, so it is not sufficient to
52751 ** save the state of the cursor.  The cursor must be
52752 ** invalidated.
52753 */
52754 SQLCIPHER_PRIVATE void sqlcipher3BtreeTripAllCursors(Btree *pBtree, int errCode){
52755   BtCursor *p;
52756   sqlcipher3BtreeEnter(pBtree);
52757   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
52758     int i;
52759     sqlcipher3BtreeClearCursor(p);
52760     p->eState = CURSOR_FAULT;
52761     p->skipNext = errCode;
52762     for(i=0; i<=p->iPage; i++){
52763       releasePage(p->apPage[i]);
52764       p->apPage[i] = 0;
52765     }
52766   }
52767   sqlcipher3BtreeLeave(pBtree);
52768 }
52769
52770 /*
52771 ** Rollback the transaction in progress.  All cursors will be
52772 ** invalided by this operation.  Any attempt to use a cursor
52773 ** that was open at the beginning of this operation will result
52774 ** in an error.
52775 **
52776 ** This will release the write lock on the database file.  If there
52777 ** are no active cursors, it also releases the read lock.
52778 */
52779 SQLCIPHER_PRIVATE int sqlcipher3BtreeRollback(Btree *p){
52780   int rc;
52781   BtShared *pBt = p->pBt;
52782   MemPage *pPage1;
52783
52784   sqlcipher3BtreeEnter(p);
52785   rc = saveAllCursors(pBt, 0, 0);
52786 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
52787   if( rc!=SQLCIPHER_OK ){
52788     /* This is a horrible situation. An IO or malloc() error occurred whilst
52789     ** trying to save cursor positions. If this is an automatic rollback (as
52790     ** the result of a constraint, malloc() failure or IO error) then 
52791     ** the cache may be internally inconsistent (not contain valid trees) so
52792     ** we cannot simply return the error to the caller. Instead, abort 
52793     ** all queries that may be using any of the cursors that failed to save.
52794     */
52795     sqlcipher3BtreeTripAllCursors(p, rc);
52796   }
52797 #endif
52798   btreeIntegrity(p);
52799
52800   if( p->inTrans==TRANS_WRITE ){
52801     int rc2;
52802
52803     assert( TRANS_WRITE==pBt->inTransaction );
52804     rc2 = sqlcipher3PagerRollback(pBt->pPager);
52805     if( rc2!=SQLCIPHER_OK ){
52806       rc = rc2;
52807     }
52808
52809     /* The rollback may have destroyed the pPage1->aData value.  So
52810     ** call btreeGetPage() on page 1 again to make
52811     ** sure pPage1->aData is set correctly. */
52812     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLCIPHER_OK ){
52813       int nPage = get4byte(28+(u8*)pPage1->aData);
52814       testcase( nPage==0 );
52815       if( nPage==0 ) sqlcipher3PagerPagecount(pBt->pPager, &nPage);
52816       testcase( pBt->nPage!=nPage );
52817       pBt->nPage = nPage;
52818       releasePage(pPage1);
52819     }
52820     assert( countWriteCursors(pBt)==0 );
52821     pBt->inTransaction = TRANS_READ;
52822   }
52823
52824   btreeEndTransaction(p);
52825   sqlcipher3BtreeLeave(p);
52826   return rc;
52827 }
52828
52829 /*
52830 ** Start a statement subtransaction. The subtransaction can can be rolled
52831 ** back independently of the main transaction. You must start a transaction 
52832 ** before starting a subtransaction. The subtransaction is ended automatically 
52833 ** if the main transaction commits or rolls back.
52834 **
52835 ** Statement subtransactions are used around individual SQL statements
52836 ** that are contained within a BEGIN...COMMIT block.  If a constraint
52837 ** error occurs within the statement, the effect of that one statement
52838 ** can be rolled back without having to rollback the entire transaction.
52839 **
52840 ** A statement sub-transaction is implemented as an anonymous savepoint. The
52841 ** value passed as the second parameter is the total number of savepoints,
52842 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
52843 ** are no active savepoints and no other statement-transactions open,
52844 ** iStatement is 1. This anonymous savepoint can be released or rolled back
52845 ** using the sqlcipher3BtreeSavepoint() function.
52846 */
52847 SQLCIPHER_PRIVATE int sqlcipher3BtreeBeginStmt(Btree *p, int iStatement){
52848   int rc;
52849   BtShared *pBt = p->pBt;
52850   sqlcipher3BtreeEnter(p);
52851   assert( p->inTrans==TRANS_WRITE );
52852   assert( pBt->readOnly==0 );
52853   assert( iStatement>0 );
52854   assert( iStatement>p->db->nSavepoint );
52855   assert( pBt->inTransaction==TRANS_WRITE );
52856   /* At the pager level, a statement transaction is a savepoint with
52857   ** an index greater than all savepoints created explicitly using
52858   ** SQL statements. It is illegal to open, release or rollback any
52859   ** such savepoints while the statement transaction savepoint is active.
52860   */
52861   rc = sqlcipher3PagerOpenSavepoint(pBt->pPager, iStatement);
52862   sqlcipher3BtreeLeave(p);
52863   return rc;
52864 }
52865
52866 /*
52867 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
52868 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
52869 ** savepoint identified by parameter iSavepoint, depending on the value 
52870 ** of op.
52871 **
52872 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
52873 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
52874 ** contents of the entire transaction are rolled back. This is different
52875 ** from a normal transaction rollback, as no locks are released and the
52876 ** transaction remains open.
52877 */
52878 SQLCIPHER_PRIVATE int sqlcipher3BtreeSavepoint(Btree *p, int op, int iSavepoint){
52879   int rc = SQLCIPHER_OK;
52880   if( p && p->inTrans==TRANS_WRITE ){
52881     BtShared *pBt = p->pBt;
52882     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
52883     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
52884     sqlcipher3BtreeEnter(p);
52885     rc = sqlcipher3PagerSavepoint(pBt->pPager, op, iSavepoint);
52886     if( rc==SQLCIPHER_OK ){
52887       if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
52888       rc = newDatabase(pBt);
52889       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
52890
52891       /* The database size was written into the offset 28 of the header
52892       ** when the transaction started, so we know that the value at offset
52893       ** 28 is nonzero. */
52894       assert( pBt->nPage>0 );
52895     }
52896     sqlcipher3BtreeLeave(p);
52897   }
52898   return rc;
52899 }
52900
52901 /*
52902 ** Create a new cursor for the BTree whose root is on the page
52903 ** iTable. If a read-only cursor is requested, it is assumed that
52904 ** the caller already has at least a read-only transaction open
52905 ** on the database already. If a write-cursor is requested, then
52906 ** the caller is assumed to have an open write transaction.
52907 **
52908 ** If wrFlag==0, then the cursor can only be used for reading.
52909 ** If wrFlag==1, then the cursor can be used for reading or for
52910 ** writing if other conditions for writing are also met.  These
52911 ** are the conditions that must be met in order for writing to
52912 ** be allowed:
52913 **
52914 ** 1:  The cursor must have been opened with wrFlag==1
52915 **
52916 ** 2:  Other database connections that share the same pager cache
52917 **     but which are not in the READ_UNCOMMITTED state may not have
52918 **     cursors open with wrFlag==0 on the same table.  Otherwise
52919 **     the changes made by this write cursor would be visible to
52920 **     the read cursors in the other database connection.
52921 **
52922 ** 3:  The database must be writable (not on read-only media)
52923 **
52924 ** 4:  There must be an active transaction.
52925 **
52926 ** No checking is done to make sure that page iTable really is the
52927 ** root page of a b-tree.  If it is not, then the cursor acquired
52928 ** will not work correctly.
52929 **
52930 ** It is assumed that the sqlcipher3BtreeCursorZero() has been called
52931 ** on pCur to initialize the memory space prior to invoking this routine.
52932 */
52933 static int btreeCursor(
52934   Btree *p,                              /* The btree */
52935   int iTable,                            /* Root page of table to open */
52936   int wrFlag,                            /* 1 to write. 0 read-only */
52937   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
52938   BtCursor *pCur                         /* Space for new cursor */
52939 ){
52940   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
52941
52942   assert( sqlcipher3BtreeHoldsMutex(p) );
52943   assert( wrFlag==0 || wrFlag==1 );
52944
52945   /* The following assert statements verify that if this is a sharable 
52946   ** b-tree database, the connection is holding the required table locks, 
52947   ** and that no other connection has any open cursor that conflicts with 
52948   ** this lock.  */
52949   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
52950   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
52951
52952   /* Assert that the caller has opened the required transaction. */
52953   assert( p->inTrans>TRANS_NONE );
52954   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
52955   assert( pBt->pPage1 && pBt->pPage1->aData );
52956
52957   if( NEVER(wrFlag && pBt->readOnly) ){
52958     return SQLCIPHER_READONLY;
52959   }
52960   if( iTable==1 && btreePagecount(pBt)==0 ){
52961     assert( wrFlag==0 );
52962     iTable = 0;
52963   }
52964
52965   /* Now that no other errors can occur, finish filling in the BtCursor
52966   ** variables and link the cursor into the BtShared list.  */
52967   pCur->pgnoRoot = (Pgno)iTable;
52968   pCur->iPage = -1;
52969   pCur->pKeyInfo = pKeyInfo;
52970   pCur->pBtree = p;
52971   pCur->pBt = pBt;
52972   pCur->wrFlag = (u8)wrFlag;
52973   pCur->pNext = pBt->pCursor;
52974   if( pCur->pNext ){
52975     pCur->pNext->pPrev = pCur;
52976   }
52977   pBt->pCursor = pCur;
52978   pCur->eState = CURSOR_INVALID;
52979   pCur->cachedRowid = 0;
52980   return SQLCIPHER_OK;
52981 }
52982 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursor(
52983   Btree *p,                                   /* The btree */
52984   int iTable,                                 /* Root page of table to open */
52985   int wrFlag,                                 /* 1 to write. 0 read-only */
52986   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
52987   BtCursor *pCur                              /* Write new cursor here */
52988 ){
52989   int rc;
52990   sqlcipher3BtreeEnter(p);
52991   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
52992   sqlcipher3BtreeLeave(p);
52993   return rc;
52994 }
52995
52996 /*
52997 ** Return the size of a BtCursor object in bytes.
52998 **
52999 ** This interfaces is needed so that users of cursors can preallocate
53000 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
53001 ** to users so they cannot do the sizeof() themselves - they must call
53002 ** this routine.
53003 */
53004 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorSize(void){
53005   return ROUND8(sizeof(BtCursor));
53006 }
53007
53008 /*
53009 ** Initialize memory that will be converted into a BtCursor object.
53010 **
53011 ** The simple approach here would be to memset() the entire object
53012 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
53013 ** do not need to be zeroed and they are large, so we can save a lot
53014 ** of run-time by skipping the initialization of those elements.
53015 */
53016 SQLCIPHER_PRIVATE void sqlcipher3BtreeCursorZero(BtCursor *p){
53017   memset(p, 0, offsetof(BtCursor, iPage));
53018 }
53019
53020 /*
53021 ** Set the cached rowid value of every cursor in the same database file
53022 ** as pCur and having the same root page number as pCur.  The value is
53023 ** set to iRowid.
53024 **
53025 ** Only positive rowid values are considered valid for this cache.
53026 ** The cache is initialized to zero, indicating an invalid cache.
53027 ** A btree will work fine with zero or negative rowids.  We just cannot
53028 ** cache zero or negative rowids, which means tables that use zero or
53029 ** negative rowids might run a little slower.  But in practice, zero
53030 ** or negative rowids are very uncommon so this should not be a problem.
53031 */
53032 SQLCIPHER_PRIVATE void sqlcipher3BtreeSetCachedRowid(BtCursor *pCur, sqlcipher3_int64 iRowid){
53033   BtCursor *p;
53034   for(p=pCur->pBt->pCursor; p; p=p->pNext){
53035     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
53036   }
53037   assert( pCur->cachedRowid==iRowid );
53038 }
53039
53040 /*
53041 ** Return the cached rowid for the given cursor.  A negative or zero
53042 ** return value indicates that the rowid cache is invalid and should be
53043 ** ignored.  If the rowid cache has never before been set, then a
53044 ** zero is returned.
53045 */
53046 SQLCIPHER_PRIVATE sqlcipher3_int64 sqlcipher3BtreeGetCachedRowid(BtCursor *pCur){
53047   return pCur->cachedRowid;
53048 }
53049
53050 /*
53051 ** Close a cursor.  The read lock on the database file is released
53052 ** when the last cursor is closed.
53053 */
53054 SQLCIPHER_PRIVATE int sqlcipher3BtreeCloseCursor(BtCursor *pCur){
53055   Btree *pBtree = pCur->pBtree;
53056   if( pBtree ){
53057     int i;
53058     BtShared *pBt = pCur->pBt;
53059     sqlcipher3BtreeEnter(pBtree);
53060     sqlcipher3BtreeClearCursor(pCur);
53061     if( pCur->pPrev ){
53062       pCur->pPrev->pNext = pCur->pNext;
53063     }else{
53064       pBt->pCursor = pCur->pNext;
53065     }
53066     if( pCur->pNext ){
53067       pCur->pNext->pPrev = pCur->pPrev;
53068     }
53069     for(i=0; i<=pCur->iPage; i++){
53070       releasePage(pCur->apPage[i]);
53071     }
53072     unlockBtreeIfUnused(pBt);
53073     invalidateOverflowCache(pCur);
53074     /* sqlcipher3_free(pCur); */
53075     sqlcipher3BtreeLeave(pBtree);
53076   }
53077   return SQLCIPHER_OK;
53078 }
53079
53080 /*
53081 ** Make sure the BtCursor* given in the argument has a valid
53082 ** BtCursor.info structure.  If it is not already valid, call
53083 ** btreeParseCell() to fill it in.
53084 **
53085 ** BtCursor.info is a cache of the information in the current cell.
53086 ** Using this cache reduces the number of calls to btreeParseCell().
53087 **
53088 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
53089 ** compiler to crash when getCellInfo() is implemented as a macro.
53090 ** But there is a measureable speed advantage to using the macro on gcc
53091 ** (when less compiler optimizations like -Os or -O0 are used and the
53092 ** compiler is not doing agressive inlining.)  So we use a real function
53093 ** for MSVC and a macro for everything else.  Ticket #2457.
53094 */
53095 #ifndef NDEBUG
53096   static void assertCellInfo(BtCursor *pCur){
53097     CellInfo info;
53098     int iPage = pCur->iPage;
53099     memset(&info, 0, sizeof(info));
53100     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
53101     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
53102   }
53103 #else
53104   #define assertCellInfo(x)
53105 #endif
53106 #ifdef _MSC_VER
53107   /* Use a real function in MSVC to work around bugs in that compiler. */
53108   static void getCellInfo(BtCursor *pCur){
53109     if( pCur->info.nSize==0 ){
53110       int iPage = pCur->iPage;
53111       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
53112       pCur->validNKey = 1;
53113     }else{
53114       assertCellInfo(pCur);
53115     }
53116   }
53117 #else /* if not _MSC_VER */
53118   /* Use a macro in all other compilers so that the function is inlined */
53119 #define getCellInfo(pCur)                                                      \
53120   if( pCur->info.nSize==0 ){                                                   \
53121     int iPage = pCur->iPage;                                                   \
53122     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
53123     pCur->validNKey = 1;                                                       \
53124   }else{                                                                       \
53125     assertCellInfo(pCur);                                                      \
53126   }
53127 #endif /* _MSC_VER */
53128
53129 #ifndef NDEBUG  /* The next routine used only within assert() statements */
53130 /*
53131 ** Return true if the given BtCursor is valid.  A valid cursor is one
53132 ** that is currently pointing to a row in a (non-empty) table.
53133 ** This is a verification routine is used only within assert() statements.
53134 */
53135 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorIsValid(BtCursor *pCur){
53136   return pCur && pCur->eState==CURSOR_VALID;
53137 }
53138 #endif /* NDEBUG */
53139
53140 /*
53141 ** Set *pSize to the size of the buffer needed to hold the value of
53142 ** the key for the current entry.  If the cursor is not pointing
53143 ** to a valid entry, *pSize is set to 0. 
53144 **
53145 ** For a table with the INTKEY flag set, this routine returns the key
53146 ** itself, not the number of bytes in the key.
53147 **
53148 ** The caller must position the cursor prior to invoking this routine.
53149 ** 
53150 ** This routine cannot fail.  It always returns SQLCIPHER_OK.  
53151 */
53152 SQLCIPHER_PRIVATE int sqlcipher3BtreeKeySize(BtCursor *pCur, i64 *pSize){
53153   assert( cursorHoldsMutex(pCur) );
53154   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
53155   if( pCur->eState!=CURSOR_VALID ){
53156     *pSize = 0;
53157   }else{
53158     getCellInfo(pCur);
53159     *pSize = pCur->info.nKey;
53160   }
53161   return SQLCIPHER_OK;
53162 }
53163
53164 /*
53165 ** Set *pSize to the number of bytes of data in the entry the
53166 ** cursor currently points to.
53167 **
53168 ** The caller must guarantee that the cursor is pointing to a non-NULL
53169 ** valid entry.  In other words, the calling procedure must guarantee
53170 ** that the cursor has Cursor.eState==CURSOR_VALID.
53171 **
53172 ** Failure is not possible.  This function always returns SQLCIPHER_OK.
53173 ** It might just as well be a procedure (returning void) but we continue
53174 ** to return an integer result code for historical reasons.
53175 */
53176 SQLCIPHER_PRIVATE int sqlcipher3BtreeDataSize(BtCursor *pCur, u32 *pSize){
53177   assert( cursorHoldsMutex(pCur) );
53178   assert( pCur->eState==CURSOR_VALID );
53179   getCellInfo(pCur);
53180   *pSize = pCur->info.nData;
53181   return SQLCIPHER_OK;
53182 }
53183
53184 /*
53185 ** Given the page number of an overflow page in the database (parameter
53186 ** ovfl), this function finds the page number of the next page in the 
53187 ** linked list of overflow pages. If possible, it uses the auto-vacuum
53188 ** pointer-map data instead of reading the content of page ovfl to do so. 
53189 **
53190 ** If an error occurs an SQLite error code is returned. Otherwise:
53191 **
53192 ** The page number of the next overflow page in the linked list is 
53193 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
53194 ** list, *pPgnoNext is set to zero. 
53195 **
53196 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
53197 ** to page number pOvfl was obtained, then *ppPage is set to point to that
53198 ** reference. It is the responsibility of the caller to call releasePage()
53199 ** on *ppPage to free the reference. In no reference was obtained (because
53200 ** the pointer-map was used to obtain the value for *pPgnoNext), then
53201 ** *ppPage is set to zero.
53202 */
53203 static int getOverflowPage(
53204   BtShared *pBt,               /* The database file */
53205   Pgno ovfl,                   /* Current overflow page number */
53206   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
53207   Pgno *pPgnoNext              /* OUT: Next overflow page number */
53208 ){
53209   Pgno next = 0;
53210   MemPage *pPage = 0;
53211   int rc = SQLCIPHER_OK;
53212
53213   assert( sqlcipher3_mutex_held(pBt->mutex) );
53214   assert(pPgnoNext);
53215
53216 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
53217   /* Try to find the next page in the overflow list using the
53218   ** autovacuum pointer-map pages. Guess that the next page in 
53219   ** the overflow list is page number (ovfl+1). If that guess turns 
53220   ** out to be wrong, fall back to loading the data of page 
53221   ** number ovfl to determine the next page number.
53222   */
53223   if( pBt->autoVacuum ){
53224     Pgno pgno;
53225     Pgno iGuess = ovfl+1;
53226     u8 eType;
53227
53228     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
53229       iGuess++;
53230     }
53231
53232     if( iGuess<=btreePagecount(pBt) ){
53233       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
53234       if( rc==SQLCIPHER_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
53235         next = iGuess;
53236         rc = SQLCIPHER_DONE;
53237       }
53238     }
53239   }
53240 #endif
53241
53242   assert( next==0 || rc==SQLCIPHER_DONE );
53243   if( rc==SQLCIPHER_OK ){
53244     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
53245     assert( rc==SQLCIPHER_OK || pPage==0 );
53246     if( rc==SQLCIPHER_OK ){
53247       next = get4byte(pPage->aData);
53248     }
53249   }
53250
53251   *pPgnoNext = next;
53252   if( ppPage ){
53253     *ppPage = pPage;
53254   }else{
53255     releasePage(pPage);
53256   }
53257   return (rc==SQLCIPHER_DONE ? SQLCIPHER_OK : rc);
53258 }
53259
53260 /*
53261 ** Copy data from a buffer to a page, or from a page to a buffer.
53262 **
53263 ** pPayload is a pointer to data stored on database page pDbPage.
53264 ** If argument eOp is false, then nByte bytes of data are copied
53265 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
53266 ** then sqlcipher3PagerWrite() is called on pDbPage and nByte bytes
53267 ** of data are copied from the buffer pBuf to pPayload.
53268 **
53269 ** SQLCIPHER_OK is returned on success, otherwise an error code.
53270 */
53271 static int copyPayload(
53272   void *pPayload,           /* Pointer to page data */
53273   void *pBuf,               /* Pointer to buffer */
53274   int nByte,                /* Number of bytes to copy */
53275   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
53276   DbPage *pDbPage           /* Page containing pPayload */
53277 ){
53278   if( eOp ){
53279     /* Copy data from buffer to page (a write operation) */
53280     int rc = sqlcipher3PagerWrite(pDbPage);
53281     if( rc!=SQLCIPHER_OK ){
53282       return rc;
53283     }
53284     memcpy(pPayload, pBuf, nByte);
53285   }else{
53286     /* Copy data from page to buffer (a read operation) */
53287     memcpy(pBuf, pPayload, nByte);
53288   }
53289   return SQLCIPHER_OK;
53290 }
53291
53292 /*
53293 ** This function is used to read or overwrite payload information
53294 ** for the entry that the pCur cursor is pointing to. If the eOp
53295 ** parameter is 0, this is a read operation (data copied into
53296 ** buffer pBuf). If it is non-zero, a write (data copied from
53297 ** buffer pBuf).
53298 **
53299 ** A total of "amt" bytes are read or written beginning at "offset".
53300 ** Data is read to or from the buffer pBuf.
53301 **
53302 ** The content being read or written might appear on the main page
53303 ** or be scattered out on multiple overflow pages.
53304 **
53305 ** If the BtCursor.isIncrblobHandle flag is set, and the current
53306 ** cursor entry uses one or more overflow pages, this function
53307 ** allocates space for and lazily popluates the overflow page-list 
53308 ** cache array (BtCursor.aOverflow). Subsequent calls use this
53309 ** cache to make seeking to the supplied offset more efficient.
53310 **
53311 ** Once an overflow page-list cache has been allocated, it may be
53312 ** invalidated if some other cursor writes to the same table, or if
53313 ** the cursor is moved to a different row. Additionally, in auto-vacuum
53314 ** mode, the following events may invalidate an overflow page-list cache.
53315 **
53316 **   * An incremental vacuum,
53317 **   * A commit in auto_vacuum="full" mode,
53318 **   * Creating a table (may require moving an overflow page).
53319 */
53320 static int accessPayload(
53321   BtCursor *pCur,      /* Cursor pointing to entry to read from */
53322   u32 offset,          /* Begin reading this far into payload */
53323   u32 amt,             /* Read this many bytes */
53324   unsigned char *pBuf, /* Write the bytes into this buffer */ 
53325   int eOp              /* zero to read. non-zero to write. */
53326 ){
53327   unsigned char *aPayload;
53328   int rc = SQLCIPHER_OK;
53329   u32 nKey;
53330   int iIdx = 0;
53331   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
53332   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
53333
53334   assert( pPage );
53335   assert( pCur->eState==CURSOR_VALID );
53336   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53337   assert( cursorHoldsMutex(pCur) );
53338
53339   getCellInfo(pCur);
53340   aPayload = pCur->info.pCell + pCur->info.nHeader;
53341   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
53342
53343   if( NEVER(offset+amt > nKey+pCur->info.nData) 
53344    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
53345   ){
53346     /* Trying to read or write past the end of the data is an error */
53347     return SQLCIPHER_CORRUPT_BKPT;
53348   }
53349
53350   /* Check if data must be read/written to/from the btree page itself. */
53351   if( offset<pCur->info.nLocal ){
53352     int a = amt;
53353     if( a+offset>pCur->info.nLocal ){
53354       a = pCur->info.nLocal - offset;
53355     }
53356     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
53357     offset = 0;
53358     pBuf += a;
53359     amt -= a;
53360   }else{
53361     offset -= pCur->info.nLocal;
53362   }
53363
53364   if( rc==SQLCIPHER_OK && amt>0 ){
53365     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
53366     Pgno nextPage;
53367
53368     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
53369
53370 #ifndef SQLCIPHER_OMIT_INCRBLOB
53371     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
53372     ** has not been allocated, allocate it now. The array is sized at
53373     ** one entry for each overflow page in the overflow chain. The
53374     ** page number of the first overflow page is stored in aOverflow[0],
53375     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
53376     ** (the cache is lazily populated).
53377     */
53378     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
53379       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
53380       pCur->aOverflow = (Pgno *)sqlcipher3MallocZero(sizeof(Pgno)*nOvfl);
53381       /* nOvfl is always positive.  If it were zero, fetchPayload would have
53382       ** been used instead of this routine. */
53383       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
53384         rc = SQLCIPHER_NOMEM;
53385       }
53386     }
53387
53388     /* If the overflow page-list cache has been allocated and the
53389     ** entry for the first required overflow page is valid, skip
53390     ** directly to it.
53391     */
53392     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
53393       iIdx = (offset/ovflSize);
53394       nextPage = pCur->aOverflow[iIdx];
53395       offset = (offset%ovflSize);
53396     }
53397 #endif
53398
53399     for( ; rc==SQLCIPHER_OK && amt>0 && nextPage; iIdx++){
53400
53401 #ifndef SQLCIPHER_OMIT_INCRBLOB
53402       /* If required, populate the overflow page-list cache. */
53403       if( pCur->aOverflow ){
53404         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
53405         pCur->aOverflow[iIdx] = nextPage;
53406       }
53407 #endif
53408
53409       if( offset>=ovflSize ){
53410         /* The only reason to read this page is to obtain the page
53411         ** number for the next page in the overflow chain. The page
53412         ** data is not required. So first try to lookup the overflow
53413         ** page-list cache, if any, then fall back to the getOverflowPage()
53414         ** function.
53415         */
53416 #ifndef SQLCIPHER_OMIT_INCRBLOB
53417         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
53418           nextPage = pCur->aOverflow[iIdx+1];
53419         } else 
53420 #endif
53421           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
53422         offset -= ovflSize;
53423       }else{
53424         /* Need to read this page properly. It contains some of the
53425         ** range of data that is being read (eOp==0) or written (eOp!=0).
53426         */
53427 #ifdef SQLCIPHER_DIRECT_OVERFLOW_READ
53428         sqlcipher3_file *fd;
53429 #endif
53430         int a = amt;
53431         if( a + offset > ovflSize ){
53432           a = ovflSize - offset;
53433         }
53434
53435 #ifdef SQLCIPHER_DIRECT_OVERFLOW_READ
53436         /* If all the following are true:
53437         **
53438         **   1) this is a read operation, and 
53439         **   2) data is required from the start of this overflow page, and
53440         **   3) the database is file-backed, and
53441         **   4) there is no open write-transaction, and
53442         **   5) the database is not a WAL database,
53443         **
53444         ** then data can be read directly from the database file into the
53445         ** output buffer, bypassing the page-cache altogether. This speeds
53446         ** up loading large records that span many overflow pages.
53447         */
53448         if( eOp==0                                             /* (1) */
53449          && offset==0                                          /* (2) */
53450          && pBt->inTransaction==TRANS_READ                     /* (4) */
53451          && (fd = sqlcipher3PagerFile(pBt->pPager))->pMethods     /* (3) */
53452          && pBt->pPage1->aData[19]==0x01                       /* (5) */
53453         ){
53454           u8 aSave[4];
53455           u8 *aWrite = &pBuf[-4];
53456           memcpy(aSave, aWrite, 4);
53457           rc = sqlcipher3OsRead(fd, aWrite, a+4, pBt->pageSize * (nextPage-1));
53458           nextPage = get4byte(aWrite);
53459           memcpy(aWrite, aSave, 4);
53460         }else
53461 #endif
53462
53463         {
53464           DbPage *pDbPage;
53465           rc = sqlcipher3PagerGet(pBt->pPager, nextPage, &pDbPage);
53466           if( rc==SQLCIPHER_OK ){
53467             aPayload = sqlcipher3PagerGetData(pDbPage);
53468             nextPage = get4byte(aPayload);
53469             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
53470             sqlcipher3PagerUnref(pDbPage);
53471             offset = 0;
53472           }
53473         }
53474         amt -= a;
53475         pBuf += a;
53476       }
53477     }
53478   }
53479
53480   if( rc==SQLCIPHER_OK && amt>0 ){
53481     return SQLCIPHER_CORRUPT_BKPT;
53482   }
53483   return rc;
53484 }
53485
53486 /*
53487 ** Read part of the key associated with cursor pCur.  Exactly
53488 ** "amt" bytes will be transfered into pBuf[].  The transfer
53489 ** begins at "offset".
53490 **
53491 ** The caller must ensure that pCur is pointing to a valid row
53492 ** in the table.
53493 **
53494 ** Return SQLCIPHER_OK on success or an error code if anything goes
53495 ** wrong.  An error is returned if "offset+amt" is larger than
53496 ** the available payload.
53497 */
53498 SQLCIPHER_PRIVATE int sqlcipher3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53499   assert( cursorHoldsMutex(pCur) );
53500   assert( pCur->eState==CURSOR_VALID );
53501   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53502   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53503   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
53504 }
53505
53506 /*
53507 ** Read part of the data associated with cursor pCur.  Exactly
53508 ** "amt" bytes will be transfered into pBuf[].  The transfer
53509 ** begins at "offset".
53510 **
53511 ** Return SQLCIPHER_OK on success or an error code if anything goes
53512 ** wrong.  An error is returned if "offset+amt" is larger than
53513 ** the available payload.
53514 */
53515 SQLCIPHER_PRIVATE int sqlcipher3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53516   int rc;
53517
53518 #ifndef SQLCIPHER_OMIT_INCRBLOB
53519   if ( pCur->eState==CURSOR_INVALID ){
53520     return SQLCIPHER_ABORT;
53521   }
53522 #endif
53523
53524   assert( cursorHoldsMutex(pCur) );
53525   rc = restoreCursorPosition(pCur);
53526   if( rc==SQLCIPHER_OK ){
53527     assert( pCur->eState==CURSOR_VALID );
53528     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53529     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53530     rc = accessPayload(pCur, offset, amt, pBuf, 0);
53531   }
53532   return rc;
53533 }
53534
53535 /*
53536 ** Return a pointer to payload information from the entry that the 
53537 ** pCur cursor is pointing to.  The pointer is to the beginning of
53538 ** the key if skipKey==0 and it points to the beginning of data if
53539 ** skipKey==1.  The number of bytes of available key/data is written
53540 ** into *pAmt.  If *pAmt==0, then the value returned will not be
53541 ** a valid pointer.
53542 **
53543 ** This routine is an optimization.  It is common for the entire key
53544 ** and data to fit on the local page and for there to be no overflow
53545 ** pages.  When that is so, this routine can be used to access the
53546 ** key and data without making a copy.  If the key and/or data spills
53547 ** onto overflow pages, then accessPayload() must be used to reassemble
53548 ** the key/data and copy it into a preallocated buffer.
53549 **
53550 ** The pointer returned by this routine looks directly into the cached
53551 ** page of the database.  The data might change or move the next time
53552 ** any btree routine is called.
53553 */
53554 static const unsigned char *fetchPayload(
53555   BtCursor *pCur,      /* Cursor pointing to entry to read from */
53556   int *pAmt,           /* Write the number of available bytes here */
53557   int skipKey          /* read beginning at data if this is true */
53558 ){
53559   unsigned char *aPayload;
53560   MemPage *pPage;
53561   u32 nKey;
53562   u32 nLocal;
53563
53564   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
53565   assert( pCur->eState==CURSOR_VALID );
53566   assert( cursorHoldsMutex(pCur) );
53567   pPage = pCur->apPage[pCur->iPage];
53568   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53569   if( NEVER(pCur->info.nSize==0) ){
53570     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
53571                    &pCur->info);
53572   }
53573   aPayload = pCur->info.pCell;
53574   aPayload += pCur->info.nHeader;
53575   if( pPage->intKey ){
53576     nKey = 0;
53577   }else{
53578     nKey = (int)pCur->info.nKey;
53579   }
53580   if( skipKey ){
53581     aPayload += nKey;
53582     nLocal = pCur->info.nLocal - nKey;
53583   }else{
53584     nLocal = pCur->info.nLocal;
53585     assert( nLocal<=nKey );
53586   }
53587   *pAmt = nLocal;
53588   return aPayload;
53589 }
53590
53591
53592 /*
53593 ** For the entry that cursor pCur is point to, return as
53594 ** many bytes of the key or data as are available on the local
53595 ** b-tree page.  Write the number of available bytes into *pAmt.
53596 **
53597 ** The pointer returned is ephemeral.  The key/data may move
53598 ** or be destroyed on the next call to any Btree routine,
53599 ** including calls from other threads against the same cache.
53600 ** Hence, a mutex on the BtShared should be held prior to calling
53601 ** this routine.
53602 **
53603 ** These routines is used to get quick access to key and data
53604 ** in the common case where no overflow pages are used.
53605 */
53606 SQLCIPHER_PRIVATE const void *sqlcipher3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
53607   const void *p = 0;
53608   assert( sqlcipher3_mutex_held(pCur->pBtree->db->mutex) );
53609   assert( cursorHoldsMutex(pCur) );
53610   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53611     p = (const void*)fetchPayload(pCur, pAmt, 0);
53612   }
53613   return p;
53614 }
53615 SQLCIPHER_PRIVATE const void *sqlcipher3BtreeDataFetch(BtCursor *pCur, int *pAmt){
53616   const void *p = 0;
53617   assert( sqlcipher3_mutex_held(pCur->pBtree->db->mutex) );
53618   assert( cursorHoldsMutex(pCur) );
53619   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53620     p = (const void*)fetchPayload(pCur, pAmt, 1);
53621   }
53622   return p;
53623 }
53624
53625
53626 /*
53627 ** Move the cursor down to a new child page.  The newPgno argument is the
53628 ** page number of the child page to move to.
53629 **
53630 ** This function returns SQLCIPHER_CORRUPT if the page-header flags field of
53631 ** the new child page does not match the flags field of the parent (i.e.
53632 ** if an intkey page appears to be the parent of a non-intkey page, or
53633 ** vice-versa).
53634 */
53635 static int moveToChild(BtCursor *pCur, u32 newPgno){
53636   int rc;
53637   int i = pCur->iPage;
53638   MemPage *pNewPage;
53639   BtShared *pBt = pCur->pBt;
53640
53641   assert( cursorHoldsMutex(pCur) );
53642   assert( pCur->eState==CURSOR_VALID );
53643   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
53644   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
53645     return SQLCIPHER_CORRUPT_BKPT;
53646   }
53647   rc = getAndInitPage(pBt, newPgno, &pNewPage);
53648   if( rc ) return rc;
53649   pCur->apPage[i+1] = pNewPage;
53650   pCur->aiIdx[i+1] = 0;
53651   pCur->iPage++;
53652
53653   pCur->info.nSize = 0;
53654   pCur->validNKey = 0;
53655   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
53656     return SQLCIPHER_CORRUPT_BKPT;
53657   }
53658   return SQLCIPHER_OK;
53659 }
53660
53661 #ifndef NDEBUG
53662 /*
53663 ** Page pParent is an internal (non-leaf) tree page. This function 
53664 ** asserts that page number iChild is the left-child if the iIdx'th
53665 ** cell in page pParent. Or, if iIdx is equal to the total number of
53666 ** cells in pParent, that page number iChild is the right-child of
53667 ** the page.
53668 */
53669 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
53670   assert( iIdx<=pParent->nCell );
53671   if( iIdx==pParent->nCell ){
53672     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
53673   }else{
53674     assert( get4byte(findCell(pParent, iIdx))==iChild );
53675   }
53676 }
53677 #else
53678 #  define assertParentIndex(x,y,z) 
53679 #endif
53680
53681 /*
53682 ** Move the cursor up to the parent page.
53683 **
53684 ** pCur->idx is set to the cell index that contains the pointer
53685 ** to the page we are coming from.  If we are coming from the
53686 ** right-most child page then pCur->idx is set to one more than
53687 ** the largest cell index.
53688 */
53689 static void moveToParent(BtCursor *pCur){
53690   assert( cursorHoldsMutex(pCur) );
53691   assert( pCur->eState==CURSOR_VALID );
53692   assert( pCur->iPage>0 );
53693   assert( pCur->apPage[pCur->iPage] );
53694   assertParentIndex(
53695     pCur->apPage[pCur->iPage-1], 
53696     pCur->aiIdx[pCur->iPage-1], 
53697     pCur->apPage[pCur->iPage]->pgno
53698   );
53699   releasePage(pCur->apPage[pCur->iPage]);
53700   pCur->iPage--;
53701   pCur->info.nSize = 0;
53702   pCur->validNKey = 0;
53703 }
53704
53705 /*
53706 ** Move the cursor to point to the root page of its b-tree structure.
53707 **
53708 ** If the table has a virtual root page, then the cursor is moved to point
53709 ** to the virtual root page instead of the actual root page. A table has a
53710 ** virtual root page when the actual root page contains no cells and a 
53711 ** single child page. This can only happen with the table rooted at page 1.
53712 **
53713 ** If the b-tree structure is empty, the cursor state is set to 
53714 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
53715 ** cell located on the root (or virtual root) page and the cursor state
53716 ** is set to CURSOR_VALID.
53717 **
53718 ** If this function returns successfully, it may be assumed that the
53719 ** page-header flags indicate that the [virtual] root-page is the expected 
53720 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
53721 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
53722 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
53723 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
53724 ** b-tree).
53725 */
53726 static int moveToRoot(BtCursor *pCur){
53727   MemPage *pRoot;
53728   int rc = SQLCIPHER_OK;
53729   Btree *p = pCur->pBtree;
53730   BtShared *pBt = p->pBt;
53731
53732   assert( cursorHoldsMutex(pCur) );
53733   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
53734   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
53735   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
53736   if( pCur->eState>=CURSOR_REQUIRESEEK ){
53737     if( pCur->eState==CURSOR_FAULT ){
53738       assert( pCur->skipNext!=SQLCIPHER_OK );
53739       return pCur->skipNext;
53740     }
53741     sqlcipher3BtreeClearCursor(pCur);
53742   }
53743
53744   if( pCur->iPage>=0 ){
53745     int i;
53746     for(i=1; i<=pCur->iPage; i++){
53747       releasePage(pCur->apPage[i]);
53748     }
53749     pCur->iPage = 0;
53750   }else if( pCur->pgnoRoot==0 ){
53751     pCur->eState = CURSOR_INVALID;
53752     return SQLCIPHER_OK;
53753   }else{
53754     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
53755     if( rc!=SQLCIPHER_OK ){
53756       pCur->eState = CURSOR_INVALID;
53757       return rc;
53758     }
53759     pCur->iPage = 0;
53760
53761     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
53762     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
53763     ** NULL, the caller expects a table b-tree. If this is not the case,
53764     ** return an SQLCIPHER_CORRUPT error.  */
53765     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
53766     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
53767       return SQLCIPHER_CORRUPT_BKPT;
53768     }
53769   }
53770
53771   /* Assert that the root page is of the correct type. This must be the
53772   ** case as the call to this function that loaded the root-page (either
53773   ** this call or a previous invocation) would have detected corruption 
53774   ** if the assumption were not true, and it is not possible for the flags 
53775   ** byte to have been modified while this cursor is holding a reference
53776   ** to the page.  */
53777   pRoot = pCur->apPage[0];
53778   assert( pRoot->pgno==pCur->pgnoRoot );
53779   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
53780
53781   pCur->aiIdx[0] = 0;
53782   pCur->info.nSize = 0;
53783   pCur->atLast = 0;
53784   pCur->validNKey = 0;
53785
53786   if( pRoot->nCell==0 && !pRoot->leaf ){
53787     Pgno subpage;
53788     if( pRoot->pgno!=1 ) return SQLCIPHER_CORRUPT_BKPT;
53789     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
53790     pCur->eState = CURSOR_VALID;
53791     rc = moveToChild(pCur, subpage);
53792   }else{
53793     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
53794   }
53795   return rc;
53796 }
53797
53798 /*
53799 ** Move the cursor down to the left-most leaf entry beneath the
53800 ** entry to which it is currently pointing.
53801 **
53802 ** The left-most leaf is the one with the smallest key - the first
53803 ** in ascending order.
53804 */
53805 static int moveToLeftmost(BtCursor *pCur){
53806   Pgno pgno;
53807   int rc = SQLCIPHER_OK;
53808   MemPage *pPage;
53809
53810   assert( cursorHoldsMutex(pCur) );
53811   assert( pCur->eState==CURSOR_VALID );
53812   while( rc==SQLCIPHER_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
53813     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53814     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
53815     rc = moveToChild(pCur, pgno);
53816   }
53817   return rc;
53818 }
53819
53820 /*
53821 ** Move the cursor down to the right-most leaf entry beneath the
53822 ** page to which it is currently pointing.  Notice the difference
53823 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
53824 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
53825 ** finds the right-most entry beneath the *page*.
53826 **
53827 ** The right-most entry is the one with the largest key - the last
53828 ** key in ascending order.
53829 */
53830 static int moveToRightmost(BtCursor *pCur){
53831   Pgno pgno;
53832   int rc = SQLCIPHER_OK;
53833   MemPage *pPage = 0;
53834
53835   assert( cursorHoldsMutex(pCur) );
53836   assert( pCur->eState==CURSOR_VALID );
53837   while( rc==SQLCIPHER_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
53838     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
53839     pCur->aiIdx[pCur->iPage] = pPage->nCell;
53840     rc = moveToChild(pCur, pgno);
53841   }
53842   if( rc==SQLCIPHER_OK ){
53843     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
53844     pCur->info.nSize = 0;
53845     pCur->validNKey = 0;
53846   }
53847   return rc;
53848 }
53849
53850 /* Move the cursor to the first entry in the table.  Return SQLCIPHER_OK
53851 ** on success.  Set *pRes to 0 if the cursor actually points to something
53852 ** or set *pRes to 1 if the table is empty.
53853 */
53854 SQLCIPHER_PRIVATE int sqlcipher3BtreeFirst(BtCursor *pCur, int *pRes){
53855   int rc;
53856
53857   assert( cursorHoldsMutex(pCur) );
53858   assert( sqlcipher3_mutex_held(pCur->pBtree->db->mutex) );
53859   rc = moveToRoot(pCur);
53860   if( rc==SQLCIPHER_OK ){
53861     if( pCur->eState==CURSOR_INVALID ){
53862       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
53863       *pRes = 1;
53864     }else{
53865       assert( pCur->apPage[pCur->iPage]->nCell>0 );
53866       *pRes = 0;
53867       rc = moveToLeftmost(pCur);
53868     }
53869   }
53870   return rc;
53871 }
53872
53873 /* Move the cursor to the last entry in the table.  Return SQLCIPHER_OK
53874 ** on success.  Set *pRes to 0 if the cursor actually points to something
53875 ** or set *pRes to 1 if the table is empty.
53876 */
53877 SQLCIPHER_PRIVATE int sqlcipher3BtreeLast(BtCursor *pCur, int *pRes){
53878   int rc;
53879  
53880   assert( cursorHoldsMutex(pCur) );
53881   assert( sqlcipher3_mutex_held(pCur->pBtree->db->mutex) );
53882
53883   /* If the cursor already points to the last entry, this is a no-op. */
53884   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
53885 #ifdef SQLCIPHER_DEBUG
53886     /* This block serves to assert() that the cursor really does point 
53887     ** to the last entry in the b-tree. */
53888     int ii;
53889     for(ii=0; ii<pCur->iPage; ii++){
53890       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
53891     }
53892     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
53893     assert( pCur->apPage[pCur->iPage]->leaf );
53894 #endif
53895     return SQLCIPHER_OK;
53896   }
53897
53898   rc = moveToRoot(pCur);
53899   if( rc==SQLCIPHER_OK ){
53900     if( CURSOR_INVALID==pCur->eState ){
53901       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
53902       *pRes = 1;
53903     }else{
53904       assert( pCur->eState==CURSOR_VALID );
53905       *pRes = 0;
53906       rc = moveToRightmost(pCur);
53907       pCur->atLast = rc==SQLCIPHER_OK ?1:0;
53908     }
53909   }
53910   return rc;
53911 }
53912
53913 /* Move the cursor so that it points to an entry near the key 
53914 ** specified by pIdxKey or intKey.   Return a success code.
53915 **
53916 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
53917 ** must be NULL.  For index tables, pIdxKey is used and intKey
53918 ** is ignored.
53919 **
53920 ** If an exact match is not found, then the cursor is always
53921 ** left pointing at a leaf page which would hold the entry if it
53922 ** were present.  The cursor might point to an entry that comes
53923 ** before or after the key.
53924 **
53925 ** An integer is written into *pRes which is the result of
53926 ** comparing the key with the entry to which the cursor is 
53927 ** pointing.  The meaning of the integer written into
53928 ** *pRes is as follows:
53929 **
53930 **     *pRes<0      The cursor is left pointing at an entry that
53931 **                  is smaller than intKey/pIdxKey or if the table is empty
53932 **                  and the cursor is therefore left point to nothing.
53933 **
53934 **     *pRes==0     The cursor is left pointing at an entry that
53935 **                  exactly matches intKey/pIdxKey.
53936 **
53937 **     *pRes>0      The cursor is left pointing at an entry that
53938 **                  is larger than intKey/pIdxKey.
53939 **
53940 */
53941 SQLCIPHER_PRIVATE int sqlcipher3BtreeMovetoUnpacked(
53942   BtCursor *pCur,          /* The cursor to be moved */
53943   UnpackedRecord *pIdxKey, /* Unpacked index key */
53944   i64 intKey,              /* The table key */
53945   int biasRight,           /* If true, bias the search to the high end */
53946   int *pRes                /* Write search results here */
53947 ){
53948   int rc;
53949
53950   assert( cursorHoldsMutex(pCur) );
53951   assert( sqlcipher3_mutex_held(pCur->pBtree->db->mutex) );
53952   assert( pRes );
53953   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
53954
53955   /* If the cursor is already positioned at the point we are trying
53956   ** to move to, then just return without doing any work */
53957   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
53958    && pCur->apPage[0]->intKey 
53959   ){
53960     if( pCur->info.nKey==intKey ){
53961       *pRes = 0;
53962       return SQLCIPHER_OK;
53963     }
53964     if( pCur->atLast && pCur->info.nKey<intKey ){
53965       *pRes = -1;
53966       return SQLCIPHER_OK;
53967     }
53968   }
53969
53970   rc = moveToRoot(pCur);
53971   if( rc ){
53972     return rc;
53973   }
53974   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
53975   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
53976   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
53977   if( pCur->eState==CURSOR_INVALID ){
53978     *pRes = -1;
53979     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
53980     return SQLCIPHER_OK;
53981   }
53982   assert( pCur->apPage[0]->intKey || pIdxKey );
53983   for(;;){
53984     int lwr, upr, idx;
53985     Pgno chldPg;
53986     MemPage *pPage = pCur->apPage[pCur->iPage];
53987     int c;
53988
53989     /* pPage->nCell must be greater than zero. If this is the root-page
53990     ** the cursor would have been INVALID above and this for(;;) loop
53991     ** not run. If this is not the root-page, then the moveToChild() routine
53992     ** would have already detected db corruption. Similarly, pPage must
53993     ** be the right kind (index or table) of b-tree page. Otherwise
53994     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
53995     assert( pPage->nCell>0 );
53996     assert( pPage->intKey==(pIdxKey==0) );
53997     lwr = 0;
53998     upr = pPage->nCell-1;
53999     if( biasRight ){
54000       pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
54001     }else{
54002       pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
54003     }
54004     for(;;){
54005       u8 *pCell;                          /* Pointer to current cell in pPage */
54006
54007       assert( idx==pCur->aiIdx[pCur->iPage] );
54008       pCur->info.nSize = 0;
54009       pCell = findCell(pPage, idx) + pPage->childPtrSize;
54010       if( pPage->intKey ){
54011         i64 nCellKey;
54012         if( pPage->hasData ){
54013           u32 dummy;
54014           pCell += getVarint32(pCell, dummy);
54015         }
54016         getVarint(pCell, (u64*)&nCellKey);
54017         if( nCellKey==intKey ){
54018           c = 0;
54019         }else if( nCellKey<intKey ){
54020           c = -1;
54021         }else{
54022           assert( nCellKey>intKey );
54023           c = +1;
54024         }
54025         pCur->validNKey = 1;
54026         pCur->info.nKey = nCellKey;
54027       }else{
54028         /* The maximum supported page-size is 65536 bytes. This means that
54029         ** the maximum number of record bytes stored on an index B-Tree
54030         ** page is less than 16384 bytes and may be stored as a 2-byte
54031         ** varint. This information is used to attempt to avoid parsing 
54032         ** the entire cell by checking for the cases where the record is 
54033         ** stored entirely within the b-tree page by inspecting the first 
54034         ** 2 bytes of the cell.
54035         */
54036         int nCell = pCell[0];
54037         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
54038           /* This branch runs if the record-size field of the cell is a
54039           ** single byte varint and the record fits entirely on the main
54040           ** b-tree page.  */
54041           c = sqlcipher3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
54042         }else if( !(pCell[1] & 0x80) 
54043           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
54044         ){
54045           /* The record-size field is a 2 byte varint and the record 
54046           ** fits entirely on the main b-tree page.  */
54047           c = sqlcipher3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
54048         }else{
54049           /* The record flows over onto one or more overflow pages. In
54050           ** this case the whole cell needs to be parsed, a buffer allocated
54051           ** and accessPayload() used to retrieve the record into the
54052           ** buffer before VdbeRecordCompare() can be called. */
54053           void *pCellKey;
54054           u8 * const pCellBody = pCell - pPage->childPtrSize;
54055           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
54056           nCell = (int)pCur->info.nKey;
54057           pCellKey = sqlcipher3Malloc( nCell );
54058           if( pCellKey==0 ){
54059             rc = SQLCIPHER_NOMEM;
54060             goto moveto_finish;
54061           }
54062           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
54063           if( rc ){
54064             sqlcipher3_free(pCellKey);
54065             goto moveto_finish;
54066           }
54067           c = sqlcipher3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
54068           sqlcipher3_free(pCellKey);
54069         }
54070       }
54071       if( c==0 ){
54072         if( pPage->intKey && !pPage->leaf ){
54073           lwr = idx;
54074           break;
54075         }else{
54076           *pRes = 0;
54077           rc = SQLCIPHER_OK;
54078           goto moveto_finish;
54079         }
54080       }
54081       if( c<0 ){
54082         lwr = idx+1;
54083       }else{
54084         upr = idx-1;
54085       }
54086       if( lwr>upr ){
54087         break;
54088       }
54089       pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
54090     }
54091     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
54092     assert( pPage->isInit );
54093     if( pPage->leaf ){
54094       chldPg = 0;
54095     }else if( lwr>=pPage->nCell ){
54096       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54097     }else{
54098       chldPg = get4byte(findCell(pPage, lwr));
54099     }
54100     if( chldPg==0 ){
54101       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54102       *pRes = c;
54103       rc = SQLCIPHER_OK;
54104       goto moveto_finish;
54105     }
54106     pCur->aiIdx[pCur->iPage] = (u16)lwr;
54107     pCur->info.nSize = 0;
54108     pCur->validNKey = 0;
54109     rc = moveToChild(pCur, chldPg);
54110     if( rc ) goto moveto_finish;
54111   }
54112 moveto_finish:
54113   return rc;
54114 }
54115
54116
54117 /*
54118 ** Return TRUE if the cursor is not pointing at an entry of the table.
54119 **
54120 ** TRUE will be returned after a call to sqlcipher3BtreeNext() moves
54121 ** past the last entry in the table or sqlcipher3BtreePrev() moves past
54122 ** the first entry.  TRUE is also returned if the table is empty.
54123 */
54124 SQLCIPHER_PRIVATE int sqlcipher3BtreeEof(BtCursor *pCur){
54125   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
54126   ** have been deleted? This API will need to change to return an error code
54127   ** as well as the boolean result value.
54128   */
54129   return (CURSOR_VALID!=pCur->eState);
54130 }
54131
54132 /*
54133 ** Advance the cursor to the next entry in the database.  If
54134 ** successful then set *pRes=0.  If the cursor
54135 ** was already pointing to the last entry in the database before
54136 ** this routine was called, then set *pRes=1.
54137 */
54138 SQLCIPHER_PRIVATE int sqlcipher3BtreeNext(BtCursor *pCur, int *pRes){
54139   int rc;
54140   int idx;
54141   MemPage *pPage;
54142
54143   assert( cursorHoldsMutex(pCur) );
54144   rc = restoreCursorPosition(pCur);
54145   if( rc!=SQLCIPHER_OK ){
54146     return rc;
54147   }
54148   assert( pRes!=0 );
54149   if( CURSOR_INVALID==pCur->eState ){
54150     *pRes = 1;
54151     return SQLCIPHER_OK;
54152   }
54153   if( pCur->skipNext>0 ){
54154     pCur->skipNext = 0;
54155     *pRes = 0;
54156     return SQLCIPHER_OK;
54157   }
54158   pCur->skipNext = 0;
54159
54160   pPage = pCur->apPage[pCur->iPage];
54161   idx = ++pCur->aiIdx[pCur->iPage];
54162   assert( pPage->isInit );
54163   assert( idx<=pPage->nCell );
54164
54165   pCur->info.nSize = 0;
54166   pCur->validNKey = 0;
54167   if( idx>=pPage->nCell ){
54168     if( !pPage->leaf ){
54169       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54170       if( rc ) return rc;
54171       rc = moveToLeftmost(pCur);
54172       *pRes = 0;
54173       return rc;
54174     }
54175     do{
54176       if( pCur->iPage==0 ){
54177         *pRes = 1;
54178         pCur->eState = CURSOR_INVALID;
54179         return SQLCIPHER_OK;
54180       }
54181       moveToParent(pCur);
54182       pPage = pCur->apPage[pCur->iPage];
54183     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
54184     *pRes = 0;
54185     if( pPage->intKey ){
54186       rc = sqlcipher3BtreeNext(pCur, pRes);
54187     }else{
54188       rc = SQLCIPHER_OK;
54189     }
54190     return rc;
54191   }
54192   *pRes = 0;
54193   if( pPage->leaf ){
54194     return SQLCIPHER_OK;
54195   }
54196   rc = moveToLeftmost(pCur);
54197   return rc;
54198 }
54199
54200
54201 /*
54202 ** Step the cursor to the back to the previous entry in the database.  If
54203 ** successful then set *pRes=0.  If the cursor
54204 ** was already pointing to the first entry in the database before
54205 ** this routine was called, then set *pRes=1.
54206 */
54207 SQLCIPHER_PRIVATE int sqlcipher3BtreePrevious(BtCursor *pCur, int *pRes){
54208   int rc;
54209   MemPage *pPage;
54210
54211   assert( cursorHoldsMutex(pCur) );
54212   rc = restoreCursorPosition(pCur);
54213   if( rc!=SQLCIPHER_OK ){
54214     return rc;
54215   }
54216   pCur->atLast = 0;
54217   if( CURSOR_INVALID==pCur->eState ){
54218     *pRes = 1;
54219     return SQLCIPHER_OK;
54220   }
54221   if( pCur->skipNext<0 ){
54222     pCur->skipNext = 0;
54223     *pRes = 0;
54224     return SQLCIPHER_OK;
54225   }
54226   pCur->skipNext = 0;
54227
54228   pPage = pCur->apPage[pCur->iPage];
54229   assert( pPage->isInit );
54230   if( !pPage->leaf ){
54231     int idx = pCur->aiIdx[pCur->iPage];
54232     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
54233     if( rc ){
54234       return rc;
54235     }
54236     rc = moveToRightmost(pCur);
54237   }else{
54238     while( pCur->aiIdx[pCur->iPage]==0 ){
54239       if( pCur->iPage==0 ){
54240         pCur->eState = CURSOR_INVALID;
54241         *pRes = 1;
54242         return SQLCIPHER_OK;
54243       }
54244       moveToParent(pCur);
54245     }
54246     pCur->info.nSize = 0;
54247     pCur->validNKey = 0;
54248
54249     pCur->aiIdx[pCur->iPage]--;
54250     pPage = pCur->apPage[pCur->iPage];
54251     if( pPage->intKey && !pPage->leaf ){
54252       rc = sqlcipher3BtreePrevious(pCur, pRes);
54253     }else{
54254       rc = SQLCIPHER_OK;
54255     }
54256   }
54257   *pRes = 0;
54258   return rc;
54259 }
54260
54261 /*
54262 ** Allocate a new page from the database file.
54263 **
54264 ** The new page is marked as dirty.  (In other words, sqlcipher3PagerWrite()
54265 ** has already been called on the new page.)  The new page has also
54266 ** been referenced and the calling routine is responsible for calling
54267 ** sqlcipher3PagerUnref() on the new page when it is done.
54268 **
54269 ** SQLCIPHER_OK is returned on success.  Any other return value indicates
54270 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
54271 ** Do not invoke sqlcipher3PagerUnref() on *ppPage if an error is returned.
54272 **
54273 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
54274 ** locate a page close to the page number "nearby".  This can be used in an
54275 ** attempt to keep related pages close to each other in the database file,
54276 ** which in turn can make database access faster.
54277 **
54278 ** If the "exact" parameter is not 0, and the page-number nearby exists 
54279 ** anywhere on the free-list, then it is guarenteed to be returned. This
54280 ** is only used by auto-vacuum databases when allocating a new table.
54281 */
54282 static int allocateBtreePage(
54283   BtShared *pBt, 
54284   MemPage **ppPage, 
54285   Pgno *pPgno, 
54286   Pgno nearby,
54287   u8 exact
54288 ){
54289   MemPage *pPage1;
54290   int rc;
54291   u32 n;     /* Number of pages on the freelist */
54292   u32 k;     /* Number of leaves on the trunk of the freelist */
54293   MemPage *pTrunk = 0;
54294   MemPage *pPrevTrunk = 0;
54295   Pgno mxPage;     /* Total size of the database file */
54296
54297   assert( sqlcipher3_mutex_held(pBt->mutex) );
54298   pPage1 = pBt->pPage1;
54299   mxPage = btreePagecount(pBt);
54300   n = get4byte(&pPage1->aData[36]);
54301   testcase( n==mxPage-1 );
54302   if( n>=mxPage ){
54303     return SQLCIPHER_CORRUPT_BKPT;
54304   }
54305   if( n>0 ){
54306     /* There are pages on the freelist.  Reuse one of those pages. */
54307     Pgno iTrunk;
54308     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
54309     
54310     /* If the 'exact' parameter was true and a query of the pointer-map
54311     ** shows that the page 'nearby' is somewhere on the free-list, then
54312     ** the entire-list will be searched for that page.
54313     */
54314 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
54315     if( exact && nearby<=mxPage ){
54316       u8 eType;
54317       assert( nearby>0 );
54318       assert( pBt->autoVacuum );
54319       rc = ptrmapGet(pBt, nearby, &eType, 0);
54320       if( rc ) return rc;
54321       if( eType==PTRMAP_FREEPAGE ){
54322         searchList = 1;
54323       }
54324       *pPgno = nearby;
54325     }
54326 #endif
54327
54328     /* Decrement the free-list count by 1. Set iTrunk to the index of the
54329     ** first free-list trunk page. iPrevTrunk is initially 1.
54330     */
54331     rc = sqlcipher3PagerWrite(pPage1->pDbPage);
54332     if( rc ) return rc;
54333     put4byte(&pPage1->aData[36], n-1);
54334
54335     /* The code within this loop is run only once if the 'searchList' variable
54336     ** is not true. Otherwise, it runs once for each trunk-page on the
54337     ** free-list until the page 'nearby' is located.
54338     */
54339     do {
54340       pPrevTrunk = pTrunk;
54341       if( pPrevTrunk ){
54342         iTrunk = get4byte(&pPrevTrunk->aData[0]);
54343       }else{
54344         iTrunk = get4byte(&pPage1->aData[32]);
54345       }
54346       testcase( iTrunk==mxPage );
54347       if( iTrunk>mxPage ){
54348         rc = SQLCIPHER_CORRUPT_BKPT;
54349       }else{
54350         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
54351       }
54352       if( rc ){
54353         pTrunk = 0;
54354         goto end_allocate_page;
54355       }
54356       assert( pTrunk!=0 );
54357       assert( pTrunk->aData!=0 );
54358
54359       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
54360       if( k==0 && !searchList ){
54361         /* The trunk has no leaves and the list is not being searched. 
54362         ** So extract the trunk page itself and use it as the newly 
54363         ** allocated page */
54364         assert( pPrevTrunk==0 );
54365         rc = sqlcipher3PagerWrite(pTrunk->pDbPage);
54366         if( rc ){
54367           goto end_allocate_page;
54368         }
54369         *pPgno = iTrunk;
54370         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54371         *ppPage = pTrunk;
54372         pTrunk = 0;
54373         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54374       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
54375         /* Value of k is out of range.  Database corruption */
54376         rc = SQLCIPHER_CORRUPT_BKPT;
54377         goto end_allocate_page;
54378 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
54379       }else if( searchList && nearby==iTrunk ){
54380         /* The list is being searched and this trunk page is the page
54381         ** to allocate, regardless of whether it has leaves.
54382         */
54383         assert( *pPgno==iTrunk );
54384         *ppPage = pTrunk;
54385         searchList = 0;
54386         rc = sqlcipher3PagerWrite(pTrunk->pDbPage);
54387         if( rc ){
54388           goto end_allocate_page;
54389         }
54390         if( k==0 ){
54391           if( !pPrevTrunk ){
54392             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54393           }else{
54394             rc = sqlcipher3PagerWrite(pPrevTrunk->pDbPage);
54395             if( rc!=SQLCIPHER_OK ){
54396               goto end_allocate_page;
54397             }
54398             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
54399           }
54400         }else{
54401           /* The trunk page is required by the caller but it contains 
54402           ** pointers to free-list leaves. The first leaf becomes a trunk
54403           ** page in this case.
54404           */
54405           MemPage *pNewTrunk;
54406           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
54407           if( iNewTrunk>mxPage ){ 
54408             rc = SQLCIPHER_CORRUPT_BKPT;
54409             goto end_allocate_page;
54410           }
54411           testcase( iNewTrunk==mxPage );
54412           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
54413           if( rc!=SQLCIPHER_OK ){
54414             goto end_allocate_page;
54415           }
54416           rc = sqlcipher3PagerWrite(pNewTrunk->pDbPage);
54417           if( rc!=SQLCIPHER_OK ){
54418             releasePage(pNewTrunk);
54419             goto end_allocate_page;
54420           }
54421           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
54422           put4byte(&pNewTrunk->aData[4], k-1);
54423           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
54424           releasePage(pNewTrunk);
54425           if( !pPrevTrunk ){
54426             assert( sqlcipher3PagerIswriteable(pPage1->pDbPage) );
54427             put4byte(&pPage1->aData[32], iNewTrunk);
54428           }else{
54429             rc = sqlcipher3PagerWrite(pPrevTrunk->pDbPage);
54430             if( rc ){
54431               goto end_allocate_page;
54432             }
54433             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
54434           }
54435         }
54436         pTrunk = 0;
54437         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54438 #endif
54439       }else if( k>0 ){
54440         /* Extract a leaf from the trunk */
54441         u32 closest;
54442         Pgno iPage;
54443         unsigned char *aData = pTrunk->aData;
54444         if( nearby>0 ){
54445           u32 i;
54446           int dist;
54447           closest = 0;
54448           dist = sqlcipher3AbsInt32(get4byte(&aData[8]) - nearby);
54449           for(i=1; i<k; i++){
54450             int d2 = sqlcipher3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
54451             if( d2<dist ){
54452               closest = i;
54453               dist = d2;
54454             }
54455           }
54456         }else{
54457           closest = 0;
54458         }
54459
54460         iPage = get4byte(&aData[8+closest*4]);
54461         testcase( iPage==mxPage );
54462         if( iPage>mxPage ){
54463           rc = SQLCIPHER_CORRUPT_BKPT;
54464           goto end_allocate_page;
54465         }
54466         testcase( iPage==mxPage );
54467         if( !searchList || iPage==nearby ){
54468           int noContent;
54469           *pPgno = iPage;
54470           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
54471                  ": %d more free pages\n",
54472                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
54473           rc = sqlcipher3PagerWrite(pTrunk->pDbPage);
54474           if( rc ) goto end_allocate_page;
54475           if( closest<k-1 ){
54476             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
54477           }
54478           put4byte(&aData[4], k-1);
54479           noContent = !btreeGetHasContent(pBt, *pPgno);
54480           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
54481           if( rc==SQLCIPHER_OK ){
54482             rc = sqlcipher3PagerWrite((*ppPage)->pDbPage);
54483             if( rc!=SQLCIPHER_OK ){
54484               releasePage(*ppPage);
54485             }
54486           }
54487           searchList = 0;
54488         }
54489       }
54490       releasePage(pPrevTrunk);
54491       pPrevTrunk = 0;
54492     }while( searchList );
54493   }else{
54494     /* There are no pages on the freelist, so create a new page at the
54495     ** end of the file */
54496     rc = sqlcipher3PagerWrite(pBt->pPage1->pDbPage);
54497     if( rc ) return rc;
54498     pBt->nPage++;
54499     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
54500
54501 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
54502     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
54503       /* If *pPgno refers to a pointer-map page, allocate two new pages
54504       ** at the end of the file instead of one. The first allocated page
54505       ** becomes a new pointer-map page, the second is used by the caller.
54506       */
54507       MemPage *pPg = 0;
54508       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
54509       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
54510       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
54511       if( rc==SQLCIPHER_OK ){
54512         rc = sqlcipher3PagerWrite(pPg->pDbPage);
54513         releasePage(pPg);
54514       }
54515       if( rc ) return rc;
54516       pBt->nPage++;
54517       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
54518     }
54519 #endif
54520     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
54521     *pPgno = pBt->nPage;
54522
54523     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54524     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
54525     if( rc ) return rc;
54526     rc = sqlcipher3PagerWrite((*ppPage)->pDbPage);
54527     if( rc!=SQLCIPHER_OK ){
54528       releasePage(*ppPage);
54529     }
54530     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
54531   }
54532
54533   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54534
54535 end_allocate_page:
54536   releasePage(pTrunk);
54537   releasePage(pPrevTrunk);
54538   if( rc==SQLCIPHER_OK ){
54539     if( sqlcipher3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
54540       releasePage(*ppPage);
54541       return SQLCIPHER_CORRUPT_BKPT;
54542     }
54543     (*ppPage)->isInit = 0;
54544   }else{
54545     *ppPage = 0;
54546   }
54547   assert( rc!=SQLCIPHER_OK || sqlcipher3PagerIswriteable((*ppPage)->pDbPage) );
54548   return rc;
54549 }
54550
54551 /*
54552 ** This function is used to add page iPage to the database file free-list. 
54553 ** It is assumed that the page is not already a part of the free-list.
54554 **
54555 ** The value passed as the second argument to this function is optional.
54556 ** If the caller happens to have a pointer to the MemPage object 
54557 ** corresponding to page iPage handy, it may pass it as the second value. 
54558 ** Otherwise, it may pass NULL.
54559 **
54560 ** If a pointer to a MemPage object is passed as the second argument,
54561 ** its reference count is not altered by this function.
54562 */
54563 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
54564   MemPage *pTrunk = 0;                /* Free-list trunk page */
54565   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
54566   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
54567   MemPage *pPage;                     /* Page being freed. May be NULL. */
54568   int rc;                             /* Return Code */
54569   int nFree;                          /* Initial number of pages on free-list */
54570
54571   assert( sqlcipher3_mutex_held(pBt->mutex) );
54572   assert( iPage>1 );
54573   assert( !pMemPage || pMemPage->pgno==iPage );
54574
54575   if( pMemPage ){
54576     pPage = pMemPage;
54577     sqlcipher3PagerRef(pPage->pDbPage);
54578   }else{
54579     pPage = btreePageLookup(pBt, iPage);
54580   }
54581
54582   /* Increment the free page count on pPage1 */
54583   rc = sqlcipher3PagerWrite(pPage1->pDbPage);
54584   if( rc ) goto freepage_out;
54585   nFree = get4byte(&pPage1->aData[36]);
54586   put4byte(&pPage1->aData[36], nFree+1);
54587
54588   if( pBt->secureDelete ){
54589     /* If the secure_delete option is enabled, then
54590     ** always fully overwrite deleted information with zeros.
54591     */
54592     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
54593      ||            ((rc = sqlcipher3PagerWrite(pPage->pDbPage))!=0)
54594     ){
54595       goto freepage_out;
54596     }
54597     memset(pPage->aData, 0, pPage->pBt->pageSize);
54598   }
54599
54600   /* If the database supports auto-vacuum, write an entry in the pointer-map
54601   ** to indicate that the page is free.
54602   */
54603   if( ISAUTOVACUUM ){
54604     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
54605     if( rc ) goto freepage_out;
54606   }
54607
54608   /* Now manipulate the actual database free-list structure. There are two
54609   ** possibilities. If the free-list is currently empty, or if the first
54610   ** trunk page in the free-list is full, then this page will become a
54611   ** new free-list trunk page. Otherwise, it will become a leaf of the
54612   ** first trunk page in the current free-list. This block tests if it
54613   ** is possible to add the page as a new free-list leaf.
54614   */
54615   if( nFree!=0 ){
54616     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
54617
54618     iTrunk = get4byte(&pPage1->aData[32]);
54619     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
54620     if( rc!=SQLCIPHER_OK ){
54621       goto freepage_out;
54622     }
54623
54624     nLeaf = get4byte(&pTrunk->aData[4]);
54625     assert( pBt->usableSize>32 );
54626     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
54627       rc = SQLCIPHER_CORRUPT_BKPT;
54628       goto freepage_out;
54629     }
54630     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
54631       /* In this case there is room on the trunk page to insert the page
54632       ** being freed as a new leaf.
54633       **
54634       ** Note that the trunk page is not really full until it contains
54635       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
54636       ** coded.  But due to a coding error in versions of SQLite prior to
54637       ** 3.6.0, databases with freelist trunk pages holding more than
54638       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
54639       ** to maintain backwards compatibility with older versions of SQLite,
54640       ** we will continue to restrict the number of entries to usableSize/4 - 8
54641       ** for now.  At some point in the future (once everyone has upgraded
54642       ** to 3.6.0 or later) we should consider fixing the conditional above
54643       ** to read "usableSize/4-2" instead of "usableSize/4-8".
54644       */
54645       rc = sqlcipher3PagerWrite(pTrunk->pDbPage);
54646       if( rc==SQLCIPHER_OK ){
54647         put4byte(&pTrunk->aData[4], nLeaf+1);
54648         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
54649         if( pPage && !pBt->secureDelete ){
54650           sqlcipher3PagerDontWrite(pPage->pDbPage);
54651         }
54652         rc = btreeSetHasContent(pBt, iPage);
54653       }
54654       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
54655       goto freepage_out;
54656     }
54657   }
54658
54659   /* If control flows to this point, then it was not possible to add the
54660   ** the page being freed as a leaf page of the first trunk in the free-list.
54661   ** Possibly because the free-list is empty, or possibly because the 
54662   ** first trunk in the free-list is full. Either way, the page being freed
54663   ** will become the new first trunk page in the free-list.
54664   */
54665   if( pPage==0 && SQLCIPHER_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
54666     goto freepage_out;
54667   }
54668   rc = sqlcipher3PagerWrite(pPage->pDbPage);
54669   if( rc!=SQLCIPHER_OK ){
54670     goto freepage_out;
54671   }
54672   put4byte(pPage->aData, iTrunk);
54673   put4byte(&pPage->aData[4], 0);
54674   put4byte(&pPage1->aData[32], iPage);
54675   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
54676
54677 freepage_out:
54678   if( pPage ){
54679     pPage->isInit = 0;
54680   }
54681   releasePage(pPage);
54682   releasePage(pTrunk);
54683   return rc;
54684 }
54685 static void freePage(MemPage *pPage, int *pRC){
54686   if( (*pRC)==SQLCIPHER_OK ){
54687     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
54688   }
54689 }
54690
54691 /*
54692 ** Free any overflow pages associated with the given Cell.
54693 */
54694 static int clearCell(MemPage *pPage, unsigned char *pCell){
54695   BtShared *pBt = pPage->pBt;
54696   CellInfo info;
54697   Pgno ovflPgno;
54698   int rc;
54699   int nOvfl;
54700   u32 ovflPageSize;
54701
54702   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
54703   btreeParseCellPtr(pPage, pCell, &info);
54704   if( info.iOverflow==0 ){
54705     return SQLCIPHER_OK;  /* No overflow pages. Return without doing anything */
54706   }
54707   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
54708     return SQLCIPHER_CORRUPT;  /* Cell extends past end of page */
54709   }
54710   ovflPgno = get4byte(&pCell[info.iOverflow]);
54711   assert( pBt->usableSize > 4 );
54712   ovflPageSize = pBt->usableSize - 4;
54713   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
54714   assert( ovflPgno==0 || nOvfl>0 );
54715   while( nOvfl-- ){
54716     Pgno iNext = 0;
54717     MemPage *pOvfl = 0;
54718     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
54719       /* 0 is not a legal page number and page 1 cannot be an 
54720       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
54721       ** file the database must be corrupt. */
54722       return SQLCIPHER_CORRUPT_BKPT;
54723     }
54724     if( nOvfl ){
54725       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
54726       if( rc ) return rc;
54727     }
54728
54729     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
54730      && sqlcipher3PagerPageRefcount(pOvfl->pDbPage)!=1
54731     ){
54732       /* There is no reason any cursor should have an outstanding reference 
54733       ** to an overflow page belonging to a cell that is being deleted/updated.
54734       ** So if there exists more than one reference to this page, then it 
54735       ** must not really be an overflow page and the database must be corrupt. 
54736       ** It is helpful to detect this before calling freePage2(), as 
54737       ** freePage2() may zero the page contents if secure-delete mode is
54738       ** enabled. If this 'overflow' page happens to be a page that the
54739       ** caller is iterating through or using in some other way, this
54740       ** can be problematic.
54741       */
54742       rc = SQLCIPHER_CORRUPT_BKPT;
54743     }else{
54744       rc = freePage2(pBt, pOvfl, ovflPgno);
54745     }
54746
54747     if( pOvfl ){
54748       sqlcipher3PagerUnref(pOvfl->pDbPage);
54749     }
54750     if( rc ) return rc;
54751     ovflPgno = iNext;
54752   }
54753   return SQLCIPHER_OK;
54754 }
54755
54756 /*
54757 ** Create the byte sequence used to represent a cell on page pPage
54758 ** and write that byte sequence into pCell[].  Overflow pages are
54759 ** allocated and filled in as necessary.  The calling procedure
54760 ** is responsible for making sure sufficient space has been allocated
54761 ** for pCell[].
54762 **
54763 ** Note that pCell does not necessary need to point to the pPage->aData
54764 ** area.  pCell might point to some temporary storage.  The cell will
54765 ** be constructed in this temporary area then copied into pPage->aData
54766 ** later.
54767 */
54768 static int fillInCell(
54769   MemPage *pPage,                /* The page that contains the cell */
54770   unsigned char *pCell,          /* Complete text of the cell */
54771   const void *pKey, i64 nKey,    /* The key */
54772   const void *pData,int nData,   /* The data */
54773   int nZero,                     /* Extra zero bytes to append to pData */
54774   int *pnSize                    /* Write cell size here */
54775 ){
54776   int nPayload;
54777   const u8 *pSrc;
54778   int nSrc, n, rc;
54779   int spaceLeft;
54780   MemPage *pOvfl = 0;
54781   MemPage *pToRelease = 0;
54782   unsigned char *pPrior;
54783   unsigned char *pPayload;
54784   BtShared *pBt = pPage->pBt;
54785   Pgno pgnoOvfl = 0;
54786   int nHeader;
54787   CellInfo info;
54788
54789   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
54790
54791   /* pPage is not necessarily writeable since pCell might be auxiliary
54792   ** buffer space that is separate from the pPage buffer area */
54793   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
54794             || sqlcipher3PagerIswriteable(pPage->pDbPage) );
54795
54796   /* Fill in the header. */
54797   nHeader = 0;
54798   if( !pPage->leaf ){
54799     nHeader += 4;
54800   }
54801   if( pPage->hasData ){
54802     nHeader += putVarint(&pCell[nHeader], nData+nZero);
54803   }else{
54804     nData = nZero = 0;
54805   }
54806   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
54807   btreeParseCellPtr(pPage, pCell, &info);
54808   assert( info.nHeader==nHeader );
54809   assert( info.nKey==nKey );
54810   assert( info.nData==(u32)(nData+nZero) );
54811   
54812   /* Fill in the payload */
54813   nPayload = nData + nZero;
54814   if( pPage->intKey ){
54815     pSrc = pData;
54816     nSrc = nData;
54817     nData = 0;
54818   }else{ 
54819     if( NEVER(nKey>0x7fffffff || pKey==0) ){
54820       return SQLCIPHER_CORRUPT_BKPT;
54821     }
54822     nPayload += (int)nKey;
54823     pSrc = pKey;
54824     nSrc = (int)nKey;
54825   }
54826   *pnSize = info.nSize;
54827   spaceLeft = info.nLocal;
54828   pPayload = &pCell[nHeader];
54829   pPrior = &pCell[info.iOverflow];
54830
54831   while( nPayload>0 ){
54832     if( spaceLeft==0 ){
54833 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
54834       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
54835       if( pBt->autoVacuum ){
54836         do{
54837           pgnoOvfl++;
54838         } while( 
54839           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
54840         );
54841       }
54842 #endif
54843       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
54844 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
54845       /* If the database supports auto-vacuum, and the second or subsequent
54846       ** overflow page is being allocated, add an entry to the pointer-map
54847       ** for that page now. 
54848       **
54849       ** If this is the first overflow page, then write a partial entry 
54850       ** to the pointer-map. If we write nothing to this pointer-map slot,
54851       ** then the optimistic overflow chain processing in clearCell()
54852       ** may misinterpret the uninitialised values and delete the
54853       ** wrong pages from the database.
54854       */
54855       if( pBt->autoVacuum && rc==SQLCIPHER_OK ){
54856         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
54857         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
54858         if( rc ){
54859           releasePage(pOvfl);
54860         }
54861       }
54862 #endif
54863       if( rc ){
54864         releasePage(pToRelease);
54865         return rc;
54866       }
54867
54868       /* If pToRelease is not zero than pPrior points into the data area
54869       ** of pToRelease.  Make sure pToRelease is still writeable. */
54870       assert( pToRelease==0 || sqlcipher3PagerIswriteable(pToRelease->pDbPage) );
54871
54872       /* If pPrior is part of the data area of pPage, then make sure pPage
54873       ** is still writeable */
54874       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
54875             || sqlcipher3PagerIswriteable(pPage->pDbPage) );
54876
54877       put4byte(pPrior, pgnoOvfl);
54878       releasePage(pToRelease);
54879       pToRelease = pOvfl;
54880       pPrior = pOvfl->aData;
54881       put4byte(pPrior, 0);
54882       pPayload = &pOvfl->aData[4];
54883       spaceLeft = pBt->usableSize - 4;
54884     }
54885     n = nPayload;
54886     if( n>spaceLeft ) n = spaceLeft;
54887
54888     /* If pToRelease is not zero than pPayload points into the data area
54889     ** of pToRelease.  Make sure pToRelease is still writeable. */
54890     assert( pToRelease==0 || sqlcipher3PagerIswriteable(pToRelease->pDbPage) );
54891
54892     /* If pPayload is part of the data area of pPage, then make sure pPage
54893     ** is still writeable */
54894     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
54895             || sqlcipher3PagerIswriteable(pPage->pDbPage) );
54896
54897     if( nSrc>0 ){
54898       if( n>nSrc ) n = nSrc;
54899       assert( pSrc );
54900       memcpy(pPayload, pSrc, n);
54901     }else{
54902       memset(pPayload, 0, n);
54903     }
54904     nPayload -= n;
54905     pPayload += n;
54906     pSrc += n;
54907     nSrc -= n;
54908     spaceLeft -= n;
54909     if( nSrc==0 ){
54910       nSrc = nData;
54911       pSrc = pData;
54912     }
54913   }
54914   releasePage(pToRelease);
54915   return SQLCIPHER_OK;
54916 }
54917
54918 /*
54919 ** Remove the i-th cell from pPage.  This routine effects pPage only.
54920 ** The cell content is not freed or deallocated.  It is assumed that
54921 ** the cell content has been copied someplace else.  This routine just
54922 ** removes the reference to the cell from pPage.
54923 **
54924 ** "sz" must be the number of bytes in the cell.
54925 */
54926 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
54927   u32 pc;         /* Offset to cell content of cell being deleted */
54928   u8 *data;       /* pPage->aData */
54929   u8 *ptr;        /* Used to move bytes around within data[] */
54930   u8 *endPtr;     /* End of loop */
54931   int rc;         /* The return code */
54932   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
54933
54934   if( *pRC ) return;
54935
54936   assert( idx>=0 && idx<pPage->nCell );
54937   assert( sz==cellSize(pPage, idx) );
54938   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
54939   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
54940   data = pPage->aData;
54941   ptr = &data[pPage->cellOffset + 2*idx];
54942   pc = get2byte(ptr);
54943   hdr = pPage->hdrOffset;
54944   testcase( pc==get2byte(&data[hdr+5]) );
54945   testcase( pc+sz==pPage->pBt->usableSize );
54946   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
54947     *pRC = SQLCIPHER_CORRUPT_BKPT;
54948     return;
54949   }
54950   rc = freeSpace(pPage, pc, sz);
54951   if( rc ){
54952     *pRC = rc;
54953     return;
54954   }
54955   endPtr = &data[pPage->cellOffset + 2*pPage->nCell - 2];
54956   assert( (SQLCIPHER_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
54957   while( ptr<endPtr ){
54958     *(u16*)ptr = *(u16*)&ptr[2];
54959     ptr += 2;
54960   }
54961   pPage->nCell--;
54962   put2byte(&data[hdr+3], pPage->nCell);
54963   pPage->nFree += 2;
54964 }
54965
54966 /*
54967 ** Insert a new cell on pPage at cell index "i".  pCell points to the
54968 ** content of the cell.
54969 **
54970 ** If the cell content will fit on the page, then put it there.  If it
54971 ** will not fit, then make a copy of the cell content into pTemp if
54972 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
54973 ** in pPage->aOvfl[] and make it point to the cell content (either
54974 ** in pTemp or the original pCell) and also record its index. 
54975 ** Allocating a new entry in pPage->aCell[] implies that 
54976 ** pPage->nOverflow is incremented.
54977 **
54978 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
54979 ** cell. The caller will overwrite them after this function returns. If
54980 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
54981 ** (but pCell+nSkip is always valid).
54982 */
54983 static void insertCell(
54984   MemPage *pPage,   /* Page into which we are copying */
54985   int i,            /* New cell becomes the i-th cell of the page */
54986   u8 *pCell,        /* Content of the new cell */
54987   int sz,           /* Bytes of content in pCell */
54988   u8 *pTemp,        /* Temp storage space for pCell, if needed */
54989   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
54990   int *pRC          /* Read and write return code from here */
54991 ){
54992   int idx = 0;      /* Where to write new cell content in data[] */
54993   int j;            /* Loop counter */
54994   int end;          /* First byte past the last cell pointer in data[] */
54995   int ins;          /* Index in data[] where new cell pointer is inserted */
54996   int cellOffset;   /* Address of first cell pointer in data[] */
54997   u8 *data;         /* The content of the whole page */
54998   u8 *ptr;          /* Used for moving information around in data[] */
54999   u8 *endPtr;       /* End of the loop */
55000
55001   int nSkip = (iChild ? 4 : 0);
55002
55003   if( *pRC ) return;
55004
55005   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
55006   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
55007   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
55008   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
55009   /* The cell should normally be sized correctly.  However, when moving a
55010   ** malformed cell from a leaf page to an interior page, if the cell size
55011   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
55012   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
55013   ** the term after the || in the following assert(). */
55014   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
55015   if( pPage->nOverflow || sz+2>pPage->nFree ){
55016     if( pTemp ){
55017       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
55018       pCell = pTemp;
55019     }
55020     if( iChild ){
55021       put4byte(pCell, iChild);
55022     }
55023     j = pPage->nOverflow++;
55024     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
55025     pPage->aOvfl[j].pCell = pCell;
55026     pPage->aOvfl[j].idx = (u16)i;
55027   }else{
55028     int rc = sqlcipher3PagerWrite(pPage->pDbPage);
55029     if( rc!=SQLCIPHER_OK ){
55030       *pRC = rc;
55031       return;
55032     }
55033     assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
55034     data = pPage->aData;
55035     cellOffset = pPage->cellOffset;
55036     end = cellOffset + 2*pPage->nCell;
55037     ins = cellOffset + 2*i;
55038     rc = allocateSpace(pPage, sz, &idx);
55039     if( rc ){ *pRC = rc; return; }
55040     /* The allocateSpace() routine guarantees the following two properties
55041     ** if it returns success */
55042     assert( idx >= end+2 );
55043     assert( idx+sz <= (int)pPage->pBt->usableSize );
55044     pPage->nCell++;
55045     pPage->nFree -= (u16)(2 + sz);
55046     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
55047     if( iChild ){
55048       put4byte(&data[idx], iChild);
55049     }
55050     ptr = &data[end];
55051     endPtr = &data[ins];
55052     assert( (SQLCIPHER_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
55053     while( ptr>endPtr ){
55054       *(u16*)ptr = *(u16*)&ptr[-2];
55055       ptr -= 2;
55056     }
55057     put2byte(&data[ins], idx);
55058     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
55059 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
55060     if( pPage->pBt->autoVacuum ){
55061       /* The cell may contain a pointer to an overflow page. If so, write
55062       ** the entry for the overflow page into the pointer map.
55063       */
55064       ptrmapPutOvflPtr(pPage, pCell, pRC);
55065     }
55066 #endif
55067   }
55068 }
55069
55070 /*
55071 ** Add a list of cells to a page.  The page should be initially empty.
55072 ** The cells are guaranteed to fit on the page.
55073 */
55074 static void assemblePage(
55075   MemPage *pPage,   /* The page to be assemblied */
55076   int nCell,        /* The number of cells to add to this page */
55077   u8 **apCell,      /* Pointers to cell bodies */
55078   u16 *aSize        /* Sizes of the cells */
55079 ){
55080   int i;            /* Loop counter */
55081   u8 *pCellptr;     /* Address of next cell pointer */
55082   int cellbody;     /* Address of next cell body */
55083   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
55084   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
55085   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
55086
55087   assert( pPage->nOverflow==0 );
55088   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
55089   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
55090             && (int)MX_CELL(pPage->pBt)<=10921);
55091   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
55092
55093   /* Check that the page has just been zeroed by zeroPage() */
55094   assert( pPage->nCell==0 );
55095   assert( get2byteNotZero(&data[hdr+5])==nUsable );
55096
55097   pCellptr = &data[pPage->cellOffset + nCell*2];
55098   cellbody = nUsable;
55099   for(i=nCell-1; i>=0; i--){
55100     u16 sz = aSize[i];
55101     pCellptr -= 2;
55102     cellbody -= sz;
55103     put2byte(pCellptr, cellbody);
55104     memcpy(&data[cellbody], apCell[i], sz);
55105   }
55106   put2byte(&data[hdr+3], nCell);
55107   put2byte(&data[hdr+5], cellbody);
55108   pPage->nFree -= (nCell*2 + nUsable - cellbody);
55109   pPage->nCell = (u16)nCell;
55110 }
55111
55112 /*
55113 ** The following parameters determine how many adjacent pages get involved
55114 ** in a balancing operation.  NN is the number of neighbors on either side
55115 ** of the page that participate in the balancing operation.  NB is the
55116 ** total number of pages that participate, including the target page and
55117 ** NN neighbors on either side.
55118 **
55119 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
55120 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
55121 ** in exchange for a larger degradation in INSERT and UPDATE performance.
55122 ** The value of NN appears to give the best results overall.
55123 */
55124 #define NN 1             /* Number of neighbors on either side of pPage */
55125 #define NB (NN*2+1)      /* Total pages involved in the balance */
55126
55127
55128 #ifndef SQLCIPHER_OMIT_QUICKBALANCE
55129 /*
55130 ** This version of balance() handles the common special case where
55131 ** a new entry is being inserted on the extreme right-end of the
55132 ** tree, in other words, when the new entry will become the largest
55133 ** entry in the tree.
55134 **
55135 ** Instead of trying to balance the 3 right-most leaf pages, just add
55136 ** a new page to the right-hand side and put the one new entry in
55137 ** that page.  This leaves the right side of the tree somewhat
55138 ** unbalanced.  But odds are that we will be inserting new entries
55139 ** at the end soon afterwards so the nearly empty page will quickly
55140 ** fill up.  On average.
55141 **
55142 ** pPage is the leaf page which is the right-most page in the tree.
55143 ** pParent is its parent.  pPage must have a single overflow entry
55144 ** which is also the right-most entry on the page.
55145 **
55146 ** The pSpace buffer is used to store a temporary copy of the divider
55147 ** cell that will be inserted into pParent. Such a cell consists of a 4
55148 ** byte page number followed by a variable length integer. In other
55149 ** words, at most 13 bytes. Hence the pSpace buffer must be at
55150 ** least 13 bytes in size.
55151 */
55152 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
55153   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
55154   MemPage *pNew;                       /* Newly allocated page */
55155   int rc;                              /* Return Code */
55156   Pgno pgnoNew;                        /* Page number of pNew */
55157
55158   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
55159   assert( sqlcipher3PagerIswriteable(pParent->pDbPage) );
55160   assert( pPage->nOverflow==1 );
55161
55162   /* This error condition is now caught prior to reaching this function */
55163   if( pPage->nCell<=0 ) return SQLCIPHER_CORRUPT_BKPT;
55164
55165   /* Allocate a new page. This page will become the right-sibling of 
55166   ** pPage. Make the parent page writable, so that the new divider cell
55167   ** may be inserted. If both these operations are successful, proceed.
55168   */
55169   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
55170
55171   if( rc==SQLCIPHER_OK ){
55172
55173     u8 *pOut = &pSpace[4];
55174     u8 *pCell = pPage->aOvfl[0].pCell;
55175     u16 szCell = cellSizePtr(pPage, pCell);
55176     u8 *pStop;
55177
55178     assert( sqlcipher3PagerIswriteable(pNew->pDbPage) );
55179     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
55180     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
55181     assemblePage(pNew, 1, &pCell, &szCell);
55182
55183     /* If this is an auto-vacuum database, update the pointer map
55184     ** with entries for the new page, and any pointer from the 
55185     ** cell on the page to an overflow page. If either of these
55186     ** operations fails, the return code is set, but the contents
55187     ** of the parent page are still manipulated by thh code below.
55188     ** That is Ok, at this point the parent page is guaranteed to
55189     ** be marked as dirty. Returning an error code will cause a
55190     ** rollback, undoing any changes made to the parent page.
55191     */
55192     if( ISAUTOVACUUM ){
55193       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
55194       if( szCell>pNew->minLocal ){
55195         ptrmapPutOvflPtr(pNew, pCell, &rc);
55196       }
55197     }
55198   
55199     /* Create a divider cell to insert into pParent. The divider cell
55200     ** consists of a 4-byte page number (the page number of pPage) and
55201     ** a variable length key value (which must be the same value as the
55202     ** largest key on pPage).
55203     **
55204     ** To find the largest key value on pPage, first find the right-most 
55205     ** cell on pPage. The first two fields of this cell are the 
55206     ** record-length (a variable length integer at most 32-bits in size)
55207     ** and the key value (a variable length integer, may have any value).
55208     ** The first of the while(...) loops below skips over the record-length
55209     ** field. The second while(...) loop copies the key value from the
55210     ** cell on pPage into the pSpace buffer.
55211     */
55212     pCell = findCell(pPage, pPage->nCell-1);
55213     pStop = &pCell[9];
55214     while( (*(pCell++)&0x80) && pCell<pStop );
55215     pStop = &pCell[9];
55216     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
55217
55218     /* Insert the new divider cell into pParent. */
55219     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
55220                0, pPage->pgno, &rc);
55221
55222     /* Set the right-child pointer of pParent to point to the new page. */
55223     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
55224   
55225     /* Release the reference to the new page. */
55226     releasePage(pNew);
55227   }
55228
55229   return rc;
55230 }
55231 #endif /* SQLCIPHER_OMIT_QUICKBALANCE */
55232
55233 #if 0
55234 /*
55235 ** This function does not contribute anything to the operation of SQLite.
55236 ** it is sometimes activated temporarily while debugging code responsible 
55237 ** for setting pointer-map entries.
55238 */
55239 static int ptrmapCheckPages(MemPage **apPage, int nPage){
55240   int i, j;
55241   for(i=0; i<nPage; i++){
55242     Pgno n;
55243     u8 e;
55244     MemPage *pPage = apPage[i];
55245     BtShared *pBt = pPage->pBt;
55246     assert( pPage->isInit );
55247
55248     for(j=0; j<pPage->nCell; j++){
55249       CellInfo info;
55250       u8 *z;
55251      
55252       z = findCell(pPage, j);
55253       btreeParseCellPtr(pPage, z, &info);
55254       if( info.iOverflow ){
55255         Pgno ovfl = get4byte(&z[info.iOverflow]);
55256         ptrmapGet(pBt, ovfl, &e, &n);
55257         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
55258       }
55259       if( !pPage->leaf ){
55260         Pgno child = get4byte(z);
55261         ptrmapGet(pBt, child, &e, &n);
55262         assert( n==pPage->pgno && e==PTRMAP_BTREE );
55263       }
55264     }
55265     if( !pPage->leaf ){
55266       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55267       ptrmapGet(pBt, child, &e, &n);
55268       assert( n==pPage->pgno && e==PTRMAP_BTREE );
55269     }
55270   }
55271   return 1;
55272 }
55273 #endif
55274
55275 /*
55276 ** This function is used to copy the contents of the b-tree node stored 
55277 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
55278 ** the pointer-map entries for each child page are updated so that the
55279 ** parent page stored in the pointer map is page pTo. If pFrom contained
55280 ** any cells with overflow page pointers, then the corresponding pointer
55281 ** map entries are also updated so that the parent page is page pTo.
55282 **
55283 ** If pFrom is currently carrying any overflow cells (entries in the
55284 ** MemPage.aOvfl[] array), they are not copied to pTo. 
55285 **
55286 ** Before returning, page pTo is reinitialized using btreeInitPage().
55287 **
55288 ** The performance of this function is not critical. It is only used by 
55289 ** the balance_shallower() and balance_deeper() procedures, neither of
55290 ** which are called often under normal circumstances.
55291 */
55292 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
55293   if( (*pRC)==SQLCIPHER_OK ){
55294     BtShared * const pBt = pFrom->pBt;
55295     u8 * const aFrom = pFrom->aData;
55296     u8 * const aTo = pTo->aData;
55297     int const iFromHdr = pFrom->hdrOffset;
55298     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
55299     int rc;
55300     int iData;
55301   
55302   
55303     assert( pFrom->isInit );
55304     assert( pFrom->nFree>=iToHdr );
55305     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
55306   
55307     /* Copy the b-tree node content from page pFrom to page pTo. */
55308     iData = get2byte(&aFrom[iFromHdr+5]);
55309     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
55310     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
55311   
55312     /* Reinitialize page pTo so that the contents of the MemPage structure
55313     ** match the new data. The initialization of pTo can actually fail under
55314     ** fairly obscure circumstances, even though it is a copy of initialized 
55315     ** page pFrom.
55316     */
55317     pTo->isInit = 0;
55318     rc = btreeInitPage(pTo);
55319     if( rc!=SQLCIPHER_OK ){
55320       *pRC = rc;
55321       return;
55322     }
55323   
55324     /* If this is an auto-vacuum database, update the pointer-map entries
55325     ** for any b-tree or overflow pages that pTo now contains the pointers to.
55326     */
55327     if( ISAUTOVACUUM ){
55328       *pRC = setChildPtrmaps(pTo);
55329     }
55330   }
55331 }
55332
55333 /*
55334 ** This routine redistributes cells on the iParentIdx'th child of pParent
55335 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
55336 ** same amount of free space. Usually a single sibling on either side of the
55337 ** page are used in the balancing, though both siblings might come from one
55338 ** side if the page is the first or last child of its parent. If the page 
55339 ** has fewer than 2 siblings (something which can only happen if the page
55340 ** is a root page or a child of a root page) then all available siblings
55341 ** participate in the balancing.
55342 **
55343 ** The number of siblings of the page might be increased or decreased by 
55344 ** one or two in an effort to keep pages nearly full but not over full. 
55345 **
55346 ** Note that when this routine is called, some of the cells on the page
55347 ** might not actually be stored in MemPage.aData[]. This can happen
55348 ** if the page is overfull. This routine ensures that all cells allocated
55349 ** to the page and its siblings fit into MemPage.aData[] before returning.
55350 **
55351 ** In the course of balancing the page and its siblings, cells may be
55352 ** inserted into or removed from the parent page (pParent). Doing so
55353 ** may cause the parent page to become overfull or underfull. If this
55354 ** happens, it is the responsibility of the caller to invoke the correct
55355 ** balancing routine to fix this problem (see the balance() routine). 
55356 **
55357 ** If this routine fails for any reason, it might leave the database
55358 ** in a corrupted state. So if this routine fails, the database should
55359 ** be rolled back.
55360 **
55361 ** The third argument to this function, aOvflSpace, is a pointer to a
55362 ** buffer big enough to hold one page. If while inserting cells into the parent
55363 ** page (pParent) the parent page becomes overfull, this buffer is
55364 ** used to store the parent's overflow cells. Because this function inserts
55365 ** a maximum of four divider cells into the parent page, and the maximum
55366 ** size of a cell stored within an internal node is always less than 1/4
55367 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
55368 ** enough for all overflow cells.
55369 **
55370 ** If aOvflSpace is set to a null pointer, this function returns 
55371 ** SQLCIPHER_NOMEM.
55372 */
55373 static int balance_nonroot(
55374   MemPage *pParent,               /* Parent page of siblings being balanced */
55375   int iParentIdx,                 /* Index of "the page" in pParent */
55376   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
55377   int isRoot                      /* True if pParent is a root-page */
55378 ){
55379   BtShared *pBt;               /* The whole database */
55380   int nCell = 0;               /* Number of cells in apCell[] */
55381   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
55382   int nNew = 0;                /* Number of pages in apNew[] */
55383   int nOld;                    /* Number of pages in apOld[] */
55384   int i, j, k;                 /* Loop counters */
55385   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
55386   int rc = SQLCIPHER_OK;          /* The return code */
55387   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
55388   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
55389   int usableSpace;             /* Bytes in pPage beyond the header */
55390   int pageFlags;               /* Value of pPage->aData[0] */
55391   int subtotal;                /* Subtotal of bytes in cells on one page */
55392   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
55393   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
55394   int szScratch;               /* Size of scratch memory requested */
55395   MemPage *apOld[NB];          /* pPage and up to two siblings */
55396   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
55397   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
55398   u8 *pRight;                  /* Location in parent of right-sibling pointer */
55399   u8 *apDiv[NB-1];             /* Divider cells in pParent */
55400   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
55401   int szNew[NB+2];             /* Combined size of cells place on i-th page */
55402   u8 **apCell = 0;             /* All cells begin balanced */
55403   u16 *szCell;                 /* Local size of all cells in apCell[] */
55404   u8 *aSpace1;                 /* Space for copies of dividers cells */
55405   Pgno pgno;                   /* Temp var to store a page number in */
55406
55407   pBt = pParent->pBt;
55408   assert( sqlcipher3_mutex_held(pBt->mutex) );
55409   assert( sqlcipher3PagerIswriteable(pParent->pDbPage) );
55410
55411 #if 0
55412   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
55413 #endif
55414
55415   /* At this point pParent may have at most one overflow cell. And if
55416   ** this overflow cell is present, it must be the cell with 
55417   ** index iParentIdx. This scenario comes about when this function
55418   ** is called (indirectly) from sqlcipher3BtreeDelete().
55419   */
55420   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
55421   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
55422
55423   if( !aOvflSpace ){
55424     return SQLCIPHER_NOMEM;
55425   }
55426
55427   /* Find the sibling pages to balance. Also locate the cells in pParent 
55428   ** that divide the siblings. An attempt is made to find NN siblings on 
55429   ** either side of pPage. More siblings are taken from one side, however, 
55430   ** if there are fewer than NN siblings on the other side. If pParent
55431   ** has NB or fewer children then all children of pParent are taken.  
55432   **
55433   ** This loop also drops the divider cells from the parent page. This
55434   ** way, the remainder of the function does not have to deal with any
55435   ** overflow cells in the parent page, since if any existed they will
55436   ** have already been removed.
55437   */
55438   i = pParent->nOverflow + pParent->nCell;
55439   if( i<2 ){
55440     nxDiv = 0;
55441     nOld = i+1;
55442   }else{
55443     nOld = 3;
55444     if( iParentIdx==0 ){                 
55445       nxDiv = 0;
55446     }else if( iParentIdx==i ){
55447       nxDiv = i-2;
55448     }else{
55449       nxDiv = iParentIdx-1;
55450     }
55451     i = 2;
55452   }
55453   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
55454     pRight = &pParent->aData[pParent->hdrOffset+8];
55455   }else{
55456     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
55457   }
55458   pgno = get4byte(pRight);
55459   while( 1 ){
55460     rc = getAndInitPage(pBt, pgno, &apOld[i]);
55461     if( rc ){
55462       memset(apOld, 0, (i+1)*sizeof(MemPage*));
55463       goto balance_cleanup;
55464     }
55465     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
55466     if( (i--)==0 ) break;
55467
55468     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
55469       apDiv[i] = pParent->aOvfl[0].pCell;
55470       pgno = get4byte(apDiv[i]);
55471       szNew[i] = cellSizePtr(pParent, apDiv[i]);
55472       pParent->nOverflow = 0;
55473     }else{
55474       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
55475       pgno = get4byte(apDiv[i]);
55476       szNew[i] = cellSizePtr(pParent, apDiv[i]);
55477
55478       /* Drop the cell from the parent page. apDiv[i] still points to
55479       ** the cell within the parent, even though it has been dropped.
55480       ** This is safe because dropping a cell only overwrites the first
55481       ** four bytes of it, and this function does not need the first
55482       ** four bytes of the divider cell. So the pointer is safe to use
55483       ** later on.  
55484       **
55485       ** But not if we are in secure-delete mode. In secure-delete mode,
55486       ** the dropCell() routine will overwrite the entire cell with zeroes.
55487       ** In this case, temporarily copy the cell into the aOvflSpace[]
55488       ** buffer. It will be copied out again as soon as the aSpace[] buffer
55489       ** is allocated.  */
55490       if( pBt->secureDelete ){
55491         int iOff;
55492
55493         iOff = SQLCIPHER_PTR_TO_INT(apDiv[i]) - SQLCIPHER_PTR_TO_INT(pParent->aData);
55494         if( (iOff+szNew[i])>(int)pBt->usableSize ){
55495           rc = SQLCIPHER_CORRUPT_BKPT;
55496           memset(apOld, 0, (i+1)*sizeof(MemPage*));
55497           goto balance_cleanup;
55498         }else{
55499           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
55500           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
55501         }
55502       }
55503       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
55504     }
55505   }
55506
55507   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
55508   ** alignment */
55509   nMaxCells = (nMaxCells + 3)&~3;
55510
55511   /*
55512   ** Allocate space for memory structures
55513   */
55514   k = pBt->pageSize + ROUND8(sizeof(MemPage));
55515   szScratch =
55516        nMaxCells*sizeof(u8*)                       /* apCell */
55517      + nMaxCells*sizeof(u16)                       /* szCell */
55518      + pBt->pageSize                               /* aSpace1 */
55519      + k*nOld;                                     /* Page copies (apCopy) */
55520   apCell = sqlcipher3ScratchMalloc( szScratch ); 
55521   if( apCell==0 ){
55522     rc = SQLCIPHER_NOMEM;
55523     goto balance_cleanup;
55524   }
55525   szCell = (u16*)&apCell[nMaxCells];
55526   aSpace1 = (u8*)&szCell[nMaxCells];
55527   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
55528
55529   /*
55530   ** Load pointers to all cells on sibling pages and the divider cells
55531   ** into the local apCell[] array.  Make copies of the divider cells
55532   ** into space obtained from aSpace1[] and remove the the divider Cells
55533   ** from pParent.
55534   **
55535   ** If the siblings are on leaf pages, then the child pointers of the
55536   ** divider cells are stripped from the cells before they are copied
55537   ** into aSpace1[].  In this way, all cells in apCell[] are without
55538   ** child pointers.  If siblings are not leaves, then all cell in
55539   ** apCell[] include child pointers.  Either way, all cells in apCell[]
55540   ** are alike.
55541   **
55542   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
55543   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
55544   */
55545   leafCorrection = apOld[0]->leaf*4;
55546   leafData = apOld[0]->hasData;
55547   for(i=0; i<nOld; i++){
55548     int limit;
55549     
55550     /* Before doing anything else, take a copy of the i'th original sibling
55551     ** The rest of this function will use data from the copies rather
55552     ** that the original pages since the original pages will be in the
55553     ** process of being overwritten.  */
55554     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
55555     memcpy(pOld, apOld[i], sizeof(MemPage));
55556     pOld->aData = (void*)&pOld[1];
55557     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
55558
55559     limit = pOld->nCell+pOld->nOverflow;
55560     if( pOld->nOverflow>0 ){
55561       for(j=0; j<limit; j++){
55562         assert( nCell<nMaxCells );
55563         apCell[nCell] = findOverflowCell(pOld, j);
55564         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55565         nCell++;
55566       }
55567     }else{
55568       u8 *aData = pOld->aData;
55569       u16 maskPage = pOld->maskPage;
55570       u16 cellOffset = pOld->cellOffset;
55571       for(j=0; j<limit; j++){
55572         assert( nCell<nMaxCells );
55573         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
55574         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55575         nCell++;
55576       }
55577     }       
55578     if( i<nOld-1 && !leafData){
55579       u16 sz = (u16)szNew[i];
55580       u8 *pTemp;
55581       assert( nCell<nMaxCells );
55582       szCell[nCell] = sz;
55583       pTemp = &aSpace1[iSpace1];
55584       iSpace1 += sz;
55585       assert( sz<=pBt->maxLocal+23 );
55586       assert( iSpace1 <= (int)pBt->pageSize );
55587       memcpy(pTemp, apDiv[i], sz);
55588       apCell[nCell] = pTemp+leafCorrection;
55589       assert( leafCorrection==0 || leafCorrection==4 );
55590       szCell[nCell] = szCell[nCell] - leafCorrection;
55591       if( !pOld->leaf ){
55592         assert( leafCorrection==0 );
55593         assert( pOld->hdrOffset==0 );
55594         /* The right pointer of the child page pOld becomes the left
55595         ** pointer of the divider cell */
55596         memcpy(apCell[nCell], &pOld->aData[8], 4);
55597       }else{
55598         assert( leafCorrection==4 );
55599         if( szCell[nCell]<4 ){
55600           /* Do not allow any cells smaller than 4 bytes. */
55601           szCell[nCell] = 4;
55602         }
55603       }
55604       nCell++;
55605     }
55606   }
55607
55608   /*
55609   ** Figure out the number of pages needed to hold all nCell cells.
55610   ** Store this number in "k".  Also compute szNew[] which is the total
55611   ** size of all cells on the i-th page and cntNew[] which is the index
55612   ** in apCell[] of the cell that divides page i from page i+1.  
55613   ** cntNew[k] should equal nCell.
55614   **
55615   ** Values computed by this block:
55616   **
55617   **           k: The total number of sibling pages
55618   **    szNew[i]: Spaced used on the i-th sibling page.
55619   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
55620   **              the right of the i-th sibling page.
55621   ** usableSpace: Number of bytes of space available on each sibling.
55622   ** 
55623   */
55624   usableSpace = pBt->usableSize - 12 + leafCorrection;
55625   for(subtotal=k=i=0; i<nCell; i++){
55626     assert( i<nMaxCells );
55627     subtotal += szCell[i] + 2;
55628     if( subtotal > usableSpace ){
55629       szNew[k] = subtotal - szCell[i];
55630       cntNew[k] = i;
55631       if( leafData ){ i--; }
55632       subtotal = 0;
55633       k++;
55634       if( k>NB+1 ){ rc = SQLCIPHER_CORRUPT_BKPT; goto balance_cleanup; }
55635     }
55636   }
55637   szNew[k] = subtotal;
55638   cntNew[k] = nCell;
55639   k++;
55640
55641   /*
55642   ** The packing computed by the previous block is biased toward the siblings
55643   ** on the left side.  The left siblings are always nearly full, while the
55644   ** right-most sibling might be nearly empty.  This block of code attempts
55645   ** to adjust the packing of siblings to get a better balance.
55646   **
55647   ** This adjustment is more than an optimization.  The packing above might
55648   ** be so out of balance as to be illegal.  For example, the right-most
55649   ** sibling might be completely empty.  This adjustment is not optional.
55650   */
55651   for(i=k-1; i>0; i--){
55652     int szRight = szNew[i];  /* Size of sibling on the right */
55653     int szLeft = szNew[i-1]; /* Size of sibling on the left */
55654     int r;              /* Index of right-most cell in left sibling */
55655     int d;              /* Index of first cell to the left of right sibling */
55656
55657     r = cntNew[i-1] - 1;
55658     d = r + 1 - leafData;
55659     assert( d<nMaxCells );
55660     assert( r<nMaxCells );
55661     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
55662       szRight += szCell[d] + 2;
55663       szLeft -= szCell[r] + 2;
55664       cntNew[i-1]--;
55665       r = cntNew[i-1] - 1;
55666       d = r + 1 - leafData;
55667     }
55668     szNew[i] = szRight;
55669     szNew[i-1] = szLeft;
55670   }
55671
55672   /* Either we found one or more cells (cntnew[0])>0) or pPage is
55673   ** a virtual root page.  A virtual root page is when the real root
55674   ** page is page 1 and we are the only child of that page.
55675   */
55676   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
55677
55678   TRACE(("BALANCE: old: %d %d %d  ",
55679     apOld[0]->pgno, 
55680     nOld>=2 ? apOld[1]->pgno : 0,
55681     nOld>=3 ? apOld[2]->pgno : 0
55682   ));
55683
55684   /*
55685   ** Allocate k new pages.  Reuse old pages where possible.
55686   */
55687   if( apOld[0]->pgno<=1 ){
55688     rc = SQLCIPHER_CORRUPT_BKPT;
55689     goto balance_cleanup;
55690   }
55691   pageFlags = apOld[0]->aData[0];
55692   for(i=0; i<k; i++){
55693     MemPage *pNew;
55694     if( i<nOld ){
55695       pNew = apNew[i] = apOld[i];
55696       apOld[i] = 0;
55697       rc = sqlcipher3PagerWrite(pNew->pDbPage);
55698       nNew++;
55699       if( rc ) goto balance_cleanup;
55700     }else{
55701       assert( i>0 );
55702       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
55703       if( rc ) goto balance_cleanup;
55704       apNew[i] = pNew;
55705       nNew++;
55706
55707       /* Set the pointer-map entry for the new sibling page. */
55708       if( ISAUTOVACUUM ){
55709         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
55710         if( rc!=SQLCIPHER_OK ){
55711           goto balance_cleanup;
55712         }
55713       }
55714     }
55715   }
55716
55717   /* Free any old pages that were not reused as new pages.
55718   */
55719   while( i<nOld ){
55720     freePage(apOld[i], &rc);
55721     if( rc ) goto balance_cleanup;
55722     releasePage(apOld[i]);
55723     apOld[i] = 0;
55724     i++;
55725   }
55726
55727   /*
55728   ** Put the new pages in accending order.  This helps to
55729   ** keep entries in the disk file in order so that a scan
55730   ** of the table is a linear scan through the file.  That
55731   ** in turn helps the operating system to deliver pages
55732   ** from the disk more rapidly.
55733   **
55734   ** An O(n^2) insertion sort algorithm is used, but since
55735   ** n is never more than NB (a small constant), that should
55736   ** not be a problem.
55737   **
55738   ** When NB==3, this one optimization makes the database
55739   ** about 25% faster for large insertions and deletions.
55740   */
55741   for(i=0; i<k-1; i++){
55742     int minV = apNew[i]->pgno;
55743     int minI = i;
55744     for(j=i+1; j<k; j++){
55745       if( apNew[j]->pgno<(unsigned)minV ){
55746         minI = j;
55747         minV = apNew[j]->pgno;
55748       }
55749     }
55750     if( minI>i ){
55751       MemPage *pT;
55752       pT = apNew[i];
55753       apNew[i] = apNew[minI];
55754       apNew[minI] = pT;
55755     }
55756   }
55757   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
55758     apNew[0]->pgno, szNew[0],
55759     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
55760     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
55761     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
55762     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
55763
55764   assert( sqlcipher3PagerIswriteable(pParent->pDbPage) );
55765   put4byte(pRight, apNew[nNew-1]->pgno);
55766
55767   /*
55768   ** Evenly distribute the data in apCell[] across the new pages.
55769   ** Insert divider cells into pParent as necessary.
55770   */
55771   j = 0;
55772   for(i=0; i<nNew; i++){
55773     /* Assemble the new sibling page. */
55774     MemPage *pNew = apNew[i];
55775     assert( j<nMaxCells );
55776     zeroPage(pNew, pageFlags);
55777     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
55778     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
55779     assert( pNew->nOverflow==0 );
55780
55781     j = cntNew[i];
55782
55783     /* If the sibling page assembled above was not the right-most sibling,
55784     ** insert a divider cell into the parent page.
55785     */
55786     assert( i<nNew-1 || j==nCell );
55787     if( j<nCell ){
55788       u8 *pCell;
55789       u8 *pTemp;
55790       int sz;
55791
55792       assert( j<nMaxCells );
55793       pCell = apCell[j];
55794       sz = szCell[j] + leafCorrection;
55795       pTemp = &aOvflSpace[iOvflSpace];
55796       if( !pNew->leaf ){
55797         memcpy(&pNew->aData[8], pCell, 4);
55798       }else if( leafData ){
55799         /* If the tree is a leaf-data tree, and the siblings are leaves, 
55800         ** then there is no divider cell in apCell[]. Instead, the divider 
55801         ** cell consists of the integer key for the right-most cell of 
55802         ** the sibling-page assembled above only.
55803         */
55804         CellInfo info;
55805         j--;
55806         btreeParseCellPtr(pNew, apCell[j], &info);
55807         pCell = pTemp;
55808         sz = 4 + putVarint(&pCell[4], info.nKey);
55809         pTemp = 0;
55810       }else{
55811         pCell -= 4;
55812         /* Obscure case for non-leaf-data trees: If the cell at pCell was
55813         ** previously stored on a leaf node, and its reported size was 4
55814         ** bytes, then it may actually be smaller than this 
55815         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
55816         ** any cell). But it is important to pass the correct size to 
55817         ** insertCell(), so reparse the cell now.
55818         **
55819         ** Note that this can never happen in an SQLite data file, as all
55820         ** cells are at least 4 bytes. It only happens in b-trees used
55821         ** to evaluate "IN (SELECT ...)" and similar clauses.
55822         */
55823         if( szCell[j]==4 ){
55824           assert(leafCorrection==4);
55825           sz = cellSizePtr(pParent, pCell);
55826         }
55827       }
55828       iOvflSpace += sz;
55829       assert( sz<=pBt->maxLocal+23 );
55830       assert( iOvflSpace <= (int)pBt->pageSize );
55831       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
55832       if( rc!=SQLCIPHER_OK ) goto balance_cleanup;
55833       assert( sqlcipher3PagerIswriteable(pParent->pDbPage) );
55834
55835       j++;
55836       nxDiv++;
55837     }
55838   }
55839   assert( j==nCell );
55840   assert( nOld>0 );
55841   assert( nNew>0 );
55842   if( (pageFlags & PTF_LEAF)==0 ){
55843     u8 *zChild = &apCopy[nOld-1]->aData[8];
55844     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
55845   }
55846
55847   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
55848     /* The root page of the b-tree now contains no cells. The only sibling
55849     ** page is the right-child of the parent. Copy the contents of the
55850     ** child page into the parent, decreasing the overall height of the
55851     ** b-tree structure by one. This is described as the "balance-shallower"
55852     ** sub-algorithm in some documentation.
55853     **
55854     ** If this is an auto-vacuum database, the call to copyNodeContent() 
55855     ** sets all pointer-map entries corresponding to database image pages 
55856     ** for which the pointer is stored within the content being copied.
55857     **
55858     ** The second assert below verifies that the child page is defragmented
55859     ** (it must be, as it was just reconstructed using assemblePage()). This
55860     ** is important if the parent page happens to be page 1 of the database
55861     ** image.  */
55862     assert( nNew==1 );
55863     assert( apNew[0]->nFree == 
55864         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
55865     );
55866     copyNodeContent(apNew[0], pParent, &rc);
55867     freePage(apNew[0], &rc);
55868   }else if( ISAUTOVACUUM ){
55869     /* Fix the pointer-map entries for all the cells that were shifted around. 
55870     ** There are several different types of pointer-map entries that need to
55871     ** be dealt with by this routine. Some of these have been set already, but
55872     ** many have not. The following is a summary:
55873     **
55874     **   1) The entries associated with new sibling pages that were not
55875     **      siblings when this function was called. These have already
55876     **      been set. We don't need to worry about old siblings that were
55877     **      moved to the free-list - the freePage() code has taken care
55878     **      of those.
55879     **
55880     **   2) The pointer-map entries associated with the first overflow
55881     **      page in any overflow chains used by new divider cells. These 
55882     **      have also already been taken care of by the insertCell() code.
55883     **
55884     **   3) If the sibling pages are not leaves, then the child pages of
55885     **      cells stored on the sibling pages may need to be updated.
55886     **
55887     **   4) If the sibling pages are not internal intkey nodes, then any
55888     **      overflow pages used by these cells may need to be updated
55889     **      (internal intkey nodes never contain pointers to overflow pages).
55890     **
55891     **   5) If the sibling pages are not leaves, then the pointer-map
55892     **      entries for the right-child pages of each sibling may need
55893     **      to be updated.
55894     **
55895     ** Cases 1 and 2 are dealt with above by other code. The next
55896     ** block deals with cases 3 and 4 and the one after that, case 5. Since
55897     ** setting a pointer map entry is a relatively expensive operation, this
55898     ** code only sets pointer map entries for child or overflow pages that have
55899     ** actually moved between pages.  */
55900     MemPage *pNew = apNew[0];
55901     MemPage *pOld = apCopy[0];
55902     int nOverflow = pOld->nOverflow;
55903     int iNextOld = pOld->nCell + nOverflow;
55904     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
55905     j = 0;                             /* Current 'old' sibling page */
55906     k = 0;                             /* Current 'new' sibling page */
55907     for(i=0; i<nCell; i++){
55908       int isDivider = 0;
55909       while( i==iNextOld ){
55910         /* Cell i is the cell immediately following the last cell on old
55911         ** sibling page j. If the siblings are not leaf pages of an
55912         ** intkey b-tree, then cell i was a divider cell. */
55913         assert( j+1 < ArraySize(apCopy) );
55914         pOld = apCopy[++j];
55915         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
55916         if( pOld->nOverflow ){
55917           nOverflow = pOld->nOverflow;
55918           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
55919         }
55920         isDivider = !leafData;  
55921       }
55922
55923       assert(nOverflow>0 || iOverflow<i );
55924       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
55925       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
55926       if( i==iOverflow ){
55927         isDivider = 1;
55928         if( (--nOverflow)>0 ){
55929           iOverflow++;
55930         }
55931       }
55932
55933       if( i==cntNew[k] ){
55934         /* Cell i is the cell immediately following the last cell on new
55935         ** sibling page k. If the siblings are not leaf pages of an
55936         ** intkey b-tree, then cell i is a divider cell.  */
55937         pNew = apNew[++k];
55938         if( !leafData ) continue;
55939       }
55940       assert( j<nOld );
55941       assert( k<nNew );
55942
55943       /* If the cell was originally divider cell (and is not now) or
55944       ** an overflow cell, or if the cell was located on a different sibling
55945       ** page before the balancing, then the pointer map entries associated
55946       ** with any child or overflow pages need to be updated.  */
55947       if( isDivider || pOld->pgno!=pNew->pgno ){
55948         if( !leafCorrection ){
55949           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
55950         }
55951         if( szCell[i]>pNew->minLocal ){
55952           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
55953         }
55954       }
55955     }
55956
55957     if( !leafCorrection ){
55958       for(i=0; i<nNew; i++){
55959         u32 key = get4byte(&apNew[i]->aData[8]);
55960         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
55961       }
55962     }
55963
55964 #if 0
55965     /* The ptrmapCheckPages() contains assert() statements that verify that
55966     ** all pointer map pages are set correctly. This is helpful while 
55967     ** debugging. This is usually disabled because a corrupt database may
55968     ** cause an assert() statement to fail.  */
55969     ptrmapCheckPages(apNew, nNew);
55970     ptrmapCheckPages(&pParent, 1);
55971 #endif
55972   }
55973
55974   assert( pParent->isInit );
55975   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
55976           nOld, nNew, nCell));
55977
55978   /*
55979   ** Cleanup before returning.
55980   */
55981 balance_cleanup:
55982   sqlcipher3ScratchFree(apCell);
55983   for(i=0; i<nOld; i++){
55984     releasePage(apOld[i]);
55985   }
55986   for(i=0; i<nNew; i++){
55987     releasePage(apNew[i]);
55988   }
55989
55990   return rc;
55991 }
55992
55993
55994 /*
55995 ** This function is called when the root page of a b-tree structure is
55996 ** overfull (has one or more overflow pages).
55997 **
55998 ** A new child page is allocated and the contents of the current root
55999 ** page, including overflow cells, are copied into the child. The root
56000 ** page is then overwritten to make it an empty page with the right-child 
56001 ** pointer pointing to the new page.
56002 **
56003 ** Before returning, all pointer-map entries corresponding to pages 
56004 ** that the new child-page now contains pointers to are updated. The
56005 ** entry corresponding to the new right-child pointer of the root
56006 ** page is also updated.
56007 **
56008 ** If successful, *ppChild is set to contain a reference to the child 
56009 ** page and SQLCIPHER_OK is returned. In this case the caller is required
56010 ** to call releasePage() on *ppChild exactly once. If an error occurs,
56011 ** an error code is returned and *ppChild is set to 0.
56012 */
56013 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
56014   int rc;                        /* Return value from subprocedures */
56015   MemPage *pChild = 0;           /* Pointer to a new child page */
56016   Pgno pgnoChild = 0;            /* Page number of the new child page */
56017   BtShared *pBt = pRoot->pBt;    /* The BTree */
56018
56019   assert( pRoot->nOverflow>0 );
56020   assert( sqlcipher3_mutex_held(pBt->mutex) );
56021
56022   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
56023   ** page that will become the new right-child of pPage. Copy the contents
56024   ** of the node stored on pRoot into the new child page.
56025   */
56026   rc = sqlcipher3PagerWrite(pRoot->pDbPage);
56027   if( rc==SQLCIPHER_OK ){
56028     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
56029     copyNodeContent(pRoot, pChild, &rc);
56030     if( ISAUTOVACUUM ){
56031       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
56032     }
56033   }
56034   if( rc ){
56035     *ppChild = 0;
56036     releasePage(pChild);
56037     return rc;
56038   }
56039   assert( sqlcipher3PagerIswriteable(pChild->pDbPage) );
56040   assert( sqlcipher3PagerIswriteable(pRoot->pDbPage) );
56041   assert( pChild->nCell==pRoot->nCell );
56042
56043   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
56044
56045   /* Copy the overflow cells from pRoot to pChild */
56046   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
56047   pChild->nOverflow = pRoot->nOverflow;
56048
56049   /* Zero the contents of pRoot. Then install pChild as the right-child. */
56050   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
56051   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
56052
56053   *ppChild = pChild;
56054   return SQLCIPHER_OK;
56055 }
56056
56057 /*
56058 ** The page that pCur currently points to has just been modified in
56059 ** some way. This function figures out if this modification means the
56060 ** tree needs to be balanced, and if so calls the appropriate balancing 
56061 ** routine. Balancing routines are:
56062 **
56063 **   balance_quick()
56064 **   balance_deeper()
56065 **   balance_nonroot()
56066 */
56067 static int balance(BtCursor *pCur){
56068   int rc = SQLCIPHER_OK;
56069   const int nMin = pCur->pBt->usableSize * 2 / 3;
56070   u8 aBalanceQuickSpace[13];
56071   u8 *pFree = 0;
56072
56073   TESTONLY( int balance_quick_called = 0 );
56074   TESTONLY( int balance_deeper_called = 0 );
56075
56076   do {
56077     int iPage = pCur->iPage;
56078     MemPage *pPage = pCur->apPage[iPage];
56079
56080     if( iPage==0 ){
56081       if( pPage->nOverflow ){
56082         /* The root page of the b-tree is overfull. In this case call the
56083         ** balance_deeper() function to create a new child for the root-page
56084         ** and copy the current contents of the root-page to it. The
56085         ** next iteration of the do-loop will balance the child page.
56086         */ 
56087         assert( (balance_deeper_called++)==0 );
56088         rc = balance_deeper(pPage, &pCur->apPage[1]);
56089         if( rc==SQLCIPHER_OK ){
56090           pCur->iPage = 1;
56091           pCur->aiIdx[0] = 0;
56092           pCur->aiIdx[1] = 0;
56093           assert( pCur->apPage[1]->nOverflow );
56094         }
56095       }else{
56096         break;
56097       }
56098     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
56099       break;
56100     }else{
56101       MemPage * const pParent = pCur->apPage[iPage-1];
56102       int const iIdx = pCur->aiIdx[iPage-1];
56103
56104       rc = sqlcipher3PagerWrite(pParent->pDbPage);
56105       if( rc==SQLCIPHER_OK ){
56106 #ifndef SQLCIPHER_OMIT_QUICKBALANCE
56107         if( pPage->hasData
56108          && pPage->nOverflow==1
56109          && pPage->aOvfl[0].idx==pPage->nCell
56110          && pParent->pgno!=1
56111          && pParent->nCell==iIdx
56112         ){
56113           /* Call balance_quick() to create a new sibling of pPage on which
56114           ** to store the overflow cell. balance_quick() inserts a new cell
56115           ** into pParent, which may cause pParent overflow. If this
56116           ** happens, the next interation of the do-loop will balance pParent 
56117           ** use either balance_nonroot() or balance_deeper(). Until this
56118           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
56119           ** buffer. 
56120           **
56121           ** The purpose of the following assert() is to check that only a
56122           ** single call to balance_quick() is made for each call to this
56123           ** function. If this were not verified, a subtle bug involving reuse
56124           ** of the aBalanceQuickSpace[] might sneak in.
56125           */
56126           assert( (balance_quick_called++)==0 );
56127           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
56128         }else
56129 #endif
56130         {
56131           /* In this case, call balance_nonroot() to redistribute cells
56132           ** between pPage and up to 2 of its sibling pages. This involves
56133           ** modifying the contents of pParent, which may cause pParent to
56134           ** become overfull or underfull. The next iteration of the do-loop
56135           ** will balance the parent page to correct this.
56136           ** 
56137           ** If the parent page becomes overfull, the overflow cell or cells
56138           ** are stored in the pSpace buffer allocated immediately below. 
56139           ** A subsequent iteration of the do-loop will deal with this by
56140           ** calling balance_nonroot() (balance_deeper() may be called first,
56141           ** but it doesn't deal with overflow cells - just moves them to a
56142           ** different page). Once this subsequent call to balance_nonroot() 
56143           ** has completed, it is safe to release the pSpace buffer used by
56144           ** the previous call, as the overflow cell data will have been 
56145           ** copied either into the body of a database page or into the new
56146           ** pSpace buffer passed to the latter call to balance_nonroot().
56147           */
56148           u8 *pSpace = sqlcipher3PageMalloc(pCur->pBt->pageSize);
56149           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
56150           if( pFree ){
56151             /* If pFree is not NULL, it points to the pSpace buffer used 
56152             ** by a previous call to balance_nonroot(). Its contents are
56153             ** now stored either on real database pages or within the 
56154             ** new pSpace buffer, so it may be safely freed here. */
56155             sqlcipher3PageFree(pFree);
56156           }
56157
56158           /* The pSpace buffer will be freed after the next call to
56159           ** balance_nonroot(), or just before this function returns, whichever
56160           ** comes first. */
56161           pFree = pSpace;
56162         }
56163       }
56164
56165       pPage->nOverflow = 0;
56166
56167       /* The next iteration of the do-loop balances the parent page. */
56168       releasePage(pPage);
56169       pCur->iPage--;
56170     }
56171   }while( rc==SQLCIPHER_OK );
56172
56173   if( pFree ){
56174     sqlcipher3PageFree(pFree);
56175   }
56176   return rc;
56177 }
56178
56179
56180 /*
56181 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
56182 ** and the data is given by (pData,nData).  The cursor is used only to
56183 ** define what table the record should be inserted into.  The cursor
56184 ** is left pointing at a random location.
56185 **
56186 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
56187 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
56188 **
56189 ** If the seekResult parameter is non-zero, then a successful call to
56190 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
56191 ** been performed. seekResult is the search result returned (a negative
56192 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
56193 ** a positive value if pCur points at an etry that is larger than 
56194 ** (pKey, nKey)). 
56195 **
56196 ** If the seekResult parameter is non-zero, then the caller guarantees that
56197 ** cursor pCur is pointing at the existing copy of a row that is to be
56198 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
56199 ** point to any entry or to no entry at all and so this function has to seek
56200 ** the cursor before the new key can be inserted.
56201 */
56202 SQLCIPHER_PRIVATE int sqlcipher3BtreeInsert(
56203   BtCursor *pCur,                /* Insert data into the table of this cursor */
56204   const void *pKey, i64 nKey,    /* The key of the new record */
56205   const void *pData, int nData,  /* The data of the new record */
56206   int nZero,                     /* Number of extra 0 bytes to append to data */
56207   int appendBias,                /* True if this is likely an append */
56208   int seekResult                 /* Result of prior MovetoUnpacked() call */
56209 ){
56210   int rc;
56211   int loc = seekResult;          /* -1: before desired location  +1: after */
56212   int szNew = 0;
56213   int idx;
56214   MemPage *pPage;
56215   Btree *p = pCur->pBtree;
56216   BtShared *pBt = p->pBt;
56217   unsigned char *oldCell;
56218   unsigned char *newCell = 0;
56219
56220   if( pCur->eState==CURSOR_FAULT ){
56221     assert( pCur->skipNext!=SQLCIPHER_OK );
56222     return pCur->skipNext;
56223   }
56224
56225   assert( cursorHoldsMutex(pCur) );
56226   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
56227   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56228
56229   /* Assert that the caller has been consistent. If this cursor was opened
56230   ** expecting an index b-tree, then the caller should be inserting blob
56231   ** keys with no associated data. If the cursor was opened expecting an
56232   ** intkey table, the caller should be inserting integer keys with a
56233   ** blob of associated data.  */
56234   assert( (pKey==0)==(pCur->pKeyInfo==0) );
56235
56236   /* If this is an insert into a table b-tree, invalidate any incrblob 
56237   ** cursors open on the row being replaced (assuming this is a replace
56238   ** operation - if it is not, the following is a no-op).  */
56239   if( pCur->pKeyInfo==0 ){
56240     invalidateIncrblobCursors(p, nKey, 0);
56241   }
56242
56243   /* Save the positions of any other cursors open on this table.
56244   **
56245   ** In some cases, the call to btreeMoveto() below is a no-op. For
56246   ** example, when inserting data into a table with auto-generated integer
56247   ** keys, the VDBE layer invokes sqlcipher3BtreeLast() to figure out the 
56248   ** integer key to use. It then calls this function to actually insert the 
56249   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
56250   ** that the cursor is already where it needs to be and returns without
56251   ** doing any work. To avoid thwarting these optimizations, it is important
56252   ** not to clear the cursor here.
56253   */
56254   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56255   if( rc ) return rc;
56256   if( !loc ){
56257     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
56258     if( rc ) return rc;
56259   }
56260   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
56261
56262   pPage = pCur->apPage[pCur->iPage];
56263   assert( pPage->intKey || nKey>=0 );
56264   assert( pPage->leaf || !pPage->intKey );
56265
56266   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
56267           pCur->pgnoRoot, nKey, nData, pPage->pgno,
56268           loc==0 ? "overwrite" : "new entry"));
56269   assert( pPage->isInit );
56270   allocateTempSpace(pBt);
56271   newCell = pBt->pTmpSpace;
56272   if( newCell==0 ) return SQLCIPHER_NOMEM;
56273   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
56274   if( rc ) goto end_insert;
56275   assert( szNew==cellSizePtr(pPage, newCell) );
56276   assert( szNew <= MX_CELL_SIZE(pBt) );
56277   idx = pCur->aiIdx[pCur->iPage];
56278   if( loc==0 ){
56279     u16 szOld;
56280     assert( idx<pPage->nCell );
56281     rc = sqlcipher3PagerWrite(pPage->pDbPage);
56282     if( rc ){
56283       goto end_insert;
56284     }
56285     oldCell = findCell(pPage, idx);
56286     if( !pPage->leaf ){
56287       memcpy(newCell, oldCell, 4);
56288     }
56289     szOld = cellSizePtr(pPage, oldCell);
56290     rc = clearCell(pPage, oldCell);
56291     dropCell(pPage, idx, szOld, &rc);
56292     if( rc ) goto end_insert;
56293   }else if( loc<0 && pPage->nCell>0 ){
56294     assert( pPage->leaf );
56295     idx = ++pCur->aiIdx[pCur->iPage];
56296   }else{
56297     assert( pPage->leaf );
56298   }
56299   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
56300   assert( rc!=SQLCIPHER_OK || pPage->nCell>0 || pPage->nOverflow>0 );
56301
56302   /* If no error has occured and pPage has an overflow cell, call balance() 
56303   ** to redistribute the cells within the tree. Since balance() may move
56304   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
56305   ** variables.
56306   **
56307   ** Previous versions of SQLite called moveToRoot() to move the cursor
56308   ** back to the root page as balance() used to invalidate the contents
56309   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
56310   ** set the cursor state to "invalid". This makes common insert operations
56311   ** slightly faster.
56312   **
56313   ** There is a subtle but important optimization here too. When inserting
56314   ** multiple records into an intkey b-tree using a single cursor (as can
56315   ** happen while processing an "INSERT INTO ... SELECT" statement), it
56316   ** is advantageous to leave the cursor pointing to the last entry in
56317   ** the b-tree if possible. If the cursor is left pointing to the last
56318   ** entry in the table, and the next row inserted has an integer key
56319   ** larger than the largest existing key, it is possible to insert the
56320   ** row without seeking the cursor. This can be a big performance boost.
56321   */
56322   pCur->info.nSize = 0;
56323   pCur->validNKey = 0;
56324   if( rc==SQLCIPHER_OK && pPage->nOverflow ){
56325     rc = balance(pCur);
56326
56327     /* Must make sure nOverflow is reset to zero even if the balance()
56328     ** fails. Internal data structure corruption will result otherwise. 
56329     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
56330     ** from trying to save the current position of the cursor.  */
56331     pCur->apPage[pCur->iPage]->nOverflow = 0;
56332     pCur->eState = CURSOR_INVALID;
56333   }
56334   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
56335
56336 end_insert:
56337   return rc;
56338 }
56339
56340 /*
56341 ** Delete the entry that the cursor is pointing to.  The cursor
56342 ** is left pointing at a arbitrary location.
56343 */
56344 SQLCIPHER_PRIVATE int sqlcipher3BtreeDelete(BtCursor *pCur){
56345   Btree *p = pCur->pBtree;
56346   BtShared *pBt = p->pBt;              
56347   int rc;                              /* Return code */
56348   MemPage *pPage;                      /* Page to delete cell from */
56349   unsigned char *pCell;                /* Pointer to cell to delete */
56350   int iCellIdx;                        /* Index of cell to delete */
56351   int iCellDepth;                      /* Depth of node containing pCell */ 
56352
56353   assert( cursorHoldsMutex(pCur) );
56354   assert( pBt->inTransaction==TRANS_WRITE );
56355   assert( !pBt->readOnly );
56356   assert( pCur->wrFlag );
56357   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56358   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
56359
56360   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
56361    || NEVER(pCur->eState!=CURSOR_VALID)
56362   ){
56363     return SQLCIPHER_ERROR;  /* Something has gone awry. */
56364   }
56365
56366   /* If this is a delete operation to remove a row from a table b-tree,
56367   ** invalidate any incrblob cursors open on the row being deleted.  */
56368   if( pCur->pKeyInfo==0 ){
56369     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
56370   }
56371
56372   iCellDepth = pCur->iPage;
56373   iCellIdx = pCur->aiIdx[iCellDepth];
56374   pPage = pCur->apPage[iCellDepth];
56375   pCell = findCell(pPage, iCellIdx);
56376
56377   /* If the page containing the entry to delete is not a leaf page, move
56378   ** the cursor to the largest entry in the tree that is smaller than
56379   ** the entry being deleted. This cell will replace the cell being deleted
56380   ** from the internal node. The 'previous' entry is used for this instead
56381   ** of the 'next' entry, as the previous entry is always a part of the
56382   ** sub-tree headed by the child page of the cell being deleted. This makes
56383   ** balancing the tree following the delete operation easier.  */
56384   if( !pPage->leaf ){
56385     int notUsed;
56386     rc = sqlcipher3BtreePrevious(pCur, &notUsed);
56387     if( rc ) return rc;
56388   }
56389
56390   /* Save the positions of any other cursors open on this table before
56391   ** making any modifications. Make the page containing the entry to be 
56392   ** deleted writable. Then free any overflow pages associated with the 
56393   ** entry and finally remove the cell itself from within the page.  
56394   */
56395   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56396   if( rc ) return rc;
56397   rc = sqlcipher3PagerWrite(pPage->pDbPage);
56398   if( rc ) return rc;
56399   rc = clearCell(pPage, pCell);
56400   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
56401   if( rc ) return rc;
56402
56403   /* If the cell deleted was not located on a leaf page, then the cursor
56404   ** is currently pointing to the largest entry in the sub-tree headed
56405   ** by the child-page of the cell that was just deleted from an internal
56406   ** node. The cell from the leaf node needs to be moved to the internal
56407   ** node to replace the deleted cell.  */
56408   if( !pPage->leaf ){
56409     MemPage *pLeaf = pCur->apPage[pCur->iPage];
56410     int nCell;
56411     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
56412     unsigned char *pTmp;
56413
56414     pCell = findCell(pLeaf, pLeaf->nCell-1);
56415     nCell = cellSizePtr(pLeaf, pCell);
56416     assert( MX_CELL_SIZE(pBt) >= nCell );
56417
56418     allocateTempSpace(pBt);
56419     pTmp = pBt->pTmpSpace;
56420
56421     rc = sqlcipher3PagerWrite(pLeaf->pDbPage);
56422     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
56423     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
56424     if( rc ) return rc;
56425   }
56426
56427   /* Balance the tree. If the entry deleted was located on a leaf page,
56428   ** then the cursor still points to that page. In this case the first
56429   ** call to balance() repairs the tree, and the if(...) condition is
56430   ** never true.
56431   **
56432   ** Otherwise, if the entry deleted was on an internal node page, then
56433   ** pCur is pointing to the leaf page from which a cell was removed to
56434   ** replace the cell deleted from the internal node. This is slightly
56435   ** tricky as the leaf node may be underfull, and the internal node may
56436   ** be either under or overfull. In this case run the balancing algorithm
56437   ** on the leaf node first. If the balance proceeds far enough up the
56438   ** tree that we can be sure that any problem in the internal node has
56439   ** been corrected, so be it. Otherwise, after balancing the leaf node,
56440   ** walk the cursor up the tree to the internal node and balance it as 
56441   ** well.  */
56442   rc = balance(pCur);
56443   if( rc==SQLCIPHER_OK && pCur->iPage>iCellDepth ){
56444     while( pCur->iPage>iCellDepth ){
56445       releasePage(pCur->apPage[pCur->iPage--]);
56446     }
56447     rc = balance(pCur);
56448   }
56449
56450   if( rc==SQLCIPHER_OK ){
56451     moveToRoot(pCur);
56452   }
56453   return rc;
56454 }
56455
56456 /*
56457 ** Create a new BTree table.  Write into *piTable the page
56458 ** number for the root page of the new table.
56459 **
56460 ** The type of type is determined by the flags parameter.  Only the
56461 ** following values of flags are currently in use.  Other values for
56462 ** flags might not work:
56463 **
56464 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
56465 **     BTREE_ZERODATA                  Used for SQL indices
56466 */
56467 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
56468   BtShared *pBt = p->pBt;
56469   MemPage *pRoot;
56470   Pgno pgnoRoot;
56471   int rc;
56472   int ptfFlags;          /* Page-type flage for the root page of new table */
56473
56474   assert( sqlcipher3BtreeHoldsMutex(p) );
56475   assert( pBt->inTransaction==TRANS_WRITE );
56476   assert( !pBt->readOnly );
56477
56478 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
56479   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56480   if( rc ){
56481     return rc;
56482   }
56483 #else
56484   if( pBt->autoVacuum ){
56485     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
56486     MemPage *pPageMove; /* The page to move to. */
56487
56488     /* Creating a new table may probably require moving an existing database
56489     ** to make room for the new tables root page. In case this page turns
56490     ** out to be an overflow page, delete all overflow page-map caches
56491     ** held by open cursors.
56492     */
56493     invalidateAllOverflowCache(pBt);
56494
56495     /* Read the value of meta[3] from the database to determine where the
56496     ** root page of the new table should go. meta[3] is the largest root-page
56497     ** created so far, so the new root-page is (meta[3]+1).
56498     */
56499     sqlcipher3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
56500     pgnoRoot++;
56501
56502     /* The new root-page may not be allocated on a pointer-map page, or the
56503     ** PENDING_BYTE page.
56504     */
56505     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
56506         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
56507       pgnoRoot++;
56508     }
56509     assert( pgnoRoot>=3 );
56510
56511     /* Allocate a page. The page that currently resides at pgnoRoot will
56512     ** be moved to the allocated page (unless the allocated page happens
56513     ** to reside at pgnoRoot).
56514     */
56515     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
56516     if( rc!=SQLCIPHER_OK ){
56517       return rc;
56518     }
56519
56520     if( pgnoMove!=pgnoRoot ){
56521       /* pgnoRoot is the page that will be used for the root-page of
56522       ** the new table (assuming an error did not occur). But we were
56523       ** allocated pgnoMove. If required (i.e. if it was not allocated
56524       ** by extending the file), the current page at position pgnoMove
56525       ** is already journaled.
56526       */
56527       u8 eType = 0;
56528       Pgno iPtrPage = 0;
56529
56530       releasePage(pPageMove);
56531
56532       /* Move the page currently at pgnoRoot to pgnoMove. */
56533       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
56534       if( rc!=SQLCIPHER_OK ){
56535         return rc;
56536       }
56537       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
56538       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
56539         rc = SQLCIPHER_CORRUPT_BKPT;
56540       }
56541       if( rc!=SQLCIPHER_OK ){
56542         releasePage(pRoot);
56543         return rc;
56544       }
56545       assert( eType!=PTRMAP_ROOTPAGE );
56546       assert( eType!=PTRMAP_FREEPAGE );
56547       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
56548       releasePage(pRoot);
56549
56550       /* Obtain the page at pgnoRoot */
56551       if( rc!=SQLCIPHER_OK ){
56552         return rc;
56553       }
56554       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
56555       if( rc!=SQLCIPHER_OK ){
56556         return rc;
56557       }
56558       rc = sqlcipher3PagerWrite(pRoot->pDbPage);
56559       if( rc!=SQLCIPHER_OK ){
56560         releasePage(pRoot);
56561         return rc;
56562       }
56563     }else{
56564       pRoot = pPageMove;
56565     } 
56566
56567     /* Update the pointer-map and meta-data with the new root-page number. */
56568     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
56569     if( rc ){
56570       releasePage(pRoot);
56571       return rc;
56572     }
56573
56574     /* When the new root page was allocated, page 1 was made writable in
56575     ** order either to increase the database filesize, or to decrement the
56576     ** freelist count.  Hence, the sqlcipher3BtreeUpdateMeta() call cannot fail.
56577     */
56578     assert( sqlcipher3PagerIswriteable(pBt->pPage1->pDbPage) );
56579     rc = sqlcipher3BtreeUpdateMeta(p, 4, pgnoRoot);
56580     if( NEVER(rc) ){
56581       releasePage(pRoot);
56582       return rc;
56583     }
56584
56585   }else{
56586     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56587     if( rc ) return rc;
56588   }
56589 #endif
56590   assert( sqlcipher3PagerIswriteable(pRoot->pDbPage) );
56591   if( createTabFlags & BTREE_INTKEY ){
56592     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
56593   }else{
56594     ptfFlags = PTF_ZERODATA | PTF_LEAF;
56595   }
56596   zeroPage(pRoot, ptfFlags);
56597   sqlcipher3PagerUnref(pRoot->pDbPage);
56598   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
56599   *piTable = (int)pgnoRoot;
56600   return SQLCIPHER_OK;
56601 }
56602 SQLCIPHER_PRIVATE int sqlcipher3BtreeCreateTable(Btree *p, int *piTable, int flags){
56603   int rc;
56604   sqlcipher3BtreeEnter(p);
56605   rc = btreeCreateTable(p, piTable, flags);
56606   sqlcipher3BtreeLeave(p);
56607   return rc;
56608 }
56609
56610 /*
56611 ** Erase the given database page and all its children.  Return
56612 ** the page to the freelist.
56613 */
56614 static int clearDatabasePage(
56615   BtShared *pBt,           /* The BTree that contains the table */
56616   Pgno pgno,               /* Page number to clear */
56617   int freePageFlag,        /* Deallocate page if true */
56618   int *pnChange            /* Add number of Cells freed to this counter */
56619 ){
56620   MemPage *pPage;
56621   int rc;
56622   unsigned char *pCell;
56623   int i;
56624
56625   assert( sqlcipher3_mutex_held(pBt->mutex) );
56626   if( pgno>btreePagecount(pBt) ){
56627     return SQLCIPHER_CORRUPT_BKPT;
56628   }
56629
56630   rc = getAndInitPage(pBt, pgno, &pPage);
56631   if( rc ) return rc;
56632   for(i=0; i<pPage->nCell; i++){
56633     pCell = findCell(pPage, i);
56634     if( !pPage->leaf ){
56635       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
56636       if( rc ) goto cleardatabasepage_out;
56637     }
56638     rc = clearCell(pPage, pCell);
56639     if( rc ) goto cleardatabasepage_out;
56640   }
56641   if( !pPage->leaf ){
56642     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
56643     if( rc ) goto cleardatabasepage_out;
56644   }else if( pnChange ){
56645     assert( pPage->intKey );
56646     *pnChange += pPage->nCell;
56647   }
56648   if( freePageFlag ){
56649     freePage(pPage, &rc);
56650   }else if( (rc = sqlcipher3PagerWrite(pPage->pDbPage))==0 ){
56651     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
56652   }
56653
56654 cleardatabasepage_out:
56655   releasePage(pPage);
56656   return rc;
56657 }
56658
56659 /*
56660 ** Delete all information from a single table in the database.  iTable is
56661 ** the page number of the root of the table.  After this routine returns,
56662 ** the root page is empty, but still exists.
56663 **
56664 ** This routine will fail with SQLCIPHER_LOCKED if there are any open
56665 ** read cursors on the table.  Open write cursors are moved to the
56666 ** root of the table.
56667 **
56668 ** If pnChange is not NULL, then table iTable must be an intkey table. The
56669 ** integer value pointed to by pnChange is incremented by the number of
56670 ** entries in the table.
56671 */
56672 SQLCIPHER_PRIVATE int sqlcipher3BtreeClearTable(Btree *p, int iTable, int *pnChange){
56673   int rc;
56674   BtShared *pBt = p->pBt;
56675   sqlcipher3BtreeEnter(p);
56676   assert( p->inTrans==TRANS_WRITE );
56677
56678   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
56679   ** is the root of a table b-tree - if it is not, the following call is
56680   ** a no-op).  */
56681   invalidateIncrblobCursors(p, 0, 1);
56682
56683   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
56684   if( SQLCIPHER_OK==rc ){
56685     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
56686   }
56687   sqlcipher3BtreeLeave(p);
56688   return rc;
56689 }
56690
56691 /*
56692 ** Erase all information in a table and add the root of the table to
56693 ** the freelist.  Except, the root of the principle table (the one on
56694 ** page 1) is never added to the freelist.
56695 **
56696 ** This routine will fail with SQLCIPHER_LOCKED if there are any open
56697 ** cursors on the table.
56698 **
56699 ** If AUTOVACUUM is enabled and the page at iTable is not the last
56700 ** root page in the database file, then the last root page 
56701 ** in the database file is moved into the slot formerly occupied by
56702 ** iTable and that last slot formerly occupied by the last root page
56703 ** is added to the freelist instead of iTable.  In this say, all
56704 ** root pages are kept at the beginning of the database file, which
56705 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
56706 ** page number that used to be the last root page in the file before
56707 ** the move.  If no page gets moved, *piMoved is set to 0.
56708 ** The last root page is recorded in meta[3] and the value of
56709 ** meta[3] is updated by this procedure.
56710 */
56711 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
56712   int rc;
56713   MemPage *pPage = 0;
56714   BtShared *pBt = p->pBt;
56715
56716   assert( sqlcipher3BtreeHoldsMutex(p) );
56717   assert( p->inTrans==TRANS_WRITE );
56718
56719   /* It is illegal to drop a table if any cursors are open on the
56720   ** database. This is because in auto-vacuum mode the backend may
56721   ** need to move another root-page to fill a gap left by the deleted
56722   ** root page. If an open cursor was using this page a problem would 
56723   ** occur.
56724   **
56725   ** This error is caught long before control reaches this point.
56726   */
56727   if( NEVER(pBt->pCursor) ){
56728     sqlcipher3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
56729     return SQLCIPHER_LOCKED_SHAREDCACHE;
56730   }
56731
56732   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
56733   if( rc ) return rc;
56734   rc = sqlcipher3BtreeClearTable(p, iTable, 0);
56735   if( rc ){
56736     releasePage(pPage);
56737     return rc;
56738   }
56739
56740   *piMoved = 0;
56741
56742   if( iTable>1 ){
56743 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
56744     freePage(pPage, &rc);
56745     releasePage(pPage);
56746 #else
56747     if( pBt->autoVacuum ){
56748       Pgno maxRootPgno;
56749       sqlcipher3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
56750
56751       if( iTable==maxRootPgno ){
56752         /* If the table being dropped is the table with the largest root-page
56753         ** number in the database, put the root page on the free list. 
56754         */
56755         freePage(pPage, &rc);
56756         releasePage(pPage);
56757         if( rc!=SQLCIPHER_OK ){
56758           return rc;
56759         }
56760       }else{
56761         /* The table being dropped does not have the largest root-page
56762         ** number in the database. So move the page that does into the 
56763         ** gap left by the deleted root-page.
56764         */
56765         MemPage *pMove;
56766         releasePage(pPage);
56767         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
56768         if( rc!=SQLCIPHER_OK ){
56769           return rc;
56770         }
56771         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
56772         releasePage(pMove);
56773         if( rc!=SQLCIPHER_OK ){
56774           return rc;
56775         }
56776         pMove = 0;
56777         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
56778         freePage(pMove, &rc);
56779         releasePage(pMove);
56780         if( rc!=SQLCIPHER_OK ){
56781           return rc;
56782         }
56783         *piMoved = maxRootPgno;
56784       }
56785
56786       /* Set the new 'max-root-page' value in the database header. This
56787       ** is the old value less one, less one more if that happens to
56788       ** be a root-page number, less one again if that is the
56789       ** PENDING_BYTE_PAGE.
56790       */
56791       maxRootPgno--;
56792       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
56793              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
56794         maxRootPgno--;
56795       }
56796       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
56797
56798       rc = sqlcipher3BtreeUpdateMeta(p, 4, maxRootPgno);
56799     }else{
56800       freePage(pPage, &rc);
56801       releasePage(pPage);
56802     }
56803 #endif
56804   }else{
56805     /* If sqlcipher3BtreeDropTable was called on page 1.
56806     ** This really never should happen except in a corrupt
56807     ** database. 
56808     */
56809     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
56810     releasePage(pPage);
56811   }
56812   return rc;  
56813 }
56814 SQLCIPHER_PRIVATE int sqlcipher3BtreeDropTable(Btree *p, int iTable, int *piMoved){
56815   int rc;
56816   sqlcipher3BtreeEnter(p);
56817   rc = btreeDropTable(p, iTable, piMoved);
56818   sqlcipher3BtreeLeave(p);
56819   return rc;
56820 }
56821
56822
56823 /*
56824 ** This function may only be called if the b-tree connection already
56825 ** has a read or write transaction open on the database.
56826 **
56827 ** Read the meta-information out of a database file.  Meta[0]
56828 ** is the number of free pages currently in the database.  Meta[1]
56829 ** through meta[15] are available for use by higher layers.  Meta[0]
56830 ** is read-only, the others are read/write.
56831 ** 
56832 ** The schema layer numbers meta values differently.  At the schema
56833 ** layer (and the SetCookie and ReadCookie opcodes) the number of
56834 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
56835 */
56836 SQLCIPHER_PRIVATE void sqlcipher3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
56837   BtShared *pBt = p->pBt;
56838
56839   sqlcipher3BtreeEnter(p);
56840   assert( p->inTrans>TRANS_NONE );
56841   assert( SQLCIPHER_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
56842   assert( pBt->pPage1 );
56843   assert( idx>=0 && idx<=15 );
56844
56845   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
56846
56847   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
56848   ** database, mark the database as read-only.  */
56849 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
56850   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
56851 #endif
56852
56853   sqlcipher3BtreeLeave(p);
56854 }
56855
56856 /*
56857 ** Write meta-information back into the database.  Meta[0] is
56858 ** read-only and may not be written.
56859 */
56860 SQLCIPHER_PRIVATE int sqlcipher3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
56861   BtShared *pBt = p->pBt;
56862   unsigned char *pP1;
56863   int rc;
56864   assert( idx>=1 && idx<=15 );
56865   sqlcipher3BtreeEnter(p);
56866   assert( p->inTrans==TRANS_WRITE );
56867   assert( pBt->pPage1!=0 );
56868   pP1 = pBt->pPage1->aData;
56869   rc = sqlcipher3PagerWrite(pBt->pPage1->pDbPage);
56870   if( rc==SQLCIPHER_OK ){
56871     put4byte(&pP1[36 + idx*4], iMeta);
56872 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
56873     if( idx==BTREE_INCR_VACUUM ){
56874       assert( pBt->autoVacuum || iMeta==0 );
56875       assert( iMeta==0 || iMeta==1 );
56876       pBt->incrVacuum = (u8)iMeta;
56877     }
56878 #endif
56879   }
56880   sqlcipher3BtreeLeave(p);
56881   return rc;
56882 }
56883
56884 #ifndef SQLCIPHER_OMIT_BTREECOUNT
56885 /*
56886 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
56887 ** number of entries in the b-tree and write the result to *pnEntry.
56888 **
56889 ** SQLCIPHER_OK is returned if the operation is successfully executed. 
56890 ** Otherwise, if an error is encountered (i.e. an IO error or database
56891 ** corruption) an SQLite error code is returned.
56892 */
56893 SQLCIPHER_PRIVATE int sqlcipher3BtreeCount(BtCursor *pCur, i64 *pnEntry){
56894   i64 nEntry = 0;                      /* Value to return in *pnEntry */
56895   int rc;                              /* Return code */
56896
56897   if( pCur->pgnoRoot==0 ){
56898     *pnEntry = 0;
56899     return SQLCIPHER_OK;
56900   }
56901   rc = moveToRoot(pCur);
56902
56903   /* Unless an error occurs, the following loop runs one iteration for each
56904   ** page in the B-Tree structure (not including overflow pages). 
56905   */
56906   while( rc==SQLCIPHER_OK ){
56907     int iIdx;                          /* Index of child node in parent */
56908     MemPage *pPage;                    /* Current page of the b-tree */
56909
56910     /* If this is a leaf page or the tree is not an int-key tree, then 
56911     ** this page contains countable entries. Increment the entry counter
56912     ** accordingly.
56913     */
56914     pPage = pCur->apPage[pCur->iPage];
56915     if( pPage->leaf || !pPage->intKey ){
56916       nEntry += pPage->nCell;
56917     }
56918
56919     /* pPage is a leaf node. This loop navigates the cursor so that it 
56920     ** points to the first interior cell that it points to the parent of
56921     ** the next page in the tree that has not yet been visited. The
56922     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
56923     ** of the page, or to the number of cells in the page if the next page
56924     ** to visit is the right-child of its parent.
56925     **
56926     ** If all pages in the tree have been visited, return SQLCIPHER_OK to the
56927     ** caller.
56928     */
56929     if( pPage->leaf ){
56930       do {
56931         if( pCur->iPage==0 ){
56932           /* All pages of the b-tree have been visited. Return successfully. */
56933           *pnEntry = nEntry;
56934           return SQLCIPHER_OK;
56935         }
56936         moveToParent(pCur);
56937       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
56938
56939       pCur->aiIdx[pCur->iPage]++;
56940       pPage = pCur->apPage[pCur->iPage];
56941     }
56942
56943     /* Descend to the child node of the cell that the cursor currently 
56944     ** points at. This is the right-child if (iIdx==pPage->nCell).
56945     */
56946     iIdx = pCur->aiIdx[pCur->iPage];
56947     if( iIdx==pPage->nCell ){
56948       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
56949     }else{
56950       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
56951     }
56952   }
56953
56954   /* An error has occurred. Return an error code. */
56955   return rc;
56956 }
56957 #endif
56958
56959 /*
56960 ** Return the pager associated with a BTree.  This routine is used for
56961 ** testing and debugging only.
56962 */
56963 SQLCIPHER_PRIVATE Pager *sqlcipher3BtreePager(Btree *p){
56964   return p->pBt->pPager;
56965 }
56966
56967 #ifndef SQLCIPHER_OMIT_INTEGRITY_CHECK
56968 /*
56969 ** Append a message to the error message string.
56970 */
56971 static void checkAppendMsg(
56972   IntegrityCk *pCheck,
56973   char *zMsg1,
56974   const char *zFormat,
56975   ...
56976 ){
56977   va_list ap;
56978   if( !pCheck->mxErr ) return;
56979   pCheck->mxErr--;
56980   pCheck->nErr++;
56981   va_start(ap, zFormat);
56982   if( pCheck->errMsg.nChar ){
56983     sqlcipher3StrAccumAppend(&pCheck->errMsg, "\n", 1);
56984   }
56985   if( zMsg1 ){
56986     sqlcipher3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
56987   }
56988   sqlcipher3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
56989   va_end(ap);
56990   if( pCheck->errMsg.mallocFailed ){
56991     pCheck->mallocFailed = 1;
56992   }
56993 }
56994 #endif /* SQLCIPHER_OMIT_INTEGRITY_CHECK */
56995
56996 #ifndef SQLCIPHER_OMIT_INTEGRITY_CHECK
56997 /*
56998 ** Add 1 to the reference count for page iPage.  If this is the second
56999 ** reference to the page, add an error message to pCheck->zErrMsg.
57000 ** Return 1 if there are 2 ore more references to the page and 0 if
57001 ** if this is the first reference to the page.
57002 **
57003 ** Also check that the page number is in bounds.
57004 */
57005 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
57006   if( iPage==0 ) return 1;
57007   if( iPage>pCheck->nPage ){
57008     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
57009     return 1;
57010   }
57011   if( pCheck->anRef[iPage]==1 ){
57012     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
57013     return 1;
57014   }
57015   return  (pCheck->anRef[iPage]++)>1;
57016 }
57017
57018 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57019 /*
57020 ** Check that the entry in the pointer-map for page iChild maps to 
57021 ** page iParent, pointer type ptrType. If not, append an error message
57022 ** to pCheck.
57023 */
57024 static void checkPtrmap(
57025   IntegrityCk *pCheck,   /* Integrity check context */
57026   Pgno iChild,           /* Child page number */
57027   u8 eType,              /* Expected pointer map type */
57028   Pgno iParent,          /* Expected pointer map parent page number */
57029   char *zContext         /* Context description (used for error msg) */
57030 ){
57031   int rc;
57032   u8 ePtrmapType = 0;
57033   Pgno iPtrmapParent = 0;
57034
57035   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
57036   if( rc!=SQLCIPHER_OK ){
57037     if( rc==SQLCIPHER_NOMEM || rc==SQLCIPHER_IOERR_NOMEM ) pCheck->mallocFailed = 1;
57038     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
57039     return;
57040   }
57041
57042   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
57043     checkAppendMsg(pCheck, zContext, 
57044       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
57045       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
57046   }
57047 }
57048 #endif
57049
57050 /*
57051 ** Check the integrity of the freelist or of an overflow page list.
57052 ** Verify that the number of pages on the list is N.
57053 */
57054 static void checkList(
57055   IntegrityCk *pCheck,  /* Integrity checking context */
57056   int isFreeList,       /* True for a freelist.  False for overflow page list */
57057   int iPage,            /* Page number for first page in the list */
57058   int N,                /* Expected number of pages in the list */
57059   char *zContext        /* Context for error messages */
57060 ){
57061   int i;
57062   int expected = N;
57063   int iFirst = iPage;
57064   while( N-- > 0 && pCheck->mxErr ){
57065     DbPage *pOvflPage;
57066     unsigned char *pOvflData;
57067     if( iPage<1 ){
57068       checkAppendMsg(pCheck, zContext,
57069          "%d of %d pages missing from overflow list starting at %d",
57070           N+1, expected, iFirst);
57071       break;
57072     }
57073     if( checkRef(pCheck, iPage, zContext) ) break;
57074     if( sqlcipher3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
57075       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
57076       break;
57077     }
57078     pOvflData = (unsigned char *)sqlcipher3PagerGetData(pOvflPage);
57079     if( isFreeList ){
57080       int n = get4byte(&pOvflData[4]);
57081 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57082       if( pCheck->pBt->autoVacuum ){
57083         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
57084       }
57085 #endif
57086       if( n>(int)pCheck->pBt->usableSize/4-2 ){
57087         checkAppendMsg(pCheck, zContext,
57088            "freelist leaf count too big on page %d", iPage);
57089         N--;
57090       }else{
57091         for(i=0; i<n; i++){
57092           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
57093 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57094           if( pCheck->pBt->autoVacuum ){
57095             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
57096           }
57097 #endif
57098           checkRef(pCheck, iFreePage, zContext);
57099         }
57100         N -= n;
57101       }
57102     }
57103 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57104     else{
57105       /* If this database supports auto-vacuum and iPage is not the last
57106       ** page in this overflow list, check that the pointer-map entry for
57107       ** the following page matches iPage.
57108       */
57109       if( pCheck->pBt->autoVacuum && N>0 ){
57110         i = get4byte(pOvflData);
57111         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
57112       }
57113     }
57114 #endif
57115     iPage = get4byte(pOvflData);
57116     sqlcipher3PagerUnref(pOvflPage);
57117   }
57118 }
57119 #endif /* SQLCIPHER_OMIT_INTEGRITY_CHECK */
57120
57121 #ifndef SQLCIPHER_OMIT_INTEGRITY_CHECK
57122 /*
57123 ** Do various sanity checks on a single page of a tree.  Return
57124 ** the tree depth.  Root pages return 0.  Parents of root pages
57125 ** return 1, and so forth.
57126 ** 
57127 ** These checks are done:
57128 **
57129 **      1.  Make sure that cells and freeblocks do not overlap
57130 **          but combine to completely cover the page.
57131 **  NO  2.  Make sure cell keys are in order.
57132 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
57133 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
57134 **      5.  Check the integrity of overflow pages.
57135 **      6.  Recursively call checkTreePage on all children.
57136 **      7.  Verify that the depth of all children is the same.
57137 **      8.  Make sure this page is at least 33% full or else it is
57138 **          the root of the tree.
57139 */
57140 static int checkTreePage(
57141   IntegrityCk *pCheck,  /* Context for the sanity check */
57142   int iPage,            /* Page number of the page to check */
57143   char *zParentContext, /* Parent context */
57144   i64 *pnParentMinKey, 
57145   i64 *pnParentMaxKey
57146 ){
57147   MemPage *pPage;
57148   int i, rc, depth, d2, pgno, cnt;
57149   int hdr, cellStart;
57150   int nCell;
57151   u8 *data;
57152   BtShared *pBt;
57153   int usableSize;
57154   char zContext[100];
57155   char *hit = 0;
57156   i64 nMinKey = 0;
57157   i64 nMaxKey = 0;
57158
57159   sqlcipher3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
57160
57161   /* Check that the page exists
57162   */
57163   pBt = pCheck->pBt;
57164   usableSize = pBt->usableSize;
57165   if( iPage==0 ) return 0;
57166   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
57167   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
57168     checkAppendMsg(pCheck, zContext,
57169        "unable to get the page. error code=%d", rc);
57170     return 0;
57171   }
57172
57173   /* Clear MemPage.isInit to make sure the corruption detection code in
57174   ** btreeInitPage() is executed.  */
57175   pPage->isInit = 0;
57176   if( (rc = btreeInitPage(pPage))!=0 ){
57177     assert( rc==SQLCIPHER_CORRUPT );  /* The only possible error from InitPage */
57178     checkAppendMsg(pCheck, zContext, 
57179                    "btreeInitPage() returns error code %d", rc);
57180     releasePage(pPage);
57181     return 0;
57182   }
57183
57184   /* Check out all the cells.
57185   */
57186   depth = 0;
57187   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
57188     u8 *pCell;
57189     u32 sz;
57190     CellInfo info;
57191
57192     /* Check payload overflow pages
57193     */
57194     sqlcipher3_snprintf(sizeof(zContext), zContext,
57195              "On tree page %d cell %d: ", iPage, i);
57196     pCell = findCell(pPage,i);
57197     btreeParseCellPtr(pPage, pCell, &info);
57198     sz = info.nData;
57199     if( !pPage->intKey ) sz += (int)info.nKey;
57200     /* For intKey pages, check that the keys are in order.
57201     */
57202     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
57203     else{
57204       if( info.nKey <= nMaxKey ){
57205         checkAppendMsg(pCheck, zContext, 
57206             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
57207       }
57208       nMaxKey = info.nKey;
57209     }
57210     assert( sz==info.nPayload );
57211     if( (sz>info.nLocal) 
57212      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
57213     ){
57214       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
57215       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
57216 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57217       if( pBt->autoVacuum ){
57218         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
57219       }
57220 #endif
57221       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
57222     }
57223
57224     /* Check sanity of left child page.
57225     */
57226     if( !pPage->leaf ){
57227       pgno = get4byte(pCell);
57228 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57229       if( pBt->autoVacuum ){
57230         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57231       }
57232 #endif
57233       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
57234       if( i>0 && d2!=depth ){
57235         checkAppendMsg(pCheck, zContext, "Child page depth differs");
57236       }
57237       depth = d2;
57238     }
57239   }
57240
57241   if( !pPage->leaf ){
57242     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57243     sqlcipher3_snprintf(sizeof(zContext), zContext, 
57244                      "On page %d at right child: ", iPage);
57245 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57246     if( pBt->autoVacuum ){
57247       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57248     }
57249 #endif
57250     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
57251   }
57252  
57253   /* For intKey leaf pages, check that the min/max keys are in order
57254   ** with any left/parent/right pages.
57255   */
57256   if( pPage->leaf && pPage->intKey ){
57257     /* if we are a left child page */
57258     if( pnParentMinKey ){
57259       /* if we are the left most child page */
57260       if( !pnParentMaxKey ){
57261         if( nMaxKey > *pnParentMinKey ){
57262           checkAppendMsg(pCheck, zContext, 
57263               "Rowid %lld out of order (max larger than parent min of %lld)",
57264               nMaxKey, *pnParentMinKey);
57265         }
57266       }else{
57267         if( nMinKey <= *pnParentMinKey ){
57268           checkAppendMsg(pCheck, zContext, 
57269               "Rowid %lld out of order (min less than parent min of %lld)",
57270               nMinKey, *pnParentMinKey);
57271         }
57272         if( nMaxKey > *pnParentMaxKey ){
57273           checkAppendMsg(pCheck, zContext, 
57274               "Rowid %lld out of order (max larger than parent max of %lld)",
57275               nMaxKey, *pnParentMaxKey);
57276         }
57277         *pnParentMinKey = nMaxKey;
57278       }
57279     /* else if we're a right child page */
57280     } else if( pnParentMaxKey ){
57281       if( nMinKey <= *pnParentMaxKey ){
57282         checkAppendMsg(pCheck, zContext, 
57283             "Rowid %lld out of order (min less than parent max of %lld)",
57284             nMinKey, *pnParentMaxKey);
57285       }
57286     }
57287   }
57288
57289   /* Check for complete coverage of the page
57290   */
57291   data = pPage->aData;
57292   hdr = pPage->hdrOffset;
57293   hit = sqlcipher3PageMalloc( pBt->pageSize );
57294   if( hit==0 ){
57295     pCheck->mallocFailed = 1;
57296   }else{
57297     int contentOffset = get2byteNotZero(&data[hdr+5]);
57298     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
57299     memset(hit+contentOffset, 0, usableSize-contentOffset);
57300     memset(hit, 1, contentOffset);
57301     nCell = get2byte(&data[hdr+3]);
57302     cellStart = hdr + 12 - 4*pPage->leaf;
57303     for(i=0; i<nCell; i++){
57304       int pc = get2byte(&data[cellStart+i*2]);
57305       u32 size = 65536;
57306       int j;
57307       if( pc<=usableSize-4 ){
57308         size = cellSizePtr(pPage, &data[pc]);
57309       }
57310       if( (int)(pc+size-1)>=usableSize ){
57311         checkAppendMsg(pCheck, 0, 
57312             "Corruption detected in cell %d on page %d",i,iPage);
57313       }else{
57314         for(j=pc+size-1; j>=pc; j--) hit[j]++;
57315       }
57316     }
57317     i = get2byte(&data[hdr+1]);
57318     while( i>0 ){
57319       int size, j;
57320       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
57321       size = get2byte(&data[i+2]);
57322       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
57323       for(j=i+size-1; j>=i; j--) hit[j]++;
57324       j = get2byte(&data[i]);
57325       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
57326       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
57327       i = j;
57328     }
57329     for(i=cnt=0; i<usableSize; i++){
57330       if( hit[i]==0 ){
57331         cnt++;
57332       }else if( hit[i]>1 ){
57333         checkAppendMsg(pCheck, 0,
57334           "Multiple uses for byte %d of page %d", i, iPage);
57335         break;
57336       }
57337     }
57338     if( cnt!=data[hdr+7] ){
57339       checkAppendMsg(pCheck, 0, 
57340           "Fragmentation of %d bytes reported as %d on page %d",
57341           cnt, data[hdr+7], iPage);
57342     }
57343   }
57344   sqlcipher3PageFree(hit);
57345   releasePage(pPage);
57346   return depth+1;
57347 }
57348 #endif /* SQLCIPHER_OMIT_INTEGRITY_CHECK */
57349
57350 #ifndef SQLCIPHER_OMIT_INTEGRITY_CHECK
57351 /*
57352 ** This routine does a complete check of the given BTree file.  aRoot[] is
57353 ** an array of pages numbers were each page number is the root page of
57354 ** a table.  nRoot is the number of entries in aRoot.
57355 **
57356 ** A read-only or read-write transaction must be opened before calling
57357 ** this function.
57358 **
57359 ** Write the number of error seen in *pnErr.  Except for some memory
57360 ** allocation errors,  an error message held in memory obtained from
57361 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
57362 ** returned.  If a memory allocation error occurs, NULL is returned.
57363 */
57364 SQLCIPHER_PRIVATE char *sqlcipher3BtreeIntegrityCheck(
57365   Btree *p,     /* The btree to be checked */
57366   int *aRoot,   /* An array of root pages numbers for individual trees */
57367   int nRoot,    /* Number of entries in aRoot[] */
57368   int mxErr,    /* Stop reporting errors after this many */
57369   int *pnErr    /* Write number of errors seen to this variable */
57370 ){
57371   Pgno i;
57372   int nRef;
57373   IntegrityCk sCheck;
57374   BtShared *pBt = p->pBt;
57375   char zErr[100];
57376
57377   sqlcipher3BtreeEnter(p);
57378   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
57379   nRef = sqlcipher3PagerRefcount(pBt->pPager);
57380   sCheck.pBt = pBt;
57381   sCheck.pPager = pBt->pPager;
57382   sCheck.nPage = btreePagecount(sCheck.pBt);
57383   sCheck.mxErr = mxErr;
57384   sCheck.nErr = 0;
57385   sCheck.mallocFailed = 0;
57386   *pnErr = 0;
57387   if( sCheck.nPage==0 ){
57388     sqlcipher3BtreeLeave(p);
57389     return 0;
57390   }
57391   sCheck.anRef = sqlcipher3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
57392   if( !sCheck.anRef ){
57393     *pnErr = 1;
57394     sqlcipher3BtreeLeave(p);
57395     return 0;
57396   }
57397   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
57398   i = PENDING_BYTE_PAGE(pBt);
57399   if( i<=sCheck.nPage ){
57400     sCheck.anRef[i] = 1;
57401   }
57402   sqlcipher3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
57403   sCheck.errMsg.useMalloc = 2;
57404
57405   /* Check the integrity of the freelist
57406   */
57407   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
57408             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
57409
57410   /* Check all the tables.
57411   */
57412   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
57413     if( aRoot[i]==0 ) continue;
57414 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57415     if( pBt->autoVacuum && aRoot[i]>1 ){
57416       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
57417     }
57418 #endif
57419     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
57420   }
57421
57422   /* Make sure every page in the file is referenced
57423   */
57424   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
57425 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
57426     if( sCheck.anRef[i]==0 ){
57427       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57428     }
57429 #else
57430     /* If the database supports auto-vacuum, make sure no tables contain
57431     ** references to pointer-map pages.
57432     */
57433     if( sCheck.anRef[i]==0 && 
57434        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
57435       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57436     }
57437     if( sCheck.anRef[i]!=0 && 
57438        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
57439       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
57440     }
57441 #endif
57442   }
57443
57444   /* Make sure this analysis did not leave any unref() pages.
57445   ** This is an internal consistency check; an integrity check
57446   ** of the integrity check.
57447   */
57448   if( NEVER(nRef != sqlcipher3PagerRefcount(pBt->pPager)) ){
57449     checkAppendMsg(&sCheck, 0, 
57450       "Outstanding page count goes from %d to %d during this analysis",
57451       nRef, sqlcipher3PagerRefcount(pBt->pPager)
57452     );
57453   }
57454
57455   /* Clean  up and report errors.
57456   */
57457   sqlcipher3BtreeLeave(p);
57458   sqlcipher3_free(sCheck.anRef);
57459   if( sCheck.mallocFailed ){
57460     sqlcipher3StrAccumReset(&sCheck.errMsg);
57461     *pnErr = sCheck.nErr+1;
57462     return 0;
57463   }
57464   *pnErr = sCheck.nErr;
57465   if( sCheck.nErr==0 ) sqlcipher3StrAccumReset(&sCheck.errMsg);
57466   return sqlcipher3StrAccumFinish(&sCheck.errMsg);
57467 }
57468 #endif /* SQLCIPHER_OMIT_INTEGRITY_CHECK */
57469
57470 /*
57471 ** Return the full pathname of the underlying database file.
57472 **
57473 ** The pager filename is invariant as long as the pager is
57474 ** open so it is safe to access without the BtShared mutex.
57475 */
57476 SQLCIPHER_PRIVATE const char *sqlcipher3BtreeGetFilename(Btree *p){
57477   assert( p->pBt->pPager!=0 );
57478   return sqlcipher3PagerFilename(p->pBt->pPager);
57479 }
57480
57481 /*
57482 ** Return the pathname of the journal file for this database. The return
57483 ** value of this routine is the same regardless of whether the journal file
57484 ** has been created or not.
57485 **
57486 ** The pager journal filename is invariant as long as the pager is
57487 ** open so it is safe to access without the BtShared mutex.
57488 */
57489 SQLCIPHER_PRIVATE const char *sqlcipher3BtreeGetJournalname(Btree *p){
57490   assert( p->pBt->pPager!=0 );
57491   return sqlcipher3PagerJournalname(p->pBt->pPager);
57492 }
57493
57494 /*
57495 ** Return non-zero if a transaction is active.
57496 */
57497 SQLCIPHER_PRIVATE int sqlcipher3BtreeIsInTrans(Btree *p){
57498   assert( p==0 || sqlcipher3_mutex_held(p->db->mutex) );
57499   return (p && (p->inTrans==TRANS_WRITE));
57500 }
57501
57502 #ifndef SQLCIPHER_OMIT_WAL
57503 /*
57504 ** Run a checkpoint on the Btree passed as the first argument.
57505 **
57506 ** Return SQLCIPHER_LOCKED if this or any other connection has an open 
57507 ** transaction on the shared-cache the argument Btree is connected to.
57508 **
57509 ** Parameter eMode is one of SQLCIPHER_CHECKPOINT_PASSIVE, FULL or RESTART.
57510 */
57511 SQLCIPHER_PRIVATE int sqlcipher3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
57512   int rc = SQLCIPHER_OK;
57513   if( p ){
57514     BtShared *pBt = p->pBt;
57515     sqlcipher3BtreeEnter(p);
57516     if( pBt->inTransaction!=TRANS_NONE ){
57517       rc = SQLCIPHER_LOCKED;
57518     }else{
57519       rc = sqlcipher3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
57520     }
57521     sqlcipher3BtreeLeave(p);
57522   }
57523   return rc;
57524 }
57525 #endif
57526
57527 /*
57528 ** Return non-zero if a read (or write) transaction is active.
57529 */
57530 SQLCIPHER_PRIVATE int sqlcipher3BtreeIsInReadTrans(Btree *p){
57531   assert( p );
57532   assert( sqlcipher3_mutex_held(p->db->mutex) );
57533   return p->inTrans!=TRANS_NONE;
57534 }
57535
57536 SQLCIPHER_PRIVATE int sqlcipher3BtreeIsInBackup(Btree *p){
57537   assert( p );
57538   assert( sqlcipher3_mutex_held(p->db->mutex) );
57539   return p->nBackup!=0;
57540 }
57541
57542 /*
57543 ** This function returns a pointer to a blob of memory associated with
57544 ** a single shared-btree. The memory is used by client code for its own
57545 ** purposes (for example, to store a high-level schema associated with 
57546 ** the shared-btree). The btree layer manages reference counting issues.
57547 **
57548 ** The first time this is called on a shared-btree, nBytes bytes of memory
57549 ** are allocated, zeroed, and returned to the caller. For each subsequent 
57550 ** call the nBytes parameter is ignored and a pointer to the same blob
57551 ** of memory returned. 
57552 **
57553 ** If the nBytes parameter is 0 and the blob of memory has not yet been
57554 ** allocated, a null pointer is returned. If the blob has already been
57555 ** allocated, it is returned as normal.
57556 **
57557 ** Just before the shared-btree is closed, the function passed as the 
57558 ** xFree argument when the memory allocation was made is invoked on the 
57559 ** blob of allocated memory. The xFree function should not call sqlcipher3_free()
57560 ** on the memory, the btree layer does that.
57561 */
57562 SQLCIPHER_PRIVATE void *sqlcipher3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
57563   BtShared *pBt = p->pBt;
57564   sqlcipher3BtreeEnter(p);
57565   if( !pBt->pSchema && nBytes ){
57566     pBt->pSchema = sqlcipher3DbMallocZero(0, nBytes);
57567     pBt->xFreeSchema = xFree;
57568   }
57569   sqlcipher3BtreeLeave(p);
57570   return pBt->pSchema;
57571 }
57572
57573 /*
57574 ** Return SQLCIPHER_LOCKED_SHAREDCACHE if another user of the same shared 
57575 ** btree as the argument handle holds an exclusive lock on the 
57576 ** sqlcipher_master table. Otherwise SQLCIPHER_OK.
57577 */
57578 SQLCIPHER_PRIVATE int sqlcipher3BtreeSchemaLocked(Btree *p){
57579   int rc;
57580   assert( sqlcipher3_mutex_held(p->db->mutex) );
57581   sqlcipher3BtreeEnter(p);
57582   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
57583   assert( rc==SQLCIPHER_OK || rc==SQLCIPHER_LOCKED_SHAREDCACHE );
57584   sqlcipher3BtreeLeave(p);
57585   return rc;
57586 }
57587
57588
57589 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
57590 /*
57591 ** Obtain a lock on the table whose root page is iTab.  The
57592 ** lock is a write lock if isWritelock is true or a read lock
57593 ** if it is false.
57594 */
57595 SQLCIPHER_PRIVATE int sqlcipher3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
57596   int rc = SQLCIPHER_OK;
57597   assert( p->inTrans!=TRANS_NONE );
57598   if( p->sharable ){
57599     u8 lockType = READ_LOCK + isWriteLock;
57600     assert( READ_LOCK+1==WRITE_LOCK );
57601     assert( isWriteLock==0 || isWriteLock==1 );
57602
57603     sqlcipher3BtreeEnter(p);
57604     rc = querySharedCacheTableLock(p, iTab, lockType);
57605     if( rc==SQLCIPHER_OK ){
57606       rc = setSharedCacheTableLock(p, iTab, lockType);
57607     }
57608     sqlcipher3BtreeLeave(p);
57609   }
57610   return rc;
57611 }
57612 #endif
57613
57614 #ifndef SQLCIPHER_OMIT_INCRBLOB
57615 /*
57616 ** Argument pCsr must be a cursor opened for writing on an 
57617 ** INTKEY table currently pointing at a valid table entry. 
57618 ** This function modifies the data stored as part of that entry.
57619 **
57620 ** Only the data content may only be modified, it is not possible to 
57621 ** change the length of the data stored. If this function is called with
57622 ** parameters that attempt to write past the end of the existing data,
57623 ** no modifications are made and SQLCIPHER_CORRUPT is returned.
57624 */
57625 SQLCIPHER_PRIVATE int sqlcipher3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
57626   int rc;
57627   assert( cursorHoldsMutex(pCsr) );
57628   assert( sqlcipher3_mutex_held(pCsr->pBtree->db->mutex) );
57629   assert( pCsr->isIncrblobHandle );
57630
57631   rc = restoreCursorPosition(pCsr);
57632   if( rc!=SQLCIPHER_OK ){
57633     return rc;
57634   }
57635   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
57636   if( pCsr->eState!=CURSOR_VALID ){
57637     return SQLCIPHER_ABORT;
57638   }
57639
57640   /* Check some assumptions: 
57641   **   (a) the cursor is open for writing,
57642   **   (b) there is a read/write transaction open,
57643   **   (c) the connection holds a write-lock on the table (if required),
57644   **   (d) there are no conflicting read-locks, and
57645   **   (e) the cursor points at a valid row of an intKey table.
57646   */
57647   if( !pCsr->wrFlag ){
57648     return SQLCIPHER_READONLY;
57649   }
57650   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
57651   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
57652   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
57653   assert( pCsr->apPage[pCsr->iPage]->intKey );
57654
57655   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
57656 }
57657
57658 /* 
57659 ** Set a flag on this cursor to cache the locations of pages from the 
57660 ** overflow list for the current row. This is used by cursors opened
57661 ** for incremental blob IO only.
57662 **
57663 ** This function sets a flag only. The actual page location cache
57664 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
57665 ** accessPayload() (the worker function for sqlcipher3BtreeData() and
57666 ** sqlcipher3BtreePutData()).
57667 */
57668 SQLCIPHER_PRIVATE void sqlcipher3BtreeCacheOverflow(BtCursor *pCur){
57669   assert( cursorHoldsMutex(pCur) );
57670   assert( sqlcipher3_mutex_held(pCur->pBtree->db->mutex) );
57671   invalidateOverflowCache(pCur);
57672   pCur->isIncrblobHandle = 1;
57673 }
57674 #endif
57675
57676 /*
57677 ** Set both the "read version" (single byte at byte offset 18) and 
57678 ** "write version" (single byte at byte offset 19) fields in the database
57679 ** header to iVersion.
57680 */
57681 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetVersion(Btree *pBtree, int iVersion){
57682   BtShared *pBt = pBtree->pBt;
57683   int rc;                         /* Return code */
57684  
57685   assert( iVersion==1 || iVersion==2 );
57686
57687   /* If setting the version fields to 1, do not automatically open the
57688   ** WAL connection, even if the version fields are currently set to 2.
57689   */
57690   pBt->doNotUseWAL = (u8)(iVersion==1);
57691
57692   rc = sqlcipher3BtreeBeginTrans(pBtree, 0);
57693   if( rc==SQLCIPHER_OK ){
57694     u8 *aData = pBt->pPage1->aData;
57695     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
57696       rc = sqlcipher3BtreeBeginTrans(pBtree, 2);
57697       if( rc==SQLCIPHER_OK ){
57698         rc = sqlcipher3PagerWrite(pBt->pPage1->pDbPage);
57699         if( rc==SQLCIPHER_OK ){
57700           aData[18] = (u8)iVersion;
57701           aData[19] = (u8)iVersion;
57702         }
57703       }
57704     }
57705   }
57706
57707   pBt->doNotUseWAL = 0;
57708   return rc;
57709 }
57710
57711 /************** End of btree.c ***********************************************/
57712 /************** Begin file backup.c ******************************************/
57713 /*
57714 ** 2009 January 28
57715 **
57716 ** The author disclaims copyright to this source code.  In place of
57717 ** a legal notice, here is a blessing:
57718 **
57719 **    May you do good and not evil.
57720 **    May you find forgiveness for yourself and forgive others.
57721 **    May you share freely, never taking more than you give.
57722 **
57723 *************************************************************************
57724 ** This file contains the implementation of the sqlcipher3_backup_XXX() 
57725 ** API functions and the related features.
57726 */
57727
57728 /* Macro to find the minimum of two numeric values.
57729 */
57730 #ifndef MIN
57731 # define MIN(x,y) ((x)<(y)?(x):(y))
57732 #endif
57733
57734 /*
57735 ** Structure allocated for each backup operation.
57736 */
57737 struct sqlcipher3_backup {
57738   sqlcipher3* pDestDb;        /* Destination database handle */
57739   Btree *pDest;            /* Destination b-tree file */
57740   u32 iDestSchema;         /* Original schema cookie in destination */
57741   int bDestLocked;         /* True once a write-transaction is open on pDest */
57742
57743   Pgno iNext;              /* Page number of the next source page to copy */
57744   sqlcipher3* pSrcDb;         /* Source database handle */
57745   Btree *pSrc;             /* Source b-tree file */
57746
57747   int rc;                  /* Backup process error code */
57748
57749   /* These two variables are set by every call to backup_step(). They are
57750   ** read by calls to backup_remaining() and backup_pagecount().
57751   */
57752   Pgno nRemaining;         /* Number of pages left to copy */
57753   Pgno nPagecount;         /* Total number of pages to copy */
57754
57755   int isAttached;          /* True once backup has been registered with pager */
57756   sqlcipher3_backup *pNext;   /* Next backup associated with source pager */
57757 };
57758
57759 /*
57760 ** THREAD SAFETY NOTES:
57761 **
57762 **   Once it has been created using backup_init(), a single sqlcipher3_backup
57763 **   structure may be accessed via two groups of thread-safe entry points:
57764 **
57765 **     * Via the sqlcipher3_backup_XXX() API function backup_step() and 
57766 **       backup_finish(). Both these functions obtain the source database
57767 **       handle mutex and the mutex associated with the source BtShared 
57768 **       structure, in that order.
57769 **
57770 **     * Via the BackupUpdate() and BackupRestart() functions, which are
57771 **       invoked by the pager layer to report various state changes in
57772 **       the page cache associated with the source database. The mutex
57773 **       associated with the source database BtShared structure will always 
57774 **       be held when either of these functions are invoked.
57775 **
57776 **   The other sqlcipher3_backup_XXX() API functions, backup_remaining() and
57777 **   backup_pagecount() are not thread-safe functions. If they are called
57778 **   while some other thread is calling backup_step() or backup_finish(),
57779 **   the values returned may be invalid. There is no way for a call to
57780 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
57781 **   or backup_pagecount().
57782 **
57783 **   Depending on the SQLite configuration, the database handles and/or
57784 **   the Btree objects may have their own mutexes that require locking.
57785 **   Non-sharable Btrees (in-memory databases for example), do not have
57786 **   associated mutexes.
57787 */
57788
57789 /*
57790 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
57791 ** in connection handle pDb. If such a database cannot be found, return
57792 ** a NULL pointer and write an error message to pErrorDb.
57793 **
57794 ** If the "temp" database is requested, it may need to be opened by this 
57795 ** function. If an error occurs while doing so, return 0 and write an 
57796 ** error message to pErrorDb.
57797 */
57798 static Btree *findBtree(sqlcipher3 *pErrorDb, sqlcipher3 *pDb, const char *zDb){
57799   int i = sqlcipher3FindDbName(pDb, zDb);
57800
57801   if( i==1 ){
57802     Parse *pParse;
57803     int rc = 0;
57804     pParse = sqlcipher3StackAllocZero(pErrorDb, sizeof(*pParse));
57805     if( pParse==0 ){
57806       sqlcipher3Error(pErrorDb, SQLCIPHER_NOMEM, "out of memory");
57807       rc = SQLCIPHER_NOMEM;
57808     }else{
57809       pParse->db = pDb;
57810       if( sqlcipher3OpenTempDatabase(pParse) ){
57811         sqlcipher3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
57812         rc = SQLCIPHER_ERROR;
57813       }
57814       sqlcipher3DbFree(pErrorDb, pParse->zErrMsg);
57815       sqlcipher3StackFree(pErrorDb, pParse);
57816     }
57817     if( rc ){
57818       return 0;
57819     }
57820   }
57821
57822   if( i<0 ){
57823     sqlcipher3Error(pErrorDb, SQLCIPHER_ERROR, "unknown database %s", zDb);
57824     return 0;
57825   }
57826
57827   return pDb->aDb[i].pBt;
57828 }
57829
57830 /*
57831 ** Attempt to set the page size of the destination to match the page size
57832 ** of the source.
57833 */
57834 static int setDestPgsz(sqlcipher3_backup *p){
57835   int rc;
57836   rc = sqlcipher3BtreeSetPageSize(p->pDest,sqlcipher3BtreeGetPageSize(p->pSrc),-1,0);
57837   return rc;
57838 }
57839
57840 /*
57841 ** Create an sqlcipher3_backup process to copy the contents of zSrcDb from
57842 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
57843 ** a pointer to the new sqlcipher3_backup object.
57844 **
57845 ** If an error occurs, NULL is returned and an error code and error message
57846 ** stored in database handle pDestDb.
57847 */
57848 SQLCIPHER_API sqlcipher3_backup *sqlcipher3_backup_init(
57849   sqlcipher3* pDestDb,                     /* Database to write to */
57850   const char *zDestDb,                  /* Name of database within pDestDb */
57851   sqlcipher3* pSrcDb,                      /* Database connection to read from */
57852   const char *zSrcDb                    /* Name of database within pSrcDb */
57853 ){
57854   sqlcipher3_backup *p;                    /* Value to return */
57855
57856   /* Lock the source database handle. The destination database
57857   ** handle is not locked in this routine, but it is locked in
57858   ** sqlcipher3_backup_step(). The user is required to ensure that no
57859   ** other thread accesses the destination handle for the duration
57860   ** of the backup operation.  Any attempt to use the destination
57861   ** database connection while a backup is in progress may cause
57862   ** a malfunction or a deadlock.
57863   */
57864   sqlcipher3_mutex_enter(pSrcDb->mutex);
57865   sqlcipher3_mutex_enter(pDestDb->mutex);
57866
57867   if( pSrcDb==pDestDb ){
57868     sqlcipher3Error(
57869         pDestDb, SQLCIPHER_ERROR, "source and destination must be distinct"
57870     );
57871     p = 0;
57872   }else {
57873     /* Allocate space for a new sqlcipher3_backup object...
57874     ** EVIDENCE-OF: R-64852-21591 The sqlcipher3_backup object is created by a
57875     ** call to sqlcipher3_backup_init() and is destroyed by a call to
57876     ** sqlcipher3_backup_finish(). */
57877     p = (sqlcipher3_backup *)sqlcipher3_malloc(sizeof(sqlcipher3_backup));
57878     if( !p ){
57879       sqlcipher3Error(pDestDb, SQLCIPHER_NOMEM, 0);
57880     }
57881   }
57882
57883   /* If the allocation succeeded, populate the new object. */
57884   if( p ){
57885     memset(p, 0, sizeof(sqlcipher3_backup));
57886     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
57887     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
57888     p->pDestDb = pDestDb;
57889     p->pSrcDb = pSrcDb;
57890     p->iNext = 1;
57891     p->isAttached = 0;
57892
57893     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLCIPHER_NOMEM ){
57894       /* One (or both) of the named databases did not exist or an OOM
57895       ** error was hit.  The error has already been written into the
57896       ** pDestDb handle.  All that is left to do here is free the
57897       ** sqlcipher3_backup structure.
57898       */
57899       sqlcipher3_free(p);
57900       p = 0;
57901     }
57902   }
57903   if( p ){
57904     p->pSrc->nBackup++;
57905   }
57906
57907   sqlcipher3_mutex_leave(pDestDb->mutex);
57908   sqlcipher3_mutex_leave(pSrcDb->mutex);
57909   return p;
57910 }
57911
57912 /*
57913 ** Argument rc is an SQLite error code. Return true if this error is 
57914 ** considered fatal if encountered during a backup operation. All errors
57915 ** are considered fatal except for SQLCIPHER_BUSY and SQLCIPHER_LOCKED.
57916 */
57917 static int isFatalError(int rc){
57918   return (rc!=SQLCIPHER_OK && rc!=SQLCIPHER_BUSY && ALWAYS(rc!=SQLCIPHER_LOCKED));
57919 }
57920
57921 /*
57922 ** Parameter zSrcData points to a buffer containing the data for 
57923 ** page iSrcPg from the source database. Copy this data into the 
57924 ** destination database.
57925 */
57926 static int backupOnePage(sqlcipher3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
57927   Pager * const pDestPager = sqlcipher3BtreePager(p->pDest);
57928   const int nSrcPgsz = sqlcipher3BtreeGetPageSize(p->pSrc);
57929   int nDestPgsz = sqlcipher3BtreeGetPageSize(p->pDest);
57930   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
57931   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
57932 #ifdef SQLCIPHER_HAS_CODEC
57933   int nSrcReserve = sqlcipher3BtreeGetReserve(p->pSrc);
57934   int nDestReserve = sqlcipher3BtreeGetReserve(p->pDest);
57935 #endif
57936
57937   int rc = SQLCIPHER_OK;
57938   i64 iOff;
57939
57940   assert( p->bDestLocked );
57941   assert( !isFatalError(p->rc) );
57942   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
57943   assert( zSrcData );
57944
57945   /* Catch the case where the destination is an in-memory database and the
57946   ** page sizes of the source and destination differ. 
57947   */
57948   if( nSrcPgsz!=nDestPgsz && sqlcipher3PagerIsMemdb(pDestPager) ){
57949     rc = SQLCIPHER_READONLY;
57950   }
57951
57952 #ifdef SQLCIPHER_HAS_CODEC
57953   /* Backup is not possible if the page size of the destination is changing
57954   ** and a codec is in use.
57955   */
57956   if( nSrcPgsz!=nDestPgsz && sqlcipher3PagerGetCodec(pDestPager)!=0 ){
57957     rc = SQLCIPHER_READONLY;
57958   }
57959
57960   /* Backup is not possible if the number of bytes of reserve space differ
57961   ** between source and destination.  If there is a difference, try to
57962   ** fix the destination to agree with the source.  If that is not possible,
57963   ** then the backup cannot proceed.
57964   */
57965   if( nSrcReserve!=nDestReserve ){
57966     u32 newPgsz = nSrcPgsz;
57967     rc = sqlcipher3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
57968     if( rc==SQLCIPHER_OK && (int)newPgsz!=nSrcPgsz ) rc = SQLCIPHER_READONLY;
57969   }
57970 #endif
57971
57972   /* This loop runs once for each destination page spanned by the source 
57973   ** page. For each iteration, variable iOff is set to the byte offset
57974   ** of the destination page.
57975   */
57976   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLCIPHER_OK && iOff<iEnd; iOff+=nDestPgsz){
57977     DbPage *pDestPg = 0;
57978     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
57979     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
57980     if( SQLCIPHER_OK==(rc = sqlcipher3PagerGet(pDestPager, iDest, &pDestPg))
57981      && SQLCIPHER_OK==(rc = sqlcipher3PagerWrite(pDestPg))
57982     ){
57983       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
57984       u8 *zDestData = sqlcipher3PagerGetData(pDestPg);
57985       u8 *zOut = &zDestData[iOff%nDestPgsz];
57986
57987       /* Copy the data from the source page into the destination page.
57988       ** Then clear the Btree layer MemPage.isInit flag. Both this module
57989       ** and the pager code use this trick (clearing the first byte
57990       ** of the page 'extra' space to invalidate the Btree layers
57991       ** cached parse of the page). MemPage.isInit is marked 
57992       ** "MUST BE FIRST" for this purpose.
57993       */
57994       memcpy(zOut, zIn, nCopy);
57995       ((u8 *)sqlcipher3PagerGetExtra(pDestPg))[0] = 0;
57996     }
57997     sqlcipher3PagerUnref(pDestPg);
57998   }
57999
58000   return rc;
58001 }
58002
58003 /*
58004 ** If pFile is currently larger than iSize bytes, then truncate it to
58005 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
58006 ** this function is a no-op.
58007 **
58008 ** Return SQLCIPHER_OK if everything is successful, or an SQLite error 
58009 ** code if an error occurs.
58010 */
58011 static int backupTruncateFile(sqlcipher3_file *pFile, i64 iSize){
58012   i64 iCurrent;
58013   int rc = sqlcipher3OsFileSize(pFile, &iCurrent);
58014   if( rc==SQLCIPHER_OK && iCurrent>iSize ){
58015     rc = sqlcipher3OsTruncate(pFile, iSize);
58016   }
58017   return rc;
58018 }
58019
58020 /*
58021 ** Register this backup object with the associated source pager for
58022 ** callbacks when pages are changed or the cache invalidated.
58023 */
58024 static void attachBackupObject(sqlcipher3_backup *p){
58025   sqlcipher3_backup **pp;
58026   assert( sqlcipher3BtreeHoldsMutex(p->pSrc) );
58027   pp = sqlcipher3PagerBackupPtr(sqlcipher3BtreePager(p->pSrc));
58028   p->pNext = *pp;
58029   *pp = p;
58030   p->isAttached = 1;
58031 }
58032
58033 /*
58034 ** Copy nPage pages from the source b-tree to the destination.
58035 */
58036 SQLCIPHER_API int sqlcipher3_backup_step(sqlcipher3_backup *p, int nPage){
58037   int rc;
58038   int destMode;       /* Destination journal mode */
58039   int pgszSrc = 0;    /* Source page size */
58040   int pgszDest = 0;   /* Destination page size */
58041
58042   sqlcipher3_mutex_enter(p->pSrcDb->mutex);
58043   sqlcipher3BtreeEnter(p->pSrc);
58044   if( p->pDestDb ){
58045     sqlcipher3_mutex_enter(p->pDestDb->mutex);
58046   }
58047
58048   rc = p->rc;
58049   if( !isFatalError(rc) ){
58050     Pager * const pSrcPager = sqlcipher3BtreePager(p->pSrc);     /* Source pager */
58051     Pager * const pDestPager = sqlcipher3BtreePager(p->pDest);   /* Dest pager */
58052     int ii;                            /* Iterator variable */
58053     int nSrcPage = -1;                 /* Size of source db in pages */
58054     int bCloseTrans = 0;               /* True if src db requires unlocking */
58055
58056     /* If the source pager is currently in a write-transaction, return
58057     ** SQLCIPHER_BUSY immediately.
58058     */
58059     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
58060       rc = SQLCIPHER_BUSY;
58061     }else{
58062       rc = SQLCIPHER_OK;
58063     }
58064
58065     /* Lock the destination database, if it is not locked already. */
58066     if( SQLCIPHER_OK==rc && p->bDestLocked==0
58067      && SQLCIPHER_OK==(rc = sqlcipher3BtreeBeginTrans(p->pDest, 2)) 
58068     ){
58069       p->bDestLocked = 1;
58070       sqlcipher3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
58071     }
58072
58073     /* If there is no open read-transaction on the source database, open
58074     ** one now. If a transaction is opened here, then it will be closed
58075     ** before this function exits.
58076     */
58077     if( rc==SQLCIPHER_OK && 0==sqlcipher3BtreeIsInReadTrans(p->pSrc) ){
58078       rc = sqlcipher3BtreeBeginTrans(p->pSrc, 0);
58079       bCloseTrans = 1;
58080     }
58081
58082     /* Do not allow backup if the destination database is in WAL mode
58083     ** and the page sizes are different between source and destination */
58084     pgszSrc = sqlcipher3BtreeGetPageSize(p->pSrc);
58085     pgszDest = sqlcipher3BtreeGetPageSize(p->pDest);
58086     destMode = sqlcipher3PagerGetJournalMode(sqlcipher3BtreePager(p->pDest));
58087     if( SQLCIPHER_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
58088       rc = SQLCIPHER_READONLY;
58089     }
58090   
58091     /* Now that there is a read-lock on the source database, query the
58092     ** source pager for the number of pages in the database.
58093     */
58094     nSrcPage = (int)sqlcipher3BtreeLastPage(p->pSrc);
58095     assert( nSrcPage>=0 );
58096     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
58097       const Pgno iSrcPg = p->iNext;                 /* Source page number */
58098       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
58099         DbPage *pSrcPg;                             /* Source page object */
58100         rc = sqlcipher3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58101         if( rc==SQLCIPHER_OK ){
58102           rc = backupOnePage(p, iSrcPg, sqlcipher3PagerGetData(pSrcPg));
58103           sqlcipher3PagerUnref(pSrcPg);
58104         }
58105       }
58106       p->iNext++;
58107     }
58108     if( rc==SQLCIPHER_OK ){
58109       p->nPagecount = nSrcPage;
58110       p->nRemaining = nSrcPage+1-p->iNext;
58111       if( p->iNext>(Pgno)nSrcPage ){
58112         rc = SQLCIPHER_DONE;
58113       }else if( !p->isAttached ){
58114         attachBackupObject(p);
58115       }
58116     }
58117   
58118     /* Update the schema version field in the destination database. This
58119     ** is to make sure that the schema-version really does change in
58120     ** the case where the source and destination databases have the
58121     ** same schema version.
58122     */
58123     if( rc==SQLCIPHER_DONE ){
58124       rc = sqlcipher3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
58125       if( rc==SQLCIPHER_OK ){
58126         if( p->pDestDb ){
58127           sqlcipher3ResetInternalSchema(p->pDestDb, -1);
58128         }
58129         if( destMode==PAGER_JOURNALMODE_WAL ){
58130           rc = sqlcipher3BtreeSetVersion(p->pDest, 2);
58131         }
58132       }
58133       if( rc==SQLCIPHER_OK ){
58134         int nDestTruncate;
58135         /* Set nDestTruncate to the final number of pages in the destination
58136         ** database. The complication here is that the destination page
58137         ** size may be different to the source page size. 
58138         **
58139         ** If the source page size is smaller than the destination page size, 
58140         ** round up. In this case the call to sqlcipher3OsTruncate() below will
58141         ** fix the size of the file. However it is important to call
58142         ** sqlcipher3PagerTruncateImage() here so that any pages in the 
58143         ** destination file that lie beyond the nDestTruncate page mark are
58144         ** journalled by PagerCommitPhaseOne() before they are destroyed
58145         ** by the file truncation.
58146         */
58147         assert( pgszSrc==sqlcipher3BtreeGetPageSize(p->pSrc) );
58148         assert( pgszDest==sqlcipher3BtreeGetPageSize(p->pDest) );
58149         if( pgszSrc<pgszDest ){
58150           int ratio = pgszDest/pgszSrc;
58151           nDestTruncate = (nSrcPage+ratio-1)/ratio;
58152           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
58153             nDestTruncate--;
58154           }
58155         }else{
58156           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
58157         }
58158         sqlcipher3PagerTruncateImage(pDestPager, nDestTruncate);
58159
58160         if( pgszSrc<pgszDest ){
58161           /* If the source page-size is smaller than the destination page-size,
58162           ** two extra things may need to happen:
58163           **
58164           **   * The destination may need to be truncated, and
58165           **
58166           **   * Data stored on the pages immediately following the 
58167           **     pending-byte page in the source database may need to be
58168           **     copied into the destination database.
58169           */
58170           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
58171           sqlcipher3_file * const pFile = sqlcipher3PagerFile(pDestPager);
58172           i64 iOff;
58173           i64 iEnd;
58174
58175           assert( pFile );
58176           assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
58177                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
58178              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
58179           ));
58180
58181           /* This call ensures that all data required to recreate the original
58182           ** database has been stored in the journal for pDestPager and the
58183           ** journal synced to disk. So at this point we may safely modify
58184           ** the database file in any way, knowing that if a power failure
58185           ** occurs, the original database will be reconstructed from the 
58186           ** journal file.  */
58187           rc = sqlcipher3PagerCommitPhaseOne(pDestPager, 0, 1);
58188
58189           /* Write the extra pages and truncate the database file as required */
58190           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
58191           for(
58192             iOff=PENDING_BYTE+pgszSrc; 
58193             rc==SQLCIPHER_OK && iOff<iEnd; 
58194             iOff+=pgszSrc
58195           ){
58196             PgHdr *pSrcPg = 0;
58197             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
58198             rc = sqlcipher3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58199             if( rc==SQLCIPHER_OK ){
58200               u8 *zData = sqlcipher3PagerGetData(pSrcPg);
58201               rc = sqlcipher3OsWrite(pFile, zData, pgszSrc, iOff);
58202             }
58203             sqlcipher3PagerUnref(pSrcPg);
58204           }
58205           if( rc==SQLCIPHER_OK ){
58206             rc = backupTruncateFile(pFile, iSize);
58207           }
58208
58209           /* Sync the database file to disk. */
58210           if( rc==SQLCIPHER_OK ){
58211             rc = sqlcipher3PagerSync(pDestPager);
58212           }
58213         }else{
58214           rc = sqlcipher3PagerCommitPhaseOne(pDestPager, 0, 0);
58215         }
58216     
58217         /* Finish committing the transaction to the destination database. */
58218         if( SQLCIPHER_OK==rc
58219          && SQLCIPHER_OK==(rc = sqlcipher3BtreeCommitPhaseTwo(p->pDest, 0))
58220         ){
58221           rc = SQLCIPHER_DONE;
58222         }
58223       }
58224     }
58225   
58226     /* If bCloseTrans is true, then this function opened a read transaction
58227     ** on the source database. Close the read transaction here. There is
58228     ** no need to check the return values of the btree methods here, as
58229     ** "committing" a read-only transaction cannot fail.
58230     */
58231     if( bCloseTrans ){
58232       TESTONLY( int rc2 );
58233       TESTONLY( rc2  = ) sqlcipher3BtreeCommitPhaseOne(p->pSrc, 0);
58234       TESTONLY( rc2 |= ) sqlcipher3BtreeCommitPhaseTwo(p->pSrc, 0);
58235       assert( rc2==SQLCIPHER_OK );
58236     }
58237   
58238     if( rc==SQLCIPHER_IOERR_NOMEM ){
58239       rc = SQLCIPHER_NOMEM;
58240     }
58241     p->rc = rc;
58242   }
58243   if( p->pDestDb ){
58244     sqlcipher3_mutex_leave(p->pDestDb->mutex);
58245   }
58246   sqlcipher3BtreeLeave(p->pSrc);
58247   sqlcipher3_mutex_leave(p->pSrcDb->mutex);
58248   return rc;
58249 }
58250
58251 /*
58252 ** Release all resources associated with an sqlcipher3_backup* handle.
58253 */
58254 SQLCIPHER_API int sqlcipher3_backup_finish(sqlcipher3_backup *p){
58255   sqlcipher3_backup **pp;                 /* Ptr to head of pagers backup list */
58256   MUTEX_LOGIC( sqlcipher3_mutex *mutex; ) /* Mutex to protect source database */
58257   int rc;                              /* Value to return */
58258
58259   /* Enter the mutexes */
58260   if( p==0 ) return SQLCIPHER_OK;
58261   sqlcipher3_mutex_enter(p->pSrcDb->mutex);
58262   sqlcipher3BtreeEnter(p->pSrc);
58263   MUTEX_LOGIC( mutex = p->pSrcDb->mutex; )
58264   if( p->pDestDb ){
58265     sqlcipher3_mutex_enter(p->pDestDb->mutex);
58266   }
58267
58268   /* Detach this backup from the source pager. */
58269   if( p->pDestDb ){
58270     p->pSrc->nBackup--;
58271   }
58272   if( p->isAttached ){
58273     pp = sqlcipher3PagerBackupPtr(sqlcipher3BtreePager(p->pSrc));
58274     while( *pp!=p ){
58275       pp = &(*pp)->pNext;
58276     }
58277     *pp = p->pNext;
58278   }
58279
58280   /* If a transaction is still open on the Btree, roll it back. */
58281   sqlcipher3BtreeRollback(p->pDest);
58282
58283   /* Set the error code of the destination database handle. */
58284   rc = (p->rc==SQLCIPHER_DONE) ? SQLCIPHER_OK : p->rc;
58285   sqlcipher3Error(p->pDestDb, rc, 0);
58286
58287   /* Exit the mutexes and free the backup context structure. */
58288   if( p->pDestDb ){
58289     sqlcipher3_mutex_leave(p->pDestDb->mutex);
58290   }
58291   sqlcipher3BtreeLeave(p->pSrc);
58292   if( p->pDestDb ){
58293     /* EVIDENCE-OF: R-64852-21591 The sqlcipher3_backup object is created by a
58294     ** call to sqlcipher3_backup_init() and is destroyed by a call to
58295     ** sqlcipher3_backup_finish(). */
58296     sqlcipher3_free(p);
58297   }
58298   sqlcipher3_mutex_leave(mutex);
58299   return rc;
58300 }
58301
58302 /*
58303 ** Return the number of pages still to be backed up as of the most recent
58304 ** call to sqlcipher3_backup_step().
58305 */
58306 SQLCIPHER_API int sqlcipher3_backup_remaining(sqlcipher3_backup *p){
58307   return p->nRemaining;
58308 }
58309
58310 /*
58311 ** Return the total number of pages in the source database as of the most 
58312 ** recent call to sqlcipher3_backup_step().
58313 */
58314 SQLCIPHER_API int sqlcipher3_backup_pagecount(sqlcipher3_backup *p){
58315   return p->nPagecount;
58316 }
58317
58318 /*
58319 ** This function is called after the contents of page iPage of the
58320 ** source database have been modified. If page iPage has already been 
58321 ** copied into the destination database, then the data written to the
58322 ** destination is now invalidated. The destination copy of iPage needs
58323 ** to be updated with the new data before the backup operation is
58324 ** complete.
58325 **
58326 ** It is assumed that the mutex associated with the BtShared object
58327 ** corresponding to the source database is held when this function is
58328 ** called.
58329 */
58330 SQLCIPHER_PRIVATE void sqlcipher3BackupUpdate(sqlcipher3_backup *pBackup, Pgno iPage, const u8 *aData){
58331   sqlcipher3_backup *p;                   /* Iterator variable */
58332   for(p=pBackup; p; p=p->pNext){
58333     assert( sqlcipher3_mutex_held(p->pSrc->pBt->mutex) );
58334     if( !isFatalError(p->rc) && iPage<p->iNext ){
58335       /* The backup process p has already copied page iPage. But now it
58336       ** has been modified by a transaction on the source pager. Copy
58337       ** the new data into the backup.
58338       */
58339       int rc;
58340       assert( p->pDestDb );
58341       sqlcipher3_mutex_enter(p->pDestDb->mutex);
58342       rc = backupOnePage(p, iPage, aData);
58343       sqlcipher3_mutex_leave(p->pDestDb->mutex);
58344       assert( rc!=SQLCIPHER_BUSY && rc!=SQLCIPHER_LOCKED );
58345       if( rc!=SQLCIPHER_OK ){
58346         p->rc = rc;
58347       }
58348     }
58349   }
58350 }
58351
58352 /*
58353 ** Restart the backup process. This is called when the pager layer
58354 ** detects that the database has been modified by an external database
58355 ** connection. In this case there is no way of knowing which of the
58356 ** pages that have been copied into the destination database are still 
58357 ** valid and which are not, so the entire process needs to be restarted.
58358 **
58359 ** It is assumed that the mutex associated with the BtShared object
58360 ** corresponding to the source database is held when this function is
58361 ** called.
58362 */
58363 SQLCIPHER_PRIVATE void sqlcipher3BackupRestart(sqlcipher3_backup *pBackup){
58364   sqlcipher3_backup *p;                   /* Iterator variable */
58365   for(p=pBackup; p; p=p->pNext){
58366     assert( sqlcipher3_mutex_held(p->pSrc->pBt->mutex) );
58367     p->iNext = 1;
58368   }
58369 }
58370
58371 #ifndef SQLCIPHER_OMIT_VACUUM
58372 /*
58373 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
58374 ** must be active for both files.
58375 **
58376 ** The size of file pTo may be reduced by this operation. If anything 
58377 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
58378 ** transaction is committed before returning.
58379 */
58380 SQLCIPHER_PRIVATE int sqlcipher3BtreeCopyFile(Btree *pTo, Btree *pFrom){
58381   int rc;
58382   sqlcipher3_file *pFd;              /* File descriptor for database pTo */
58383   sqlcipher3_backup b;
58384   sqlcipher3BtreeEnter(pTo);
58385   sqlcipher3BtreeEnter(pFrom);
58386
58387   assert( sqlcipher3BtreeIsInTrans(pTo) );
58388   pFd = sqlcipher3PagerFile(sqlcipher3BtreePager(pTo));
58389   if( pFd->pMethods ){
58390     i64 nByte = sqlcipher3BtreeGetPageSize(pFrom)*(i64)sqlcipher3BtreeLastPage(pFrom);
58391     sqlcipher3OsFileControl(pFd, SQLCIPHER_FCNTL_OVERWRITE, &nByte);
58392   }
58393
58394   /* Set up an sqlcipher3_backup object. sqlcipher3_backup.pDestDb must be set
58395   ** to 0. This is used by the implementations of sqlcipher3_backup_step()
58396   ** and sqlcipher3_backup_finish() to detect that they are being called
58397   ** from this function, not directly by the user.
58398   */
58399   memset(&b, 0, sizeof(b));
58400   b.pSrcDb = pFrom->db;
58401   b.pSrc = pFrom;
58402   b.pDest = pTo;
58403   b.iNext = 1;
58404
58405   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
58406   ** file. By passing this as the number of pages to copy to
58407   ** sqlcipher3_backup_step(), we can guarantee that the copy finishes 
58408   ** within a single call (unless an error occurs). The assert() statement
58409   ** checks this assumption - (p->rc) should be set to either SQLCIPHER_DONE 
58410   ** or an error code.
58411   */
58412   sqlcipher3_backup_step(&b, 0x7FFFFFFF);
58413   assert( b.rc!=SQLCIPHER_OK );
58414   rc = sqlcipher3_backup_finish(&b);
58415   if( rc==SQLCIPHER_OK ){
58416     pTo->pBt->pageSizeFixed = 0;
58417   }else{
58418     sqlcipher3PagerClearCache(sqlcipher3BtreePager(b.pDest));
58419   }
58420
58421   assert( sqlcipher3BtreeIsInTrans(pTo)==0 );
58422   sqlcipher3BtreeLeave(pFrom);
58423   sqlcipher3BtreeLeave(pTo);
58424   return rc;
58425 }
58426 #endif /* SQLCIPHER_OMIT_VACUUM */
58427
58428 /************** End of backup.c **********************************************/
58429 /************** Begin file vdbemem.c *****************************************/
58430 /*
58431 ** 2004 May 26
58432 **
58433 ** The author disclaims copyright to this source code.  In place of
58434 ** a legal notice, here is a blessing:
58435 **
58436 **    May you do good and not evil.
58437 **    May you find forgiveness for yourself and forgive others.
58438 **    May you share freely, never taking more than you give.
58439 **
58440 *************************************************************************
58441 **
58442 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
58443 ** stores a single value in the VDBE.  Mem is an opaque structure visible
58444 ** only within the VDBE.  Interface routines refer to a Mem using the
58445 ** name sqlcipher_value
58446 */
58447
58448 /*
58449 ** Call sqlcipher3VdbeMemExpandBlob() on the supplied value (type Mem*)
58450 ** P if required.
58451 */
58452 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlcipher3VdbeMemExpandBlob(P):0)
58453
58454 /*
58455 ** If pMem is an object with a valid string representation, this routine
58456 ** ensures the internal encoding for the string representation is
58457 ** 'desiredEnc', one of SQLCIPHER_UTF8, SQLCIPHER_UTF16LE or SQLCIPHER_UTF16BE.
58458 **
58459 ** If pMem is not a string object, or the encoding of the string
58460 ** representation is already stored using the requested encoding, then this
58461 ** routine is a no-op.
58462 **
58463 ** SQLCIPHER_OK is returned if the conversion is successful (or not required).
58464 ** SQLCIPHER_NOMEM may be returned if a malloc() fails during conversion
58465 ** between formats.
58466 */
58467 SQLCIPHER_PRIVATE int sqlcipher3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
58468   int rc;
58469   assert( (pMem->flags&MEM_RowSet)==0 );
58470   assert( desiredEnc==SQLCIPHER_UTF8 || desiredEnc==SQLCIPHER_UTF16LE
58471            || desiredEnc==SQLCIPHER_UTF16BE );
58472   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
58473     return SQLCIPHER_OK;
58474   }
58475   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58476 #ifdef SQLCIPHER_OMIT_UTF16
58477   return SQLCIPHER_ERROR;
58478 #else
58479
58480   /* MemTranslate() may return SQLCIPHER_OK or SQLCIPHER_NOMEM. If NOMEM is returned,
58481   ** then the encoding of the value may not have changed.
58482   */
58483   rc = sqlcipher3VdbeMemTranslate(pMem, (u8)desiredEnc);
58484   assert(rc==SQLCIPHER_OK    || rc==SQLCIPHER_NOMEM);
58485   assert(rc==SQLCIPHER_OK    || pMem->enc!=desiredEnc);
58486   assert(rc==SQLCIPHER_NOMEM || pMem->enc==desiredEnc);
58487   return rc;
58488 #endif
58489 }
58490
58491 /*
58492 ** Make sure pMem->z points to a writable allocation of at least 
58493 ** n bytes.
58494 **
58495 ** If the memory cell currently contains string or blob data
58496 ** and the third argument passed to this function is true, the 
58497 ** current content of the cell is preserved. Otherwise, it may
58498 ** be discarded.  
58499 **
58500 ** This function sets the MEM_Dyn flag and clears any xDel callback.
58501 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
58502 ** not set, Mem.n is zeroed.
58503 */
58504 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemGrow(Mem *pMem, int n, int preserve){
58505   assert( 1 >=
58506     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
58507     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
58508     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
58509     ((pMem->flags&MEM_Static) ? 1 : 0)
58510   );
58511   assert( (pMem->flags&MEM_RowSet)==0 );
58512
58513   if( n<32 ) n = 32;
58514   if( sqlcipher3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
58515     if( preserve && pMem->z==pMem->zMalloc ){
58516       pMem->z = pMem->zMalloc = sqlcipher3DbReallocOrFree(pMem->db, pMem->z, n);
58517       preserve = 0;
58518     }else{
58519       sqlcipher3DbFree(pMem->db, pMem->zMalloc);
58520       pMem->zMalloc = sqlcipher3DbMallocRaw(pMem->db, n);
58521     }
58522   }
58523
58524   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
58525     memcpy(pMem->zMalloc, pMem->z, pMem->n);
58526   }
58527   if( pMem->flags&MEM_Dyn && pMem->xDel ){
58528     pMem->xDel((void *)(pMem->z));
58529   }
58530
58531   pMem->z = pMem->zMalloc;
58532   if( pMem->z==0 ){
58533     pMem->flags = MEM_Null;
58534   }else{
58535     pMem->flags &= ~(MEM_Ephem|MEM_Static);
58536   }
58537   pMem->xDel = 0;
58538   return (pMem->z ? SQLCIPHER_OK : SQLCIPHER_NOMEM);
58539 }
58540
58541 /*
58542 ** Make the given Mem object MEM_Dyn.  In other words, make it so
58543 ** that any TEXT or BLOB content is stored in memory obtained from
58544 ** malloc().  In this way, we know that the memory is safe to be
58545 ** overwritten or altered.
58546 **
58547 ** Return SQLCIPHER_OK on success or SQLCIPHER_NOMEM if malloc fails.
58548 */
58549 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemMakeWriteable(Mem *pMem){
58550   int f;
58551   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58552   assert( (pMem->flags&MEM_RowSet)==0 );
58553   expandBlob(pMem);
58554   f = pMem->flags;
58555   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
58556     if( sqlcipher3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
58557       return SQLCIPHER_NOMEM;
58558     }
58559     pMem->z[pMem->n] = 0;
58560     pMem->z[pMem->n+1] = 0;
58561     pMem->flags |= MEM_Term;
58562 #ifdef SQLCIPHER_DEBUG
58563     pMem->pScopyFrom = 0;
58564 #endif
58565   }
58566
58567   return SQLCIPHER_OK;
58568 }
58569
58570 /*
58571 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
58572 ** blob stored in dynamically allocated space.
58573 */
58574 #ifndef SQLCIPHER_OMIT_INCRBLOB
58575 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemExpandBlob(Mem *pMem){
58576   if( pMem->flags & MEM_Zero ){
58577     int nByte;
58578     assert( pMem->flags&MEM_Blob );
58579     assert( (pMem->flags&MEM_RowSet)==0 );
58580     assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58581
58582     /* Set nByte to the number of bytes required to store the expanded blob. */
58583     nByte = pMem->n + pMem->u.nZero;
58584     if( nByte<=0 ){
58585       nByte = 1;
58586     }
58587     if( sqlcipher3VdbeMemGrow(pMem, nByte, 1) ){
58588       return SQLCIPHER_NOMEM;
58589     }
58590
58591     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
58592     pMem->n += pMem->u.nZero;
58593     pMem->flags &= ~(MEM_Zero|MEM_Term);
58594   }
58595   return SQLCIPHER_OK;
58596 }
58597 #endif
58598
58599
58600 /*
58601 ** Make sure the given Mem is \u0000 terminated.
58602 */
58603 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemNulTerminate(Mem *pMem){
58604   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58605   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
58606     return SQLCIPHER_OK;   /* Nothing to do */
58607   }
58608   if( sqlcipher3VdbeMemGrow(pMem, pMem->n+2, 1) ){
58609     return SQLCIPHER_NOMEM;
58610   }
58611   pMem->z[pMem->n] = 0;
58612   pMem->z[pMem->n+1] = 0;
58613   pMem->flags |= MEM_Term;
58614   return SQLCIPHER_OK;
58615 }
58616
58617 /*
58618 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
58619 ** are converted using sqlcipher3_snprintf().  Converting a BLOB to a string
58620 ** is a no-op.
58621 **
58622 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
58623 **
58624 ** A MEM_Null value will never be passed to this function. This function is
58625 ** used for converting values to text for returning to the user (i.e. via
58626 ** sqlcipher3_value_text()), or for ensuring that values to be used as btree
58627 ** keys are strings. In the former case a NULL pointer is returned the
58628 ** user and the later is an internal programming error.
58629 */
58630 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemStringify(Mem *pMem, int enc){
58631   int rc = SQLCIPHER_OK;
58632   int fg = pMem->flags;
58633   const int nByte = 32;
58634
58635   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58636   assert( !(fg&MEM_Zero) );
58637   assert( !(fg&(MEM_Str|MEM_Blob)) );
58638   assert( fg&(MEM_Int|MEM_Real) );
58639   assert( (pMem->flags&MEM_RowSet)==0 );
58640   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58641
58642
58643   if( sqlcipher3VdbeMemGrow(pMem, nByte, 0) ){
58644     return SQLCIPHER_NOMEM;
58645   }
58646
58647   /* For a Real or Integer, use sqlcipher3_mprintf() to produce the UTF-8
58648   ** string representation of the value. Then, if the required encoding
58649   ** is UTF-16le or UTF-16be do a translation.
58650   ** 
58651   ** FIX ME: It would be better if sqlcipher3_snprintf() could do UTF-16.
58652   */
58653   if( fg & MEM_Int ){
58654     sqlcipher3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
58655   }else{
58656     assert( fg & MEM_Real );
58657     sqlcipher3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
58658   }
58659   pMem->n = sqlcipher3Strlen30(pMem->z);
58660   pMem->enc = SQLCIPHER_UTF8;
58661   pMem->flags |= MEM_Str|MEM_Term;
58662   sqlcipher3VdbeChangeEncoding(pMem, enc);
58663   return rc;
58664 }
58665
58666 /*
58667 ** Memory cell pMem contains the context of an aggregate function.
58668 ** This routine calls the finalize method for that function.  The
58669 ** result of the aggregate is stored back into pMem.
58670 **
58671 ** Return SQLCIPHER_ERROR if the finalizer reports an error.  SQLCIPHER_OK
58672 ** otherwise.
58673 */
58674 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
58675   int rc = SQLCIPHER_OK;
58676   if( ALWAYS(pFunc && pFunc->xFinalize) ){
58677     sqlcipher3_context ctx;
58678     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
58679     assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58680     memset(&ctx, 0, sizeof(ctx));
58681     ctx.s.flags = MEM_Null;
58682     ctx.s.db = pMem->db;
58683     ctx.pMem = pMem;
58684     ctx.pFunc = pFunc;
58685     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
58686     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
58687     sqlcipher3DbFree(pMem->db, pMem->zMalloc);
58688     memcpy(pMem, &ctx.s, sizeof(ctx.s));
58689     rc = ctx.isError;
58690   }
58691   return rc;
58692 }
58693
58694 /*
58695 ** If the memory cell contains a string value that must be freed by
58696 ** invoking an external callback, free it now. Calling this function
58697 ** does not free any Mem.zMalloc buffer.
58698 */
58699 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemReleaseExternal(Mem *p){
58700   assert( p->db==0 || sqlcipher3_mutex_held(p->db->mutex) );
58701   if( p->flags&MEM_Agg ){
58702     sqlcipher3VdbeMemFinalize(p, p->u.pDef);
58703     assert( (p->flags & MEM_Agg)==0 );
58704     sqlcipher3VdbeMemRelease(p);
58705   }else if( p->flags&MEM_Dyn && p->xDel ){
58706     assert( (p->flags&MEM_RowSet)==0 );
58707     p->xDel((void *)p->z);
58708     p->xDel = 0;
58709   }else if( p->flags&MEM_RowSet ){
58710     sqlcipher3RowSetClear(p->u.pRowSet);
58711   }else if( p->flags&MEM_Frame ){
58712     sqlcipher3VdbeMemSetNull(p);
58713   }
58714 }
58715
58716 /*
58717 ** Release any memory held by the Mem. This may leave the Mem in an
58718 ** inconsistent state, for example with (Mem.z==0) and
58719 ** (Mem.type==SQLCIPHER_TEXT).
58720 */
58721 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemRelease(Mem *p){
58722   MemReleaseExt(p);
58723   sqlcipher3DbFree(p->db, p->zMalloc);
58724   p->z = 0;
58725   p->zMalloc = 0;
58726   p->xDel = 0;
58727 }
58728
58729 /*
58730 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
58731 ** If the double is too large, return 0x8000000000000000.
58732 **
58733 ** Most systems appear to do this simply by assigning
58734 ** variables and without the extra range tests.  But
58735 ** there are reports that windows throws an expection
58736 ** if the floating point value is out of range. (See ticket #2880.)
58737 ** Because we do not completely understand the problem, we will
58738 ** take the conservative approach and always do range tests
58739 ** before attempting the conversion.
58740 */
58741 static i64 doubleToInt64(double r){
58742 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
58743   /* When floating-point is omitted, double and int64 are the same thing */
58744   return r;
58745 #else
58746   /*
58747   ** Many compilers we encounter do not define constants for the
58748   ** minimum and maximum 64-bit integers, or they define them
58749   ** inconsistently.  And many do not understand the "LL" notation.
58750   ** So we define our own static constants here using nothing
58751   ** larger than a 32-bit integer constant.
58752   */
58753   static const i64 maxInt = LARGEST_INT64;
58754   static const i64 minInt = SMALLEST_INT64;
58755
58756   if( r<(double)minInt ){
58757     return minInt;
58758   }else if( r>(double)maxInt ){
58759     /* minInt is correct here - not maxInt.  It turns out that assigning
58760     ** a very large positive number to an integer results in a very large
58761     ** negative integer.  This makes no sense, but it is what x86 hardware
58762     ** does so for compatibility we will do the same in software. */
58763     return minInt;
58764   }else{
58765     return (i64)r;
58766   }
58767 #endif
58768 }
58769
58770 /*
58771 ** Return some kind of integer value which is the best we can do
58772 ** at representing the value that *pMem describes as an integer.
58773 ** If pMem is an integer, then the value is exact.  If pMem is
58774 ** a floating-point then the value returned is the integer part.
58775 ** If pMem is a string or blob, then we make an attempt to convert
58776 ** it into a integer and return that.  If pMem represents an
58777 ** an SQL-NULL value, return 0.
58778 **
58779 ** If pMem represents a string value, its encoding might be changed.
58780 */
58781 SQLCIPHER_PRIVATE i64 sqlcipher3VdbeIntValue(Mem *pMem){
58782   int flags;
58783   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58784   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58785   flags = pMem->flags;
58786   if( flags & MEM_Int ){
58787     return pMem->u.i;
58788   }else if( flags & MEM_Real ){
58789     return doubleToInt64(pMem->r);
58790   }else if( flags & (MEM_Str|MEM_Blob) ){
58791     i64 value = 0;
58792     assert( pMem->z || pMem->n==0 );
58793     testcase( pMem->z==0 );
58794     sqlcipher3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
58795     return value;
58796   }else{
58797     return 0;
58798   }
58799 }
58800
58801 /*
58802 ** Return the best representation of pMem that we can get into a
58803 ** double.  If pMem is already a double or an integer, return its
58804 ** value.  If it is a string or blob, try to convert it to a double.
58805 ** If it is a NULL, return 0.0.
58806 */
58807 SQLCIPHER_PRIVATE double sqlcipher3VdbeRealValue(Mem *pMem){
58808   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58809   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58810   if( pMem->flags & MEM_Real ){
58811     return pMem->r;
58812   }else if( pMem->flags & MEM_Int ){
58813     return (double)pMem->u.i;
58814   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
58815     /* (double)0 In case of SQLCIPHER_OMIT_FLOATING_POINT... */
58816     double val = (double)0;
58817     sqlcipher3AtoF(pMem->z, &val, pMem->n, pMem->enc);
58818     return val;
58819   }else{
58820     /* (double)0 In case of SQLCIPHER_OMIT_FLOATING_POINT... */
58821     return (double)0;
58822   }
58823 }
58824
58825 /*
58826 ** The MEM structure is already a MEM_Real.  Try to also make it a
58827 ** MEM_Int if we can.
58828 */
58829 SQLCIPHER_PRIVATE void sqlcipher3VdbeIntegerAffinity(Mem *pMem){
58830   assert( pMem->flags & MEM_Real );
58831   assert( (pMem->flags & MEM_RowSet)==0 );
58832   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58833   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58834
58835   pMem->u.i = doubleToInt64(pMem->r);
58836
58837   /* Only mark the value as an integer if
58838   **
58839   **    (1) the round-trip conversion real->int->real is a no-op, and
58840   **    (2) The integer is neither the largest nor the smallest
58841   **        possible integer (ticket #3922)
58842   **
58843   ** The second and third terms in the following conditional enforces
58844   ** the second condition under the assumption that addition overflow causes
58845   ** values to wrap around.  On x86 hardware, the third term is always
58846   ** true and could be omitted.  But we leave it in because other
58847   ** architectures might behave differently.
58848   */
58849   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
58850       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
58851     pMem->flags |= MEM_Int;
58852   }
58853 }
58854
58855 /*
58856 ** Convert pMem to type integer.  Invalidate any prior representations.
58857 */
58858 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemIntegerify(Mem *pMem){
58859   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58860   assert( (pMem->flags & MEM_RowSet)==0 );
58861   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58862
58863   pMem->u.i = sqlcipher3VdbeIntValue(pMem);
58864   MemSetTypeFlag(pMem, MEM_Int);
58865   return SQLCIPHER_OK;
58866 }
58867
58868 /*
58869 ** Convert pMem so that it is of type MEM_Real.
58870 ** Invalidate any prior representations.
58871 */
58872 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemRealify(Mem *pMem){
58873   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58874   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58875
58876   pMem->r = sqlcipher3VdbeRealValue(pMem);
58877   MemSetTypeFlag(pMem, MEM_Real);
58878   return SQLCIPHER_OK;
58879 }
58880
58881 /*
58882 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
58883 ** Invalidate any prior representations.
58884 **
58885 ** Every effort is made to force the conversion, even if the input
58886 ** is a string that does not look completely like a number.  Convert
58887 ** as much of the string as we can and ignore the rest.
58888 */
58889 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemNumerify(Mem *pMem){
58890   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
58891     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
58892     assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58893     if( 0==sqlcipher3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
58894       MemSetTypeFlag(pMem, MEM_Int);
58895     }else{
58896       pMem->r = sqlcipher3VdbeRealValue(pMem);
58897       MemSetTypeFlag(pMem, MEM_Real);
58898       sqlcipher3VdbeIntegerAffinity(pMem);
58899     }
58900   }
58901   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
58902   pMem->flags &= ~(MEM_Str|MEM_Blob);
58903   return SQLCIPHER_OK;
58904 }
58905
58906 /*
58907 ** Delete any previous value and set the value stored in *pMem to NULL.
58908 */
58909 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetNull(Mem *pMem){
58910   if( pMem->flags & MEM_Frame ){
58911     VdbeFrame *pFrame = pMem->u.pFrame;
58912     pFrame->pParent = pFrame->v->pDelFrame;
58913     pFrame->v->pDelFrame = pFrame;
58914   }
58915   if( pMem->flags & MEM_RowSet ){
58916     sqlcipher3RowSetClear(pMem->u.pRowSet);
58917   }
58918   MemSetTypeFlag(pMem, MEM_Null);
58919   pMem->type = SQLCIPHER_NULL;
58920 }
58921
58922 /*
58923 ** Delete any previous value and set the value to be a BLOB of length
58924 ** n containing all zeros.
58925 */
58926 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetZeroBlob(Mem *pMem, int n){
58927   sqlcipher3VdbeMemRelease(pMem);
58928   pMem->flags = MEM_Blob|MEM_Zero;
58929   pMem->type = SQLCIPHER_BLOB;
58930   pMem->n = 0;
58931   if( n<0 ) n = 0;
58932   pMem->u.nZero = n;
58933   pMem->enc = SQLCIPHER_UTF8;
58934
58935 #ifdef SQLCIPHER_OMIT_INCRBLOB
58936   sqlcipher3VdbeMemGrow(pMem, n, 0);
58937   if( pMem->z ){
58938     pMem->n = n;
58939     memset(pMem->z, 0, n);
58940   }
58941 #endif
58942 }
58943
58944 /*
58945 ** Delete any previous value and set the value stored in *pMem to val,
58946 ** manifest type INTEGER.
58947 */
58948 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetInt64(Mem *pMem, i64 val){
58949   sqlcipher3VdbeMemRelease(pMem);
58950   pMem->u.i = val;
58951   pMem->flags = MEM_Int;
58952   pMem->type = SQLCIPHER_INTEGER;
58953 }
58954
58955 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
58956 /*
58957 ** Delete any previous value and set the value stored in *pMem to val,
58958 ** manifest type REAL.
58959 */
58960 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetDouble(Mem *pMem, double val){
58961   if( sqlcipher3IsNaN(val) ){
58962     sqlcipher3VdbeMemSetNull(pMem);
58963   }else{
58964     sqlcipher3VdbeMemRelease(pMem);
58965     pMem->r = val;
58966     pMem->flags = MEM_Real;
58967     pMem->type = SQLCIPHER_FLOAT;
58968   }
58969 }
58970 #endif
58971
58972 /*
58973 ** Delete any previous value and set the value of pMem to be an
58974 ** empty boolean index.
58975 */
58976 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetRowSet(Mem *pMem){
58977   sqlcipher3 *db = pMem->db;
58978   assert( db!=0 );
58979   assert( (pMem->flags & MEM_RowSet)==0 );
58980   sqlcipher3VdbeMemRelease(pMem);
58981   pMem->zMalloc = sqlcipher3DbMallocRaw(db, 64);
58982   if( db->mallocFailed ){
58983     pMem->flags = MEM_Null;
58984   }else{
58985     assert( pMem->zMalloc );
58986     pMem->u.pRowSet = sqlcipher3RowSetInit(db, pMem->zMalloc, 
58987                                        sqlcipher3DbMallocSize(db, pMem->zMalloc));
58988     assert( pMem->u.pRowSet!=0 );
58989     pMem->flags = MEM_RowSet;
58990   }
58991 }
58992
58993 /*
58994 ** Return true if the Mem object contains a TEXT or BLOB that is
58995 ** too large - whose size exceeds SQLCIPHER_MAX_LENGTH.
58996 */
58997 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemTooBig(Mem *p){
58998   assert( p->db!=0 );
58999   if( p->flags & (MEM_Str|MEM_Blob) ){
59000     int n = p->n;
59001     if( p->flags & MEM_Zero ){
59002       n += p->u.nZero;
59003     }
59004     return n>p->db->aLimit[SQLCIPHER_LIMIT_LENGTH];
59005   }
59006   return 0; 
59007 }
59008
59009 #ifdef SQLCIPHER_DEBUG
59010 /*
59011 ** This routine prepares a memory cell for modication by breaking
59012 ** its link to a shallow copy and by marking any current shallow
59013 ** copies of this cell as invalid.
59014 **
59015 ** This is used for testing and debugging only - to make sure shallow
59016 ** copies are not misused.
59017 */
59018 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
59019   int i;
59020   Mem *pX;
59021   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
59022     if( pX->pScopyFrom==pMem ){
59023       pX->flags |= MEM_Invalid;
59024       pX->pScopyFrom = 0;
59025     }
59026   }
59027   pMem->pScopyFrom = 0;
59028 }
59029 #endif /* SQLCIPHER_DEBUG */
59030
59031 /*
59032 ** Size of struct Mem not including the Mem.zMalloc member.
59033 */
59034 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
59035
59036 /*
59037 ** Make an shallow copy of pFrom into pTo.  Prior contents of
59038 ** pTo are freed.  The pFrom->z field is not duplicated.  If
59039 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
59040 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
59041 */
59042 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
59043   assert( (pFrom->flags & MEM_RowSet)==0 );
59044   MemReleaseExt(pTo);
59045   memcpy(pTo, pFrom, MEMCELLSIZE);
59046   pTo->xDel = 0;
59047   if( (pFrom->flags&MEM_Static)==0 ){
59048     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
59049     assert( srcType==MEM_Ephem || srcType==MEM_Static );
59050     pTo->flags |= srcType;
59051   }
59052 }
59053
59054 /*
59055 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
59056 ** freed before the copy is made.
59057 */
59058 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
59059   int rc = SQLCIPHER_OK;
59060
59061   assert( (pFrom->flags & MEM_RowSet)==0 );
59062   MemReleaseExt(pTo);
59063   memcpy(pTo, pFrom, MEMCELLSIZE);
59064   pTo->flags &= ~MEM_Dyn;
59065
59066   if( pTo->flags&(MEM_Str|MEM_Blob) ){
59067     if( 0==(pFrom->flags&MEM_Static) ){
59068       pTo->flags |= MEM_Ephem;
59069       rc = sqlcipher3VdbeMemMakeWriteable(pTo);
59070     }
59071   }
59072
59073   return rc;
59074 }
59075
59076 /*
59077 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
59078 ** freed. If pFrom contains ephemeral data, a copy is made.
59079 **
59080 ** pFrom contains an SQL NULL when this routine returns.
59081 */
59082 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemMove(Mem *pTo, Mem *pFrom){
59083   assert( pFrom->db==0 || sqlcipher3_mutex_held(pFrom->db->mutex) );
59084   assert( pTo->db==0 || sqlcipher3_mutex_held(pTo->db->mutex) );
59085   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
59086
59087   sqlcipher3VdbeMemRelease(pTo);
59088   memcpy(pTo, pFrom, sizeof(Mem));
59089   pFrom->flags = MEM_Null;
59090   pFrom->xDel = 0;
59091   pFrom->zMalloc = 0;
59092 }
59093
59094 /*
59095 ** Change the value of a Mem to be a string or a BLOB.
59096 **
59097 ** The memory management strategy depends on the value of the xDel
59098 ** parameter. If the value passed is SQLCIPHER_TRANSIENT, then the 
59099 ** string is copied into a (possibly existing) buffer managed by the 
59100 ** Mem structure. Otherwise, any existing buffer is freed and the
59101 ** pointer copied.
59102 **
59103 ** If the string is too large (if it exceeds the SQLCIPHER_LIMIT_LENGTH
59104 ** size limit) then no memory allocation occurs.  If the string can be
59105 ** stored without allocating memory, then it is.  If a memory allocation
59106 ** is required to store the string, then value of pMem is unchanged.  In
59107 ** either case, SQLCIPHER_TOOBIG is returned.
59108 */
59109 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemSetStr(
59110   Mem *pMem,          /* Memory cell to set to string value */
59111   const char *z,      /* String pointer */
59112   int n,              /* Bytes in string, or negative */
59113   u8 enc,             /* Encoding of z.  0 for BLOBs */
59114   void (*xDel)(void*) /* Destructor function */
59115 ){
59116   int nByte = n;      /* New value for pMem->n */
59117   int iLimit;         /* Maximum allowed string or blob size */
59118   u16 flags = 0;      /* New value for pMem->flags */
59119
59120   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
59121   assert( (pMem->flags & MEM_RowSet)==0 );
59122
59123   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
59124   if( !z ){
59125     sqlcipher3VdbeMemSetNull(pMem);
59126     return SQLCIPHER_OK;
59127   }
59128
59129   if( pMem->db ){
59130     iLimit = pMem->db->aLimit[SQLCIPHER_LIMIT_LENGTH];
59131   }else{
59132     iLimit = SQLCIPHER_MAX_LENGTH;
59133   }
59134   flags = (enc==0?MEM_Blob:MEM_Str);
59135   if( nByte<0 ){
59136     assert( enc!=0 );
59137     if( enc==SQLCIPHER_UTF8 ){
59138       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
59139     }else{
59140       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
59141     }
59142     flags |= MEM_Term;
59143   }
59144
59145   /* The following block sets the new values of Mem.z and Mem.xDel. It
59146   ** also sets a flag in local variable "flags" to indicate the memory
59147   ** management (one of MEM_Dyn or MEM_Static).
59148   */
59149   if( xDel==SQLCIPHER_TRANSIENT ){
59150     int nAlloc = nByte;
59151     if( flags&MEM_Term ){
59152       nAlloc += (enc==SQLCIPHER_UTF8?1:2);
59153     }
59154     if( nByte>iLimit ){
59155       return SQLCIPHER_TOOBIG;
59156     }
59157     if( sqlcipher3VdbeMemGrow(pMem, nAlloc, 0) ){
59158       return SQLCIPHER_NOMEM;
59159     }
59160     memcpy(pMem->z, z, nAlloc);
59161   }else if( xDel==SQLCIPHER_DYNAMIC ){
59162     sqlcipher3VdbeMemRelease(pMem);
59163     pMem->zMalloc = pMem->z = (char *)z;
59164     pMem->xDel = 0;
59165   }else{
59166     sqlcipher3VdbeMemRelease(pMem);
59167     pMem->z = (char *)z;
59168     pMem->xDel = xDel;
59169     flags |= ((xDel==SQLCIPHER_STATIC)?MEM_Static:MEM_Dyn);
59170   }
59171
59172   pMem->n = nByte;
59173   pMem->flags = flags;
59174   pMem->enc = (enc==0 ? SQLCIPHER_UTF8 : enc);
59175   pMem->type = (enc==0 ? SQLCIPHER_BLOB : SQLCIPHER_TEXT);
59176
59177 #ifndef SQLCIPHER_OMIT_UTF16
59178   if( pMem->enc!=SQLCIPHER_UTF8 && sqlcipher3VdbeMemHandleBom(pMem) ){
59179     return SQLCIPHER_NOMEM;
59180   }
59181 #endif
59182
59183   if( nByte>iLimit ){
59184     return SQLCIPHER_TOOBIG;
59185   }
59186
59187   return SQLCIPHER_OK;
59188 }
59189
59190 /*
59191 ** Compare the values contained by the two memory cells, returning
59192 ** negative, zero or positive if pMem1 is less than, equal to, or greater
59193 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
59194 ** and reals) sorted numerically, followed by text ordered by the collating
59195 ** sequence pColl and finally blob's ordered by memcmp().
59196 **
59197 ** Two NULL values are considered equal by this function.
59198 */
59199 SQLCIPHER_PRIVATE int sqlcipher3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
59200   int rc;
59201   int f1, f2;
59202   int combined_flags;
59203
59204   f1 = pMem1->flags;
59205   f2 = pMem2->flags;
59206   combined_flags = f1|f2;
59207   assert( (combined_flags & MEM_RowSet)==0 );
59208  
59209   /* If one value is NULL, it is less than the other. If both values
59210   ** are NULL, return 0.
59211   */
59212   if( combined_flags&MEM_Null ){
59213     return (f2&MEM_Null) - (f1&MEM_Null);
59214   }
59215
59216   /* If one value is a number and the other is not, the number is less.
59217   ** If both are numbers, compare as reals if one is a real, or as integers
59218   ** if both values are integers.
59219   */
59220   if( combined_flags&(MEM_Int|MEM_Real) ){
59221     if( !(f1&(MEM_Int|MEM_Real)) ){
59222       return 1;
59223     }
59224     if( !(f2&(MEM_Int|MEM_Real)) ){
59225       return -1;
59226     }
59227     if( (f1 & f2 & MEM_Int)==0 ){
59228       double r1, r2;
59229       if( (f1&MEM_Real)==0 ){
59230         r1 = (double)pMem1->u.i;
59231       }else{
59232         r1 = pMem1->r;
59233       }
59234       if( (f2&MEM_Real)==0 ){
59235         r2 = (double)pMem2->u.i;
59236       }else{
59237         r2 = pMem2->r;
59238       }
59239       if( r1<r2 ) return -1;
59240       if( r1>r2 ) return 1;
59241       return 0;
59242     }else{
59243       assert( f1&MEM_Int );
59244       assert( f2&MEM_Int );
59245       if( pMem1->u.i < pMem2->u.i ) return -1;
59246       if( pMem1->u.i > pMem2->u.i ) return 1;
59247       return 0;
59248     }
59249   }
59250
59251   /* If one value is a string and the other is a blob, the string is less.
59252   ** If both are strings, compare using the collating functions.
59253   */
59254   if( combined_flags&MEM_Str ){
59255     if( (f1 & MEM_Str)==0 ){
59256       return 1;
59257     }
59258     if( (f2 & MEM_Str)==0 ){
59259       return -1;
59260     }
59261
59262     assert( pMem1->enc==pMem2->enc );
59263     assert( pMem1->enc==SQLCIPHER_UTF8 || 
59264             pMem1->enc==SQLCIPHER_UTF16LE || pMem1->enc==SQLCIPHER_UTF16BE );
59265
59266     /* The collation sequence must be defined at this point, even if
59267     ** the user deletes the collation sequence after the vdbe program is
59268     ** compiled (this was not always the case).
59269     */
59270     assert( !pColl || pColl->xCmp );
59271
59272     if( pColl ){
59273       if( pMem1->enc==pColl->enc ){
59274         /* The strings are already in the correct encoding.  Call the
59275         ** comparison function directly */
59276         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
59277       }else{
59278         const void *v1, *v2;
59279         int n1, n2;
59280         Mem c1;
59281         Mem c2;
59282         memset(&c1, 0, sizeof(c1));
59283         memset(&c2, 0, sizeof(c2));
59284         sqlcipher3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
59285         sqlcipher3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
59286         v1 = sqlcipher3ValueText((sqlcipher3_value*)&c1, pColl->enc);
59287         n1 = v1==0 ? 0 : c1.n;
59288         v2 = sqlcipher3ValueText((sqlcipher3_value*)&c2, pColl->enc);
59289         n2 = v2==0 ? 0 : c2.n;
59290         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
59291         sqlcipher3VdbeMemRelease(&c1);
59292         sqlcipher3VdbeMemRelease(&c2);
59293         return rc;
59294       }
59295     }
59296     /* If a NULL pointer was passed as the collate function, fall through
59297     ** to the blob case and use memcmp().  */
59298   }
59299  
59300   /* Both values must be blobs.  Compare using memcmp().  */
59301   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
59302   if( rc==0 ){
59303     rc = pMem1->n - pMem2->n;
59304   }
59305   return rc;
59306 }
59307
59308 /*
59309 ** Move data out of a btree key or data field and into a Mem structure.
59310 ** The data or key is taken from the entry that pCur is currently pointing
59311 ** to.  offset and amt determine what portion of the data or key to retrieve.
59312 ** key is true to get the key or false to get data.  The result is written
59313 ** into the pMem element.
59314 **
59315 ** The pMem structure is assumed to be uninitialized.  Any prior content
59316 ** is overwritten without being freed.
59317 **
59318 ** If this routine fails for any reason (malloc returns NULL or unable
59319 ** to read from the disk) then the pMem is left in an inconsistent state.
59320 */
59321 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemFromBtree(
59322   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
59323   int offset,       /* Offset from the start of data to return bytes from. */
59324   int amt,          /* Number of bytes to return. */
59325   int key,          /* If true, retrieve from the btree key, not data. */
59326   Mem *pMem         /* OUT: Return data in this Mem structure. */
59327 ){
59328   char *zData;        /* Data from the btree layer */
59329   int available = 0;  /* Number of bytes available on the local btree page */
59330   int rc = SQLCIPHER_OK; /* Return code */
59331
59332   assert( sqlcipher3BtreeCursorIsValid(pCur) );
59333
59334   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
59335   ** that both the BtShared and database handle mutexes are held. */
59336   assert( (pMem->flags & MEM_RowSet)==0 );
59337   if( key ){
59338     zData = (char *)sqlcipher3BtreeKeyFetch(pCur, &available);
59339   }else{
59340     zData = (char *)sqlcipher3BtreeDataFetch(pCur, &available);
59341   }
59342   assert( zData!=0 );
59343
59344   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
59345     sqlcipher3VdbeMemRelease(pMem);
59346     pMem->z = &zData[offset];
59347     pMem->flags = MEM_Blob|MEM_Ephem;
59348   }else if( SQLCIPHER_OK==(rc = sqlcipher3VdbeMemGrow(pMem, amt+2, 0)) ){
59349     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
59350     pMem->enc = 0;
59351     pMem->type = SQLCIPHER_BLOB;
59352     if( key ){
59353       rc = sqlcipher3BtreeKey(pCur, offset, amt, pMem->z);
59354     }else{
59355       rc = sqlcipher3BtreeData(pCur, offset, amt, pMem->z);
59356     }
59357     pMem->z[amt] = 0;
59358     pMem->z[amt+1] = 0;
59359     if( rc!=SQLCIPHER_OK ){
59360       sqlcipher3VdbeMemRelease(pMem);
59361     }
59362   }
59363   pMem->n = amt;
59364
59365   return rc;
59366 }
59367
59368 /* This function is only available internally, it is not part of the
59369 ** external API. It works in a similar way to sqlcipher3_value_text(),
59370 ** except the data returned is in the encoding specified by the second
59371 ** parameter, which must be one of SQLCIPHER_UTF16BE, SQLCIPHER_UTF16LE or
59372 ** SQLCIPHER_UTF8.
59373 **
59374 ** (2006-02-16:)  The enc value can be or-ed with SQLCIPHER_UTF16_ALIGNED.
59375 ** If that is the case, then the result must be aligned on an even byte
59376 ** boundary.
59377 */
59378 SQLCIPHER_PRIVATE const void *sqlcipher3ValueText(sqlcipher3_value* pVal, u8 enc){
59379   if( !pVal ) return 0;
59380
59381   assert( pVal->db==0 || sqlcipher3_mutex_held(pVal->db->mutex) );
59382   assert( (enc&3)==(enc&~SQLCIPHER_UTF16_ALIGNED) );
59383   assert( (pVal->flags & MEM_RowSet)==0 );
59384
59385   if( pVal->flags&MEM_Null ){
59386     return 0;
59387   }
59388   assert( (MEM_Blob>>3) == MEM_Str );
59389   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
59390   expandBlob(pVal);
59391   if( pVal->flags&MEM_Str ){
59392     sqlcipher3VdbeChangeEncoding(pVal, enc & ~SQLCIPHER_UTF16_ALIGNED);
59393     if( (enc & SQLCIPHER_UTF16_ALIGNED)!=0 && 1==(1&SQLCIPHER_PTR_TO_INT(pVal->z)) ){
59394       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
59395       if( sqlcipher3VdbeMemMakeWriteable(pVal)!=SQLCIPHER_OK ){
59396         return 0;
59397       }
59398     }
59399     sqlcipher3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
59400   }else{
59401     assert( (pVal->flags&MEM_Blob)==0 );
59402     sqlcipher3VdbeMemStringify(pVal, enc);
59403     assert( 0==(1&SQLCIPHER_PTR_TO_INT(pVal->z)) );
59404   }
59405   assert(pVal->enc==(enc & ~SQLCIPHER_UTF16_ALIGNED) || pVal->db==0
59406               || pVal->db->mallocFailed );
59407   if( pVal->enc==(enc & ~SQLCIPHER_UTF16_ALIGNED) ){
59408     return pVal->z;
59409   }else{
59410     return 0;
59411   }
59412 }
59413
59414 /*
59415 ** Create a new sqlcipher3_value object.
59416 */
59417 SQLCIPHER_PRIVATE sqlcipher3_value *sqlcipher3ValueNew(sqlcipher3 *db){
59418   Mem *p = sqlcipher3DbMallocZero(db, sizeof(*p));
59419   if( p ){
59420     p->flags = MEM_Null;
59421     p->type = SQLCIPHER_NULL;
59422     p->db = db;
59423   }
59424   return p;
59425 }
59426
59427 /*
59428 ** Create a new sqlcipher3_value object, containing the value of pExpr.
59429 **
59430 ** This only works for very simple expressions that consist of one constant
59431 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
59432 ** be converted directly into a value, then the value is allocated and
59433 ** a pointer written to *ppVal. The caller is responsible for deallocating
59434 ** the value by passing it to sqlcipher3ValueFree() later on. If the expression
59435 ** cannot be converted to a value, then *ppVal is set to NULL.
59436 */
59437 SQLCIPHER_PRIVATE int sqlcipher3ValueFromExpr(
59438   sqlcipher3 *db,              /* The database connection */
59439   Expr *pExpr,              /* The expression to evaluate */
59440   u8 enc,                   /* Encoding to use */
59441   u8 affinity,              /* Affinity to use */
59442   sqlcipher3_value **ppVal     /* Write the new value here */
59443 ){
59444   int op;
59445   char *zVal = 0;
59446   sqlcipher3_value *pVal = 0;
59447   int negInt = 1;
59448   const char *zNeg = "";
59449
59450   if( !pExpr ){
59451     *ppVal = 0;
59452     return SQLCIPHER_OK;
59453   }
59454   op = pExpr->op;
59455
59456   /* op can only be TK_REGISTER if we have compiled with SQLCIPHER_ENABLE_STAT3.
59457   ** The ifdef here is to enable us to achieve 100% branch test coverage even
59458   ** when SQLCIPHER_ENABLE_STAT3 is omitted.
59459   */
59460 #ifdef SQLCIPHER_ENABLE_STAT3
59461   if( op==TK_REGISTER ) op = pExpr->op2;
59462 #else
59463   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
59464 #endif
59465
59466   /* Handle negative integers in a single step.  This is needed in the
59467   ** case when the value is -9223372036854775808.
59468   */
59469   if( op==TK_UMINUS
59470    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
59471     pExpr = pExpr->pLeft;
59472     op = pExpr->op;
59473     negInt = -1;
59474     zNeg = "-";
59475   }
59476
59477   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
59478     pVal = sqlcipher3ValueNew(db);
59479     if( pVal==0 ) goto no_mem;
59480     if( ExprHasProperty(pExpr, EP_IntValue) ){
59481       sqlcipher3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
59482     }else{
59483       zVal = sqlcipher3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
59484       if( zVal==0 ) goto no_mem;
59485       sqlcipher3ValueSetStr(pVal, -1, zVal, SQLCIPHER_UTF8, SQLCIPHER_DYNAMIC);
59486       if( op==TK_FLOAT ) pVal->type = SQLCIPHER_FLOAT;
59487     }
59488     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLCIPHER_AFF_NONE ){
59489       sqlcipher3ValueApplyAffinity(pVal, SQLCIPHER_AFF_NUMERIC, SQLCIPHER_UTF8);
59490     }else{
59491       sqlcipher3ValueApplyAffinity(pVal, affinity, SQLCIPHER_UTF8);
59492     }
59493     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
59494     if( enc!=SQLCIPHER_UTF8 ){
59495       sqlcipher3VdbeChangeEncoding(pVal, enc);
59496     }
59497   }else if( op==TK_UMINUS ) {
59498     /* This branch happens for multiple negative signs.  Ex: -(-5) */
59499     if( SQLCIPHER_OK==sqlcipher3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
59500       sqlcipher3VdbeMemNumerify(pVal);
59501       if( pVal->u.i==SMALLEST_INT64 ){
59502         pVal->flags &= MEM_Int;
59503         pVal->flags |= MEM_Real;
59504         pVal->r = (double)LARGEST_INT64;
59505       }else{
59506         pVal->u.i = -pVal->u.i;
59507       }
59508       pVal->r = -pVal->r;
59509       sqlcipher3ValueApplyAffinity(pVal, affinity, enc);
59510     }
59511   }else if( op==TK_NULL ){
59512     pVal = sqlcipher3ValueNew(db);
59513     if( pVal==0 ) goto no_mem;
59514   }
59515 #ifndef SQLCIPHER_OMIT_BLOB_LITERAL
59516   else if( op==TK_BLOB ){
59517     int nVal;
59518     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
59519     assert( pExpr->u.zToken[1]=='\'' );
59520     pVal = sqlcipher3ValueNew(db);
59521     if( !pVal ) goto no_mem;
59522     zVal = &pExpr->u.zToken[2];
59523     nVal = sqlcipher3Strlen30(zVal)-1;
59524     assert( zVal[nVal]=='\'' );
59525     sqlcipher3VdbeMemSetStr(pVal, sqlcipher3HexToBlob(db, zVal, nVal), nVal/2,
59526                          0, SQLCIPHER_DYNAMIC);
59527   }
59528 #endif
59529
59530   if( pVal ){
59531     sqlcipher3VdbeMemStoreType(pVal);
59532   }
59533   *ppVal = pVal;
59534   return SQLCIPHER_OK;
59535
59536 no_mem:
59537   db->mallocFailed = 1;
59538   sqlcipher3DbFree(db, zVal);
59539   sqlcipher3ValueFree(pVal);
59540   *ppVal = 0;
59541   return SQLCIPHER_NOMEM;
59542 }
59543
59544 /*
59545 ** Change the string value of an sqlcipher3_value object
59546 */
59547 SQLCIPHER_PRIVATE void sqlcipher3ValueSetStr(
59548   sqlcipher3_value *v,     /* Value to be set */
59549   int n,                /* Length of string z */
59550   const void *z,        /* Text of the new string */
59551   u8 enc,               /* Encoding to use */
59552   void (*xDel)(void*)   /* Destructor for the string */
59553 ){
59554   if( v ) sqlcipher3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
59555 }
59556
59557 /*
59558 ** Free an sqlcipher3_value object
59559 */
59560 SQLCIPHER_PRIVATE void sqlcipher3ValueFree(sqlcipher3_value *v){
59561   if( !v ) return;
59562   sqlcipher3VdbeMemRelease((Mem *)v);
59563   sqlcipher3DbFree(((Mem*)v)->db, v);
59564 }
59565
59566 /*
59567 ** Return the number of bytes in the sqlcipher3_value object assuming
59568 ** that it uses the encoding "enc"
59569 */
59570 SQLCIPHER_PRIVATE int sqlcipher3ValueBytes(sqlcipher3_value *pVal, u8 enc){
59571   Mem *p = (Mem*)pVal;
59572   if( (p->flags & MEM_Blob)!=0 || sqlcipher3ValueText(pVal, enc) ){
59573     if( p->flags & MEM_Zero ){
59574       return p->n + p->u.nZero;
59575     }else{
59576       return p->n;
59577     }
59578   }
59579   return 0;
59580 }
59581
59582 /************** End of vdbemem.c *********************************************/
59583 /************** Begin file vdbeaux.c *****************************************/
59584 /*
59585 ** 2003 September 6
59586 **
59587 ** The author disclaims copyright to this source code.  In place of
59588 ** a legal notice, here is a blessing:
59589 **
59590 **    May you do good and not evil.
59591 **    May you find forgiveness for yourself and forgive others.
59592 **    May you share freely, never taking more than you give.
59593 **
59594 *************************************************************************
59595 ** This file contains code used for creating, destroying, and populating
59596 ** a VDBE (or an "sqlcipher3_stmt" as it is known to the outside world.)  Prior
59597 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
59598 ** But that file was getting too big so this subroutines were split out.
59599 */
59600
59601
59602
59603 /*
59604 ** When debugging the code generator in a symbolic debugger, one can
59605 ** set the sqlcipher3VdbeAddopTrace to 1 and all opcodes will be printed
59606 ** as they are added to the instruction stream.
59607 */
59608 #ifdef SQLCIPHER_DEBUG
59609 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddopTrace = 0;
59610 #endif
59611
59612
59613 /*
59614 ** Create a new virtual database engine.
59615 */
59616 SQLCIPHER_PRIVATE Vdbe *sqlcipher3VdbeCreate(sqlcipher3 *db){
59617   Vdbe *p;
59618   p = sqlcipher3DbMallocZero(db, sizeof(Vdbe) );
59619   if( p==0 ) return 0;
59620   p->db = db;
59621   if( db->pVdbe ){
59622     db->pVdbe->pPrev = p;
59623   }
59624   p->pNext = db->pVdbe;
59625   p->pPrev = 0;
59626   db->pVdbe = p;
59627   p->magic = VDBE_MAGIC_INIT;
59628   return p;
59629 }
59630
59631 /*
59632 ** Remember the SQL string for a prepared statement.
59633 */
59634 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
59635   assert( isPrepareV2==1 || isPrepareV2==0 );
59636   if( p==0 ) return;
59637 #ifdef SQLCIPHER_OMIT_TRACE
59638   if( !isPrepareV2 ) return;
59639 #endif
59640   assert( p->zSql==0 );
59641   p->zSql = sqlcipher3DbStrNDup(p->db, z, n);
59642   p->isPrepareV2 = (u8)isPrepareV2;
59643 }
59644
59645 /*
59646 ** Return the SQL associated with a prepared statement
59647 */
59648 SQLCIPHER_API const char *sqlcipher3_sql(sqlcipher3_stmt *pStmt){
59649   Vdbe *p = (Vdbe *)pStmt;
59650   return (p && p->isPrepareV2) ? p->zSql : 0;
59651 }
59652
59653 /*
59654 ** Swap all content between two VDBE structures.
59655 */
59656 SQLCIPHER_PRIVATE void sqlcipher3VdbeSwap(Vdbe *pA, Vdbe *pB){
59657   Vdbe tmp, *pTmp;
59658   char *zTmp;
59659   tmp = *pA;
59660   *pA = *pB;
59661   *pB = tmp;
59662   pTmp = pA->pNext;
59663   pA->pNext = pB->pNext;
59664   pB->pNext = pTmp;
59665   pTmp = pA->pPrev;
59666   pA->pPrev = pB->pPrev;
59667   pB->pPrev = pTmp;
59668   zTmp = pA->zSql;
59669   pA->zSql = pB->zSql;
59670   pB->zSql = zTmp;
59671   pB->isPrepareV2 = pA->isPrepareV2;
59672 }
59673
59674 #ifdef SQLCIPHER_DEBUG
59675 /*
59676 ** Turn tracing on or off
59677 */
59678 SQLCIPHER_PRIVATE void sqlcipher3VdbeTrace(Vdbe *p, FILE *trace){
59679   p->trace = trace;
59680 }
59681 #endif
59682
59683 /*
59684 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
59685 ** it was.
59686 **
59687 ** If an out-of-memory error occurs while resizing the array, return
59688 ** SQLCIPHER_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
59689 ** unchanged (this is so that any opcodes already allocated can be 
59690 ** correctly deallocated along with the rest of the Vdbe).
59691 */
59692 static int growOpArray(Vdbe *p){
59693   VdbeOp *pNew;
59694   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
59695   pNew = sqlcipher3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
59696   if( pNew ){
59697     p->nOpAlloc = sqlcipher3DbMallocSize(p->db, pNew)/sizeof(Op);
59698     p->aOp = pNew;
59699   }
59700   return (pNew ? SQLCIPHER_OK : SQLCIPHER_NOMEM);
59701 }
59702
59703 /*
59704 ** Add a new instruction to the list of instructions current in the
59705 ** VDBE.  Return the address of the new instruction.
59706 **
59707 ** Parameters:
59708 **
59709 **    p               Pointer to the VDBE
59710 **
59711 **    op              The opcode for this instruction
59712 **
59713 **    p1, p2, p3      Operands
59714 **
59715 ** Use the sqlcipher3VdbeResolveLabel() function to fix an address and
59716 ** the sqlcipher3VdbeChangeP4() function to change the value of the P4
59717 ** operand.
59718 */
59719 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
59720   int i;
59721   VdbeOp *pOp;
59722
59723   i = p->nOp;
59724   assert( p->magic==VDBE_MAGIC_INIT );
59725   assert( op>0 && op<0xff );
59726   if( p->nOpAlloc<=i ){
59727     if( growOpArray(p) ){
59728       return 1;
59729     }
59730   }
59731   p->nOp++;
59732   pOp = &p->aOp[i];
59733   pOp->opcode = (u8)op;
59734   pOp->p5 = 0;
59735   pOp->p1 = p1;
59736   pOp->p2 = p2;
59737   pOp->p3 = p3;
59738   pOp->p4.p = 0;
59739   pOp->p4type = P4_NOTUSED;
59740 #ifdef SQLCIPHER_DEBUG
59741   pOp->zComment = 0;
59742   if( sqlcipher3VdbeAddopTrace ) sqlcipher3VdbePrintOp(0, i, &p->aOp[i]);
59743 #endif
59744 #ifdef VDBE_PROFILE
59745   pOp->cycles = 0;
59746   pOp->cnt = 0;
59747 #endif
59748   return i;
59749 }
59750 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp0(Vdbe *p, int op){
59751   return sqlcipher3VdbeAddOp3(p, op, 0, 0, 0);
59752 }
59753 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp1(Vdbe *p, int op, int p1){
59754   return sqlcipher3VdbeAddOp3(p, op, p1, 0, 0);
59755 }
59756 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
59757   return sqlcipher3VdbeAddOp3(p, op, p1, p2, 0);
59758 }
59759
59760
59761 /*
59762 ** Add an opcode that includes the p4 value as a pointer.
59763 */
59764 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp4(
59765   Vdbe *p,            /* Add the opcode to this VM */
59766   int op,             /* The new opcode */
59767   int p1,             /* The P1 operand */
59768   int p2,             /* The P2 operand */
59769   int p3,             /* The P3 operand */
59770   const char *zP4,    /* The P4 operand */
59771   int p4type          /* P4 operand type */
59772 ){
59773   int addr = sqlcipher3VdbeAddOp3(p, op, p1, p2, p3);
59774   sqlcipher3VdbeChangeP4(p, addr, zP4, p4type);
59775   return addr;
59776 }
59777
59778 /*
59779 ** Add an OP_ParseSchema opcode.  This routine is broken out from
59780 ** sqlcipher3VdbeAddOp4() since it needs to also local all btrees.
59781 **
59782 ** The zWhere string must have been obtained from sqlcipher3_malloc().
59783 ** This routine will take ownership of the allocated memory.
59784 */
59785 SQLCIPHER_PRIVATE void sqlcipher3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
59786   int j;
59787   int addr = sqlcipher3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
59788   sqlcipher3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
59789   for(j=0; j<p->db->nDb; j++) sqlcipher3VdbeUsesBtree(p, j);
59790 }
59791
59792 /*
59793 ** Add an opcode that includes the p4 value as an integer.
59794 */
59795 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp4Int(
59796   Vdbe *p,            /* Add the opcode to this VM */
59797   int op,             /* The new opcode */
59798   int p1,             /* The P1 operand */
59799   int p2,             /* The P2 operand */
59800   int p3,             /* The P3 operand */
59801   int p4              /* The P4 operand as an integer */
59802 ){
59803   int addr = sqlcipher3VdbeAddOp3(p, op, p1, p2, p3);
59804   sqlcipher3VdbeChangeP4(p, addr, SQLCIPHER_INT_TO_PTR(p4), P4_INT32);
59805   return addr;
59806 }
59807
59808 /*
59809 ** Create a new symbolic label for an instruction that has yet to be
59810 ** coded.  The symbolic label is really just a negative number.  The
59811 ** label can be used as the P2 value of an operation.  Later, when
59812 ** the label is resolved to a specific address, the VDBE will scan
59813 ** through its operation list and change all values of P2 which match
59814 ** the label into the resolved address.
59815 **
59816 ** The VDBE knows that a P2 value is a label because labels are
59817 ** always negative and P2 values are suppose to be non-negative.
59818 ** Hence, a negative P2 value is a label that has yet to be resolved.
59819 **
59820 ** Zero is returned if a malloc() fails.
59821 */
59822 SQLCIPHER_PRIVATE int sqlcipher3VdbeMakeLabel(Vdbe *p){
59823   int i;
59824   i = p->nLabel++;
59825   assert( p->magic==VDBE_MAGIC_INIT );
59826   if( i>=p->nLabelAlloc ){
59827     int n = p->nLabelAlloc*2 + 5;
59828     p->aLabel = sqlcipher3DbReallocOrFree(p->db, p->aLabel,
59829                                        n*sizeof(p->aLabel[0]));
59830     p->nLabelAlloc = sqlcipher3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
59831   }
59832   if( p->aLabel ){
59833     p->aLabel[i] = -1;
59834   }
59835   return -1-i;
59836 }
59837
59838 /*
59839 ** Resolve label "x" to be the address of the next instruction to
59840 ** be inserted.  The parameter "x" must have been obtained from
59841 ** a prior call to sqlcipher3VdbeMakeLabel().
59842 */
59843 SQLCIPHER_PRIVATE void sqlcipher3VdbeResolveLabel(Vdbe *p, int x){
59844   int j = -1-x;
59845   assert( p->magic==VDBE_MAGIC_INIT );
59846   assert( j>=0 && j<p->nLabel );
59847   if( p->aLabel ){
59848     p->aLabel[j] = p->nOp;
59849   }
59850 }
59851
59852 /*
59853 ** Mark the VDBE as one that can only be run one time.
59854 */
59855 SQLCIPHER_PRIVATE void sqlcipher3VdbeRunOnlyOnce(Vdbe *p){
59856   p->runOnlyOnce = 1;
59857 }
59858
59859 #ifdef SQLCIPHER_DEBUG /* sqlcipher3AssertMayAbort() logic */
59860
59861 /*
59862 ** The following type and function are used to iterate through all opcodes
59863 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
59864 ** invoke directly or indirectly. It should be used as follows:
59865 **
59866 **   Op *pOp;
59867 **   VdbeOpIter sIter;
59868 **
59869 **   memset(&sIter, 0, sizeof(sIter));
59870 **   sIter.v = v;                            // v is of type Vdbe* 
59871 **   while( (pOp = opIterNext(&sIter)) ){
59872 **     // Do something with pOp
59873 **   }
59874 **   sqlcipher3DbFree(v->db, sIter.apSub);
59875 ** 
59876 */
59877 typedef struct VdbeOpIter VdbeOpIter;
59878 struct VdbeOpIter {
59879   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
59880   SubProgram **apSub;        /* Array of subprograms */
59881   int nSub;                  /* Number of entries in apSub */
59882   int iAddr;                 /* Address of next instruction to return */
59883   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
59884 };
59885 static Op *opIterNext(VdbeOpIter *p){
59886   Vdbe *v = p->v;
59887   Op *pRet = 0;
59888   Op *aOp;
59889   int nOp;
59890
59891   if( p->iSub<=p->nSub ){
59892
59893     if( p->iSub==0 ){
59894       aOp = v->aOp;
59895       nOp = v->nOp;
59896     }else{
59897       aOp = p->apSub[p->iSub-1]->aOp;
59898       nOp = p->apSub[p->iSub-1]->nOp;
59899     }
59900     assert( p->iAddr<nOp );
59901
59902     pRet = &aOp[p->iAddr];
59903     p->iAddr++;
59904     if( p->iAddr==nOp ){
59905       p->iSub++;
59906       p->iAddr = 0;
59907     }
59908   
59909     if( pRet->p4type==P4_SUBPROGRAM ){
59910       int nByte = (p->nSub+1)*sizeof(SubProgram*);
59911       int j;
59912       for(j=0; j<p->nSub; j++){
59913         if( p->apSub[j]==pRet->p4.pProgram ) break;
59914       }
59915       if( j==p->nSub ){
59916         p->apSub = sqlcipher3DbReallocOrFree(v->db, p->apSub, nByte);
59917         if( !p->apSub ){
59918           pRet = 0;
59919         }else{
59920           p->apSub[p->nSub++] = pRet->p4.pProgram;
59921         }
59922       }
59923     }
59924   }
59925
59926   return pRet;
59927 }
59928
59929 /*
59930 ** Check if the program stored in the VM associated with pParse may
59931 ** throw an ABORT exception (causing the statement, but not entire transaction
59932 ** to be rolled back). This condition is true if the main program or any
59933 ** sub-programs contains any of the following:
59934 **
59935 **   *  OP_Halt with P1=SQLCIPHER_CONSTRAINT and P2=OE_Abort.
59936 **   *  OP_HaltIfNull with P1=SQLCIPHER_CONSTRAINT and P2=OE_Abort.
59937 **   *  OP_Destroy
59938 **   *  OP_VUpdate
59939 **   *  OP_VRename
59940 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
59941 **
59942 ** Then check that the value of Parse.mayAbort is true if an
59943 ** ABORT may be thrown, or false otherwise. Return true if it does
59944 ** match, or false otherwise. This function is intended to be used as
59945 ** part of an assert statement in the compiler. Similar to:
59946 **
59947 **   assert( sqlcipher3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
59948 */
59949 SQLCIPHER_PRIVATE int sqlcipher3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
59950   int hasAbort = 0;
59951   Op *pOp;
59952   VdbeOpIter sIter;
59953   memset(&sIter, 0, sizeof(sIter));
59954   sIter.v = v;
59955
59956   while( (pOp = opIterNext(&sIter))!=0 ){
59957     int opcode = pOp->opcode;
59958     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
59959 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
59960      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
59961 #endif
59962      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
59963       && (pOp->p1==SQLCIPHER_CONSTRAINT && pOp->p2==OE_Abort))
59964     ){
59965       hasAbort = 1;
59966       break;
59967     }
59968   }
59969   sqlcipher3DbFree(v->db, sIter.apSub);
59970
59971   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
59972   ** If malloc failed, then the while() loop above may not have iterated
59973   ** through all opcodes and hasAbort may be set incorrectly. Return
59974   ** true for this case to prevent the assert() in the callers frame
59975   ** from failing.  */
59976   return ( v->db->mallocFailed || hasAbort==mayAbort );
59977 }
59978 #endif /* SQLCIPHER_DEBUG - the sqlcipher3AssertMayAbort() function */
59979
59980 /*
59981 ** Loop through the program looking for P2 values that are negative
59982 ** on jump instructions.  Each such value is a label.  Resolve the
59983 ** label by setting the P2 value to its correct non-zero value.
59984 **
59985 ** This routine is called once after all opcodes have been inserted.
59986 **
59987 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
59988 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
59989 ** sqlcipher3VdbeMakeReady() to size the Vdbe.apArg[] array.
59990 **
59991 ** The Op.opflags field is set on all opcodes.
59992 */
59993 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
59994   int i;
59995   int nMaxArgs = *pMaxFuncArgs;
59996   Op *pOp;
59997   int *aLabel = p->aLabel;
59998   p->readOnly = 1;
59999   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
60000     u8 opcode = pOp->opcode;
60001
60002     pOp->opflags = sqlcipher3OpcodeProperty[opcode];
60003     if( opcode==OP_Function || opcode==OP_AggStep ){
60004       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
60005     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
60006       p->readOnly = 0;
60007 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
60008     }else if( opcode==OP_VUpdate ){
60009       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
60010     }else if( opcode==OP_VFilter ){
60011       int n;
60012       assert( p->nOp - i >= 3 );
60013       assert( pOp[-1].opcode==OP_Integer );
60014       n = pOp[-1].p1;
60015       if( n>nMaxArgs ) nMaxArgs = n;
60016 #endif
60017     }else if( opcode==OP_Next || opcode==OP_SorterNext ){
60018       pOp->p4.xAdvance = sqlcipher3BtreeNext;
60019       pOp->p4type = P4_ADVANCE;
60020     }else if( opcode==OP_Prev ){
60021       pOp->p4.xAdvance = sqlcipher3BtreePrevious;
60022       pOp->p4type = P4_ADVANCE;
60023     }
60024
60025     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
60026       assert( -1-pOp->p2<p->nLabel );
60027       pOp->p2 = aLabel[-1-pOp->p2];
60028     }
60029   }
60030   sqlcipher3DbFree(p->db, p->aLabel);
60031   p->aLabel = 0;
60032
60033   *pMaxFuncArgs = nMaxArgs;
60034 }
60035
60036 /*
60037 ** Return the address of the next instruction to be inserted.
60038 */
60039 SQLCIPHER_PRIVATE int sqlcipher3VdbeCurrentAddr(Vdbe *p){
60040   assert( p->magic==VDBE_MAGIC_INIT );
60041   return p->nOp;
60042 }
60043
60044 /*
60045 ** This function returns a pointer to the array of opcodes associated with
60046 ** the Vdbe passed as the first argument. It is the callers responsibility
60047 ** to arrange for the returned array to be eventually freed using the 
60048 ** vdbeFreeOpArray() function.
60049 **
60050 ** Before returning, *pnOp is set to the number of entries in the returned
60051 ** array. Also, *pnMaxArg is set to the larger of its current value and 
60052 ** the number of entries in the Vdbe.apArg[] array required to execute the 
60053 ** returned program.
60054 */
60055 SQLCIPHER_PRIVATE VdbeOp *sqlcipher3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
60056   VdbeOp *aOp = p->aOp;
60057   assert( aOp && !p->db->mallocFailed );
60058
60059   /* Check that sqlcipher3VdbeUsesBtree() was not called on this VM */
60060   assert( p->btreeMask==0 );
60061
60062   resolveP2Values(p, pnMaxArg);
60063   *pnOp = p->nOp;
60064   p->aOp = 0;
60065   return aOp;
60066 }
60067
60068 /*
60069 ** Add a whole list of operations to the operation stack.  Return the
60070 ** address of the first operation added.
60071 */
60072 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
60073   int addr;
60074   assert( p->magic==VDBE_MAGIC_INIT );
60075   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
60076     return 0;
60077   }
60078   addr = p->nOp;
60079   if( ALWAYS(nOp>0) ){
60080     int i;
60081     VdbeOpList const *pIn = aOp;
60082     for(i=0; i<nOp; i++, pIn++){
60083       int p2 = pIn->p2;
60084       VdbeOp *pOut = &p->aOp[i+addr];
60085       pOut->opcode = pIn->opcode;
60086       pOut->p1 = pIn->p1;
60087       if( p2<0 && (sqlcipher3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
60088         pOut->p2 = addr + ADDR(p2);
60089       }else{
60090         pOut->p2 = p2;
60091       }
60092       pOut->p3 = pIn->p3;
60093       pOut->p4type = P4_NOTUSED;
60094       pOut->p4.p = 0;
60095       pOut->p5 = 0;
60096 #ifdef SQLCIPHER_DEBUG
60097       pOut->zComment = 0;
60098       if( sqlcipher3VdbeAddopTrace ){
60099         sqlcipher3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
60100       }
60101 #endif
60102     }
60103     p->nOp += nOp;
60104   }
60105   return addr;
60106 }
60107
60108 /*
60109 ** Change the value of the P1 operand for a specific instruction.
60110 ** This routine is useful when a large program is loaded from a
60111 ** static array using sqlcipher3VdbeAddOpList but we want to make a
60112 ** few minor changes to the program.
60113 */
60114 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP1(Vdbe *p, u32 addr, int val){
60115   assert( p!=0 );
60116   if( ((u32)p->nOp)>addr ){
60117     p->aOp[addr].p1 = val;
60118   }
60119 }
60120
60121 /*
60122 ** Change the value of the P2 operand for a specific instruction.
60123 ** This routine is useful for setting a jump destination.
60124 */
60125 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP2(Vdbe *p, u32 addr, int val){
60126   assert( p!=0 );
60127   if( ((u32)p->nOp)>addr ){
60128     p->aOp[addr].p2 = val;
60129   }
60130 }
60131
60132 /*
60133 ** Change the value of the P3 operand for a specific instruction.
60134 */
60135 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP3(Vdbe *p, u32 addr, int val){
60136   assert( p!=0 );
60137   if( ((u32)p->nOp)>addr ){
60138     p->aOp[addr].p3 = val;
60139   }
60140 }
60141
60142 /*
60143 ** Change the value of the P5 operand for the most recently
60144 ** added operation.
60145 */
60146 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP5(Vdbe *p, u8 val){
60147   assert( p!=0 );
60148   if( p->aOp ){
60149     assert( p->nOp>0 );
60150     p->aOp[p->nOp-1].p5 = val;
60151   }
60152 }
60153
60154 /*
60155 ** Change the P2 operand of instruction addr so that it points to
60156 ** the address of the next instruction to be coded.
60157 */
60158 SQLCIPHER_PRIVATE void sqlcipher3VdbeJumpHere(Vdbe *p, int addr){
60159   assert( addr>=0 || p->db->mallocFailed );
60160   if( addr>=0 ) sqlcipher3VdbeChangeP2(p, addr, p->nOp);
60161 }
60162
60163
60164 /*
60165 ** If the input FuncDef structure is ephemeral, then free it.  If
60166 ** the FuncDef is not ephermal, then do nothing.
60167 */
60168 static void freeEphemeralFunction(sqlcipher3 *db, FuncDef *pDef){
60169   if( ALWAYS(pDef) && (pDef->flags & SQLCIPHER_FUNC_EPHEM)!=0 ){
60170     sqlcipher3DbFree(db, pDef);
60171   }
60172 }
60173
60174 static void vdbeFreeOpArray(sqlcipher3 *, Op *, int);
60175
60176 /*
60177 ** Delete a P4 value if necessary.
60178 */
60179 static void freeP4(sqlcipher3 *db, int p4type, void *p4){
60180   if( p4 ){
60181     assert( db );
60182     switch( p4type ){
60183       case P4_REAL:
60184       case P4_INT64:
60185       case P4_DYNAMIC:
60186       case P4_KEYINFO:
60187       case P4_INTARRAY:
60188       case P4_KEYINFO_HANDOFF: {
60189         sqlcipher3DbFree(db, p4);
60190         break;
60191       }
60192       case P4_MPRINTF: {
60193         if( db->pnBytesFreed==0 ) sqlcipher3_free(p4);
60194         break;
60195       }
60196       case P4_VDBEFUNC: {
60197         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
60198         freeEphemeralFunction(db, pVdbeFunc->pFunc);
60199         if( db->pnBytesFreed==0 ) sqlcipher3VdbeDeleteAuxData(pVdbeFunc, 0);
60200         sqlcipher3DbFree(db, pVdbeFunc);
60201         break;
60202       }
60203       case P4_FUNCDEF: {
60204         freeEphemeralFunction(db, (FuncDef*)p4);
60205         break;
60206       }
60207       case P4_MEM: {
60208         if( db->pnBytesFreed==0 ){
60209           sqlcipher3ValueFree((sqlcipher3_value*)p4);
60210         }else{
60211           Mem *p = (Mem*)p4;
60212           sqlcipher3DbFree(db, p->zMalloc);
60213           sqlcipher3DbFree(db, p);
60214         }
60215         break;
60216       }
60217       case P4_VTAB : {
60218         if( db->pnBytesFreed==0 ) sqlcipher3VtabUnlock((VTable *)p4);
60219         break;
60220       }
60221     }
60222   }
60223 }
60224
60225 /*
60226 ** Free the space allocated for aOp and any p4 values allocated for the
60227 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
60228 ** nOp entries. 
60229 */
60230 static void vdbeFreeOpArray(sqlcipher3 *db, Op *aOp, int nOp){
60231   if( aOp ){
60232     Op *pOp;
60233     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
60234       freeP4(db, pOp->p4type, pOp->p4.p);
60235 #ifdef SQLCIPHER_DEBUG
60236       sqlcipher3DbFree(db, pOp->zComment);
60237 #endif     
60238     }
60239   }
60240   sqlcipher3DbFree(db, aOp);
60241 }
60242
60243 /*
60244 ** Link the SubProgram object passed as the second argument into the linked
60245 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
60246 ** objects when the VM is no longer required.
60247 */
60248 SQLCIPHER_PRIVATE void sqlcipher3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
60249   p->pNext = pVdbe->pProgram;
60250   pVdbe->pProgram = p;
60251 }
60252
60253 /*
60254 ** Change the opcode at addr into OP_Noop
60255 */
60256 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeToNoop(Vdbe *p, int addr){
60257   if( p->aOp ){
60258     VdbeOp *pOp = &p->aOp[addr];
60259     sqlcipher3 *db = p->db;
60260     freeP4(db, pOp->p4type, pOp->p4.p);
60261     memset(pOp, 0, sizeof(pOp[0]));
60262     pOp->opcode = OP_Noop;
60263   }
60264 }
60265
60266 /*
60267 ** Change the value of the P4 operand for a specific instruction.
60268 ** This routine is useful when a large program is loaded from a
60269 ** static array using sqlcipher3VdbeAddOpList but we want to make a
60270 ** few minor changes to the program.
60271 **
60272 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
60273 ** the string is made into memory obtained from sqlcipher3_malloc().
60274 ** A value of n==0 means copy bytes of zP4 up to and including the
60275 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
60276 **
60277 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
60278 ** A copy is made of the KeyInfo structure into memory obtained from
60279 ** sqlcipher3_malloc, to be freed when the Vdbe is finalized.
60280 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
60281 ** stored in memory that the caller has obtained from sqlcipher3_malloc. The 
60282 ** caller should not free the allocation, it will be freed when the Vdbe is
60283 ** finalized.
60284 ** 
60285 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
60286 ** to a string or structure that is guaranteed to exist for the lifetime of
60287 ** the Vdbe. In these cases we can just copy the pointer.
60288 **
60289 ** If addr<0 then change P4 on the most recently inserted instruction.
60290 */
60291 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
60292   Op *pOp;
60293   sqlcipher3 *db;
60294   assert( p!=0 );
60295   db = p->db;
60296   assert( p->magic==VDBE_MAGIC_INIT );
60297   if( p->aOp==0 || db->mallocFailed ){
60298     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
60299       freeP4(db, n, (void*)*(char**)&zP4);
60300     }
60301     return;
60302   }
60303   assert( p->nOp>0 );
60304   assert( addr<p->nOp );
60305   if( addr<0 ){
60306     addr = p->nOp - 1;
60307   }
60308   pOp = &p->aOp[addr];
60309   freeP4(db, pOp->p4type, pOp->p4.p);
60310   pOp->p4.p = 0;
60311   if( n==P4_INT32 ){
60312     /* Note: this cast is safe, because the origin data point was an int
60313     ** that was cast to a (const char *). */
60314     pOp->p4.i = SQLCIPHER_PTR_TO_INT(zP4);
60315     pOp->p4type = P4_INT32;
60316   }else if( zP4==0 ){
60317     pOp->p4.p = 0;
60318     pOp->p4type = P4_NOTUSED;
60319   }else if( n==P4_KEYINFO ){
60320     KeyInfo *pKeyInfo;
60321     int nField, nByte;
60322
60323     nField = ((KeyInfo*)zP4)->nField;
60324     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
60325     pKeyInfo = sqlcipher3DbMallocRaw(0, nByte);
60326     pOp->p4.pKeyInfo = pKeyInfo;
60327     if( pKeyInfo ){
60328       u8 *aSortOrder;
60329       memcpy((char*)pKeyInfo, zP4, nByte - nField);
60330       aSortOrder = pKeyInfo->aSortOrder;
60331       if( aSortOrder ){
60332         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
60333         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
60334       }
60335       pOp->p4type = P4_KEYINFO;
60336     }else{
60337       p->db->mallocFailed = 1;
60338       pOp->p4type = P4_NOTUSED;
60339     }
60340   }else if( n==P4_KEYINFO_HANDOFF ){
60341     pOp->p4.p = (void*)zP4;
60342     pOp->p4type = P4_KEYINFO;
60343   }else if( n==P4_VTAB ){
60344     pOp->p4.p = (void*)zP4;
60345     pOp->p4type = P4_VTAB;
60346     sqlcipher3VtabLock((VTable *)zP4);
60347     assert( ((VTable *)zP4)->db==p->db );
60348   }else if( n<0 ){
60349     pOp->p4.p = (void*)zP4;
60350     pOp->p4type = (signed char)n;
60351   }else{
60352     if( n==0 ) n = sqlcipher3Strlen30(zP4);
60353     pOp->p4.z = sqlcipher3DbStrNDup(p->db, zP4, n);
60354     pOp->p4type = P4_DYNAMIC;
60355   }
60356 }
60357
60358 #ifndef NDEBUG
60359 /*
60360 ** Change the comment on the the most recently coded instruction.  Or
60361 ** insert a No-op and add the comment to that new instruction.  This
60362 ** makes the code easier to read during debugging.  None of this happens
60363 ** in a production build.
60364 */
60365 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
60366   assert( p->nOp>0 || p->aOp==0 );
60367   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
60368   if( p->nOp ){
60369     assert( p->aOp );
60370     sqlcipher3DbFree(p->db, p->aOp[p->nOp-1].zComment);
60371     p->aOp[p->nOp-1].zComment = sqlcipher3VMPrintf(p->db, zFormat, ap);
60372   }
60373 }
60374 SQLCIPHER_PRIVATE void sqlcipher3VdbeComment(Vdbe *p, const char *zFormat, ...){
60375   va_list ap;
60376   if( p ){
60377     va_start(ap, zFormat);
60378     vdbeVComment(p, zFormat, ap);
60379     va_end(ap);
60380   }
60381 }
60382 SQLCIPHER_PRIVATE void sqlcipher3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
60383   va_list ap;
60384   if( p ){
60385     sqlcipher3VdbeAddOp0(p, OP_Noop);
60386     va_start(ap, zFormat);
60387     vdbeVComment(p, zFormat, ap);
60388     va_end(ap);
60389   }
60390 }
60391 #endif  /* NDEBUG */
60392
60393 /*
60394 ** Return the opcode for a given address.  If the address is -1, then
60395 ** return the most recently inserted opcode.
60396 **
60397 ** If a memory allocation error has occurred prior to the calling of this
60398 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
60399 ** is readable but not writable, though it is cast to a writable value.
60400 ** The return of a dummy opcode allows the call to continue functioning
60401 ** after a OOM fault without having to check to see if the return from 
60402 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
60403 ** dummy will never be written to.  This is verified by code inspection and
60404 ** by running with Valgrind.
60405 **
60406 ** About the #ifdef SQLCIPHER_OMIT_TRACE:  Normally, this routine is never called
60407 ** unless p->nOp>0.  This is because in the absense of SQLCIPHER_OMIT_TRACE,
60408 ** an OP_Trace instruction is always inserted by sqlcipher3VdbeGet() as soon as
60409 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
60410 ** having to double-check to make sure that the result is non-negative. But
60411 ** if SQLCIPHER_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
60412 ** check the value of p->nOp-1 before continuing.
60413 */
60414 SQLCIPHER_PRIVATE VdbeOp *sqlcipher3VdbeGetOp(Vdbe *p, int addr){
60415   /* C89 specifies that the constant "dummy" will be initialized to all
60416   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
60417   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
60418   assert( p->magic==VDBE_MAGIC_INIT );
60419   if( addr<0 ){
60420 #ifdef SQLCIPHER_OMIT_TRACE
60421     if( p->nOp==0 ) return (VdbeOp*)&dummy;
60422 #endif
60423     addr = p->nOp - 1;
60424   }
60425   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
60426   if( p->db->mallocFailed ){
60427     return (VdbeOp*)&dummy;
60428   }else{
60429     return &p->aOp[addr];
60430   }
60431 }
60432
60433 #if !defined(SQLCIPHER_OMIT_EXPLAIN) || !defined(NDEBUG) \
60434      || defined(VDBE_PROFILE) || defined(SQLCIPHER_DEBUG)
60435 /*
60436 ** Compute a string that describes the P4 parameter for an opcode.
60437 ** Use zTemp for any required temporary buffer space.
60438 */
60439 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
60440   char *zP4 = zTemp;
60441   assert( nTemp>=20 );
60442   switch( pOp->p4type ){
60443     case P4_KEYINFO_STATIC:
60444     case P4_KEYINFO: {
60445       int i, j;
60446       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
60447       sqlcipher3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
60448       i = sqlcipher3Strlen30(zTemp);
60449       for(j=0; j<pKeyInfo->nField; j++){
60450         CollSeq *pColl = pKeyInfo->aColl[j];
60451         if( pColl ){
60452           int n = sqlcipher3Strlen30(pColl->zName);
60453           if( i+n>nTemp-6 ){
60454             memcpy(&zTemp[i],",...",4);
60455             break;
60456           }
60457           zTemp[i++] = ',';
60458           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
60459             zTemp[i++] = '-';
60460           }
60461           memcpy(&zTemp[i], pColl->zName,n+1);
60462           i += n;
60463         }else if( i+4<nTemp-6 ){
60464           memcpy(&zTemp[i],",nil",4);
60465           i += 4;
60466         }
60467       }
60468       zTemp[i++] = ')';
60469       zTemp[i] = 0;
60470       assert( i<nTemp );
60471       break;
60472     }
60473     case P4_COLLSEQ: {
60474       CollSeq *pColl = pOp->p4.pColl;
60475       sqlcipher3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
60476       break;
60477     }
60478     case P4_FUNCDEF: {
60479       FuncDef *pDef = pOp->p4.pFunc;
60480       sqlcipher3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
60481       break;
60482     }
60483     case P4_INT64: {
60484       sqlcipher3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
60485       break;
60486     }
60487     case P4_INT32: {
60488       sqlcipher3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
60489       break;
60490     }
60491     case P4_REAL: {
60492       sqlcipher3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
60493       break;
60494     }
60495     case P4_MEM: {
60496       Mem *pMem = pOp->p4.pMem;
60497       assert( (pMem->flags & MEM_Null)==0 );
60498       if( pMem->flags & MEM_Str ){
60499         zP4 = pMem->z;
60500       }else if( pMem->flags & MEM_Int ){
60501         sqlcipher3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
60502       }else if( pMem->flags & MEM_Real ){
60503         sqlcipher3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
60504       }else{
60505         assert( pMem->flags & MEM_Blob );
60506         zP4 = "(blob)";
60507       }
60508       break;
60509     }
60510 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
60511     case P4_VTAB: {
60512       sqlcipher3_vtab *pVtab = pOp->p4.pVtab->pVtab;
60513       sqlcipher3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
60514       break;
60515     }
60516 #endif
60517     case P4_INTARRAY: {
60518       sqlcipher3_snprintf(nTemp, zTemp, "intarray");
60519       break;
60520     }
60521     case P4_SUBPROGRAM: {
60522       sqlcipher3_snprintf(nTemp, zTemp, "program");
60523       break;
60524     }
60525     case P4_ADVANCE: {
60526       zTemp[0] = 0;
60527       break;
60528     }
60529     default: {
60530       zP4 = pOp->p4.z;
60531       if( zP4==0 ){
60532         zP4 = zTemp;
60533         zTemp[0] = 0;
60534       }
60535     }
60536   }
60537   assert( zP4!=0 );
60538   return zP4;
60539 }
60540 #endif
60541
60542 /*
60543 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
60544 **
60545 ** The prepared statements need to know in advance the complete set of
60546 ** attached databases that they will be using.  A mask of these databases
60547 ** is maintained in p->btreeMask and is used for locking and other purposes.
60548 */
60549 SQLCIPHER_PRIVATE void sqlcipher3VdbeUsesBtree(Vdbe *p, int i){
60550   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
60551   assert( i<(int)sizeof(p->btreeMask)*8 );
60552   p->btreeMask |= ((yDbMask)1)<<i;
60553   if( i!=1 && sqlcipher3BtreeSharable(p->db->aDb[i].pBt) ){
60554     p->lockMask |= ((yDbMask)1)<<i;
60555   }
60556 }
60557
60558 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && SQLCIPHER_THREADSAFE>0
60559 /*
60560 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
60561 ** this routine obtains the mutex associated with each BtShared structure
60562 ** that may be accessed by the VM passed as an argument. In doing so it also
60563 ** sets the BtShared.db member of each of the BtShared structures, ensuring
60564 ** that the correct busy-handler callback is invoked if required.
60565 **
60566 ** If SQLite is not threadsafe but does support shared-cache mode, then
60567 ** sqlcipher3BtreeEnter() is invoked to set the BtShared.db variables
60568 ** of all of BtShared structures accessible via the database handle 
60569 ** associated with the VM.
60570 **
60571 ** If SQLite is not threadsafe and does not support shared-cache mode, this
60572 ** function is a no-op.
60573 **
60574 ** The p->btreeMask field is a bitmask of all btrees that the prepared 
60575 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
60576 ** corresponding to btrees that use shared cache.  Then the runtime of
60577 ** this routine is N*N.  But as N is rarely more than 1, this should not
60578 ** be a problem.
60579 */
60580 SQLCIPHER_PRIVATE void sqlcipher3VdbeEnter(Vdbe *p){
60581   int i;
60582   yDbMask mask;
60583   sqlcipher3 *db;
60584   Db *aDb;
60585   int nDb;
60586   if( p->lockMask==0 ) return;  /* The common case */
60587   db = p->db;
60588   aDb = db->aDb;
60589   nDb = db->nDb;
60590   for(i=0, mask=1; i<nDb; i++, mask += mask){
60591     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
60592       sqlcipher3BtreeEnter(aDb[i].pBt);
60593     }
60594   }
60595 }
60596 #endif
60597
60598 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && SQLCIPHER_THREADSAFE>0
60599 /*
60600 ** Unlock all of the btrees previously locked by a call to sqlcipher3VdbeEnter().
60601 */
60602 SQLCIPHER_PRIVATE void sqlcipher3VdbeLeave(Vdbe *p){
60603   int i;
60604   yDbMask mask;
60605   sqlcipher3 *db;
60606   Db *aDb;
60607   int nDb;
60608   if( p->lockMask==0 ) return;  /* The common case */
60609   db = p->db;
60610   aDb = db->aDb;
60611   nDb = db->nDb;
60612   for(i=0, mask=1; i<nDb; i++, mask += mask){
60613     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
60614       sqlcipher3BtreeLeave(aDb[i].pBt);
60615     }
60616   }
60617 }
60618 #endif
60619
60620 #if defined(VDBE_PROFILE) || defined(SQLCIPHER_DEBUG)
60621 /*
60622 ** Print a single opcode.  This routine is used for debugging only.
60623 */
60624 SQLCIPHER_PRIVATE void sqlcipher3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
60625   char *zP4;
60626   char zPtr[50];
60627   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
60628   if( pOut==0 ) pOut = stdout;
60629   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
60630   fprintf(pOut, zFormat1, pc, 
60631       sqlcipher3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
60632 #ifdef SQLCIPHER_DEBUG
60633       pOp->zComment ? pOp->zComment : ""
60634 #else
60635       ""
60636 #endif
60637   );
60638   fflush(pOut);
60639 }
60640 #endif
60641
60642 /*
60643 ** Release an array of N Mem elements
60644 */
60645 static void releaseMemArray(Mem *p, int N){
60646   if( p && N ){
60647     Mem *pEnd;
60648     sqlcipher3 *db = p->db;
60649     u8 malloc_failed = db->mallocFailed;
60650     if( db->pnBytesFreed ){
60651       for(pEnd=&p[N]; p<pEnd; p++){
60652         sqlcipher3DbFree(db, p->zMalloc);
60653       }
60654       return;
60655     }
60656     for(pEnd=&p[N]; p<pEnd; p++){
60657       assert( (&p[1])==pEnd || p[0].db==p[1].db );
60658
60659       /* This block is really an inlined version of sqlcipher3VdbeMemRelease()
60660       ** that takes advantage of the fact that the memory cell value is 
60661       ** being set to NULL after releasing any dynamic resources.
60662       **
60663       ** The justification for duplicating code is that according to 
60664       ** callgrind, this causes a certain test case to hit the CPU 4.7 
60665       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
60666       ** sqlcipher3MemRelease() were called from here. With -O2, this jumps
60667       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
60668       ** with no indexes using a single prepared INSERT statement, bind() 
60669       ** and reset(). Inserts are grouped into a transaction.
60670       */
60671       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
60672         sqlcipher3VdbeMemRelease(p);
60673       }else if( p->zMalloc ){
60674         sqlcipher3DbFree(db, p->zMalloc);
60675         p->zMalloc = 0;
60676       }
60677
60678       p->flags = MEM_Null;
60679     }
60680     db->mallocFailed = malloc_failed;
60681   }
60682 }
60683
60684 /*
60685 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
60686 ** allocated by the OP_Program opcode in sqlcipher3VdbeExec().
60687 */
60688 SQLCIPHER_PRIVATE void sqlcipher3VdbeFrameDelete(VdbeFrame *p){
60689   int i;
60690   Mem *aMem = VdbeFrameMem(p);
60691   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
60692   for(i=0; i<p->nChildCsr; i++){
60693     sqlcipher3VdbeFreeCursor(p->v, apCsr[i]);
60694   }
60695   releaseMemArray(aMem, p->nChildMem);
60696   sqlcipher3DbFree(p->v->db, p);
60697 }
60698
60699 #ifndef SQLCIPHER_OMIT_EXPLAIN
60700 /*
60701 ** Give a listing of the program in the virtual machine.
60702 **
60703 ** The interface is the same as sqlcipher3VdbeExec().  But instead of
60704 ** running the code, it invokes the callback once for each instruction.
60705 ** This feature is used to implement "EXPLAIN".
60706 **
60707 ** When p->explain==1, each instruction is listed.  When
60708 ** p->explain==2, only OP_Explain instructions are listed and these
60709 ** are shown in a different format.  p->explain==2 is used to implement
60710 ** EXPLAIN QUERY PLAN.
60711 **
60712 ** When p->explain==1, first the main program is listed, then each of
60713 ** the trigger subprograms are listed one by one.
60714 */
60715 SQLCIPHER_PRIVATE int sqlcipher3VdbeList(
60716   Vdbe *p                   /* The VDBE */
60717 ){
60718   int nRow;                            /* Stop when row count reaches this */
60719   int nSub = 0;                        /* Number of sub-vdbes seen so far */
60720   SubProgram **apSub = 0;              /* Array of sub-vdbes */
60721   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
60722   sqlcipher3 *db = p->db;                 /* The database connection */
60723   int i;                               /* Loop counter */
60724   int rc = SQLCIPHER_OK;                  /* Return code */
60725   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
60726
60727   assert( p->explain );
60728   assert( p->magic==VDBE_MAGIC_RUN );
60729   assert( p->rc==SQLCIPHER_OK || p->rc==SQLCIPHER_BUSY || p->rc==SQLCIPHER_NOMEM );
60730
60731   /* Even though this opcode does not use dynamic strings for
60732   ** the result, result columns may become dynamic if the user calls
60733   ** sqlcipher3_column_text16(), causing a translation to UTF-16 encoding.
60734   */
60735   releaseMemArray(pMem, 8);
60736   p->pResultSet = 0;
60737
60738   if( p->rc==SQLCIPHER_NOMEM ){
60739     /* This happens if a malloc() inside a call to sqlcipher3_column_text() or
60740     ** sqlcipher3_column_text16() failed.  */
60741     db->mallocFailed = 1;
60742     return SQLCIPHER_ERROR;
60743   }
60744
60745   /* When the number of output rows reaches nRow, that means the
60746   ** listing has finished and sqlcipher3_step() should return SQLCIPHER_DONE.
60747   ** nRow is the sum of the number of rows in the main program, plus
60748   ** the sum of the number of rows in all trigger subprograms encountered
60749   ** so far.  The nRow value will increase as new trigger subprograms are
60750   ** encountered, but p->pc will eventually catch up to nRow.
60751   */
60752   nRow = p->nOp;
60753   if( p->explain==1 ){
60754     /* The first 8 memory cells are used for the result set.  So we will
60755     ** commandeer the 9th cell to use as storage for an array of pointers
60756     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
60757     ** cells.  */
60758     assert( p->nMem>9 );
60759     pSub = &p->aMem[9];
60760     if( pSub->flags&MEM_Blob ){
60761       /* On the first call to sqlcipher3_step(), pSub will hold a NULL.  It is
60762       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
60763       nSub = pSub->n/sizeof(Vdbe*);
60764       apSub = (SubProgram **)pSub->z;
60765     }
60766     for(i=0; i<nSub; i++){
60767       nRow += apSub[i]->nOp;
60768     }
60769   }
60770
60771   do{
60772     i = p->pc++;
60773   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
60774   if( i>=nRow ){
60775     p->rc = SQLCIPHER_OK;
60776     rc = SQLCIPHER_DONE;
60777   }else if( db->u1.isInterrupted ){
60778     p->rc = SQLCIPHER_INTERRUPT;
60779     rc = SQLCIPHER_ERROR;
60780     sqlcipher3SetString(&p->zErrMsg, db, "%s", sqlcipher3ErrStr(p->rc));
60781   }else{
60782     char *z;
60783     Op *pOp;
60784     if( i<p->nOp ){
60785       /* The output line number is small enough that we are still in the
60786       ** main program. */
60787       pOp = &p->aOp[i];
60788     }else{
60789       /* We are currently listing subprograms.  Figure out which one and
60790       ** pick up the appropriate opcode. */
60791       int j;
60792       i -= p->nOp;
60793       for(j=0; i>=apSub[j]->nOp; j++){
60794         i -= apSub[j]->nOp;
60795       }
60796       pOp = &apSub[j]->aOp[i];
60797     }
60798     if( p->explain==1 ){
60799       pMem->flags = MEM_Int;
60800       pMem->type = SQLCIPHER_INTEGER;
60801       pMem->u.i = i;                                /* Program counter */
60802       pMem++;
60803   
60804       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
60805       pMem->z = (char*)sqlcipher3OpcodeName(pOp->opcode);  /* Opcode */
60806       assert( pMem->z!=0 );
60807       pMem->n = sqlcipher3Strlen30(pMem->z);
60808       pMem->type = SQLCIPHER_TEXT;
60809       pMem->enc = SQLCIPHER_UTF8;
60810       pMem++;
60811
60812       /* When an OP_Program opcode is encounter (the only opcode that has
60813       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
60814       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
60815       ** has not already been seen.
60816       */
60817       if( pOp->p4type==P4_SUBPROGRAM ){
60818         int nByte = (nSub+1)*sizeof(SubProgram*);
60819         int j;
60820         for(j=0; j<nSub; j++){
60821           if( apSub[j]==pOp->p4.pProgram ) break;
60822         }
60823         if( j==nSub && SQLCIPHER_OK==sqlcipher3VdbeMemGrow(pSub, nByte, 1) ){
60824           apSub = (SubProgram **)pSub->z;
60825           apSub[nSub++] = pOp->p4.pProgram;
60826           pSub->flags |= MEM_Blob;
60827           pSub->n = nSub*sizeof(SubProgram*);
60828         }
60829       }
60830     }
60831
60832     pMem->flags = MEM_Int;
60833     pMem->u.i = pOp->p1;                          /* P1 */
60834     pMem->type = SQLCIPHER_INTEGER;
60835     pMem++;
60836
60837     pMem->flags = MEM_Int;
60838     pMem->u.i = pOp->p2;                          /* P2 */
60839     pMem->type = SQLCIPHER_INTEGER;
60840     pMem++;
60841
60842     pMem->flags = MEM_Int;
60843     pMem->u.i = pOp->p3;                          /* P3 */
60844     pMem->type = SQLCIPHER_INTEGER;
60845     pMem++;
60846
60847     if( sqlcipher3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
60848       assert( p->db->mallocFailed );
60849       return SQLCIPHER_ERROR;
60850     }
60851     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
60852     z = displayP4(pOp, pMem->z, 32);
60853     if( z!=pMem->z ){
60854       sqlcipher3VdbeMemSetStr(pMem, z, -1, SQLCIPHER_UTF8, 0);
60855     }else{
60856       assert( pMem->z!=0 );
60857       pMem->n = sqlcipher3Strlen30(pMem->z);
60858       pMem->enc = SQLCIPHER_UTF8;
60859     }
60860     pMem->type = SQLCIPHER_TEXT;
60861     pMem++;
60862
60863     if( p->explain==1 ){
60864       if( sqlcipher3VdbeMemGrow(pMem, 4, 0) ){
60865         assert( p->db->mallocFailed );
60866         return SQLCIPHER_ERROR;
60867       }
60868       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
60869       pMem->n = 2;
60870       sqlcipher3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
60871       pMem->type = SQLCIPHER_TEXT;
60872       pMem->enc = SQLCIPHER_UTF8;
60873       pMem++;
60874   
60875 #ifdef SQLCIPHER_DEBUG
60876       if( pOp->zComment ){
60877         pMem->flags = MEM_Str|MEM_Term;
60878         pMem->z = pOp->zComment;
60879         pMem->n = sqlcipher3Strlen30(pMem->z);
60880         pMem->enc = SQLCIPHER_UTF8;
60881         pMem->type = SQLCIPHER_TEXT;
60882       }else
60883 #endif
60884       {
60885         pMem->flags = MEM_Null;                       /* Comment */
60886         pMem->type = SQLCIPHER_NULL;
60887       }
60888     }
60889
60890     p->nResColumn = 8 - 4*(p->explain-1);
60891     p->pResultSet = &p->aMem[1];
60892     p->rc = SQLCIPHER_OK;
60893     rc = SQLCIPHER_ROW;
60894   }
60895   return rc;
60896 }
60897 #endif /* SQLCIPHER_OMIT_EXPLAIN */
60898
60899 #ifdef SQLCIPHER_DEBUG
60900 /*
60901 ** Print the SQL that was used to generate a VDBE program.
60902 */
60903 SQLCIPHER_PRIVATE void sqlcipher3VdbePrintSql(Vdbe *p){
60904   int nOp = p->nOp;
60905   VdbeOp *pOp;
60906   if( nOp<1 ) return;
60907   pOp = &p->aOp[0];
60908   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
60909     const char *z = pOp->p4.z;
60910     while( sqlcipher3Isspace(*z) ) z++;
60911     printf("SQL: [%s]\n", z);
60912   }
60913 }
60914 #endif
60915
60916 #if !defined(SQLCIPHER_OMIT_TRACE) && defined(SQLCIPHER_ENABLE_IOTRACE)
60917 /*
60918 ** Print an IOTRACE message showing SQL content.
60919 */
60920 SQLCIPHER_PRIVATE void sqlcipher3VdbeIOTraceSql(Vdbe *p){
60921   int nOp = p->nOp;
60922   VdbeOp *pOp;
60923   if( sqlcipher3IoTrace==0 ) return;
60924   if( nOp<1 ) return;
60925   pOp = &p->aOp[0];
60926   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
60927     int i, j;
60928     char z[1000];
60929     sqlcipher3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
60930     for(i=0; sqlcipher3Isspace(z[i]); i++){}
60931     for(j=0; z[i]; i++){
60932       if( sqlcipher3Isspace(z[i]) ){
60933         if( z[i-1]!=' ' ){
60934           z[j++] = ' ';
60935         }
60936       }else{
60937         z[j++] = z[i];
60938       }
60939     }
60940     z[j] = 0;
60941     sqlcipher3IoTrace("SQL %s\n", z);
60942   }
60943 }
60944 #endif /* !SQLCIPHER_OMIT_TRACE && SQLCIPHER_ENABLE_IOTRACE */
60945
60946 /*
60947 ** Allocate space from a fixed size buffer and return a pointer to
60948 ** that space.  If insufficient space is available, return NULL.
60949 **
60950 ** The pBuf parameter is the initial value of a pointer which will
60951 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
60952 ** NULL, it means that memory space has already been allocated and that
60953 ** this routine should not allocate any new memory.  When pBuf is not
60954 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
60955 ** is NULL.
60956 **
60957 ** nByte is the number of bytes of space needed.
60958 **
60959 ** *ppFrom points to available space and pEnd points to the end of the
60960 ** available space.  When space is allocated, *ppFrom is advanced past
60961 ** the end of the allocated space.
60962 **
60963 ** *pnByte is a counter of the number of bytes of space that have failed
60964 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
60965 ** request, then increment *pnByte by the amount of the request.
60966 */
60967 static void *allocSpace(
60968   void *pBuf,          /* Where return pointer will be stored */
60969   int nByte,           /* Number of bytes to allocate */
60970   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
60971   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
60972   int *pnByte          /* If allocation cannot be made, increment *pnByte */
60973 ){
60974   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
60975   if( pBuf ) return pBuf;
60976   nByte = ROUND8(nByte);
60977   if( &(*ppFrom)[nByte] <= pEnd ){
60978     pBuf = (void*)*ppFrom;
60979     *ppFrom += nByte;
60980   }else{
60981     *pnByte += nByte;
60982   }
60983   return pBuf;
60984 }
60985
60986 /*
60987 ** Rewind the VDBE back to the beginning in preparation for
60988 ** running it.
60989 */
60990 SQLCIPHER_PRIVATE void sqlcipher3VdbeRewind(Vdbe *p){
60991 #if defined(SQLCIPHER_DEBUG) || defined(VDBE_PROFILE)
60992   int i;
60993 #endif
60994   assert( p!=0 );
60995   assert( p->magic==VDBE_MAGIC_INIT );
60996
60997   /* There should be at least one opcode.
60998   */
60999   assert( p->nOp>0 );
61000
61001   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
61002   p->magic = VDBE_MAGIC_RUN;
61003
61004 #ifdef SQLCIPHER_DEBUG
61005   for(i=1; i<p->nMem; i++){
61006     assert( p->aMem[i].db==p->db );
61007   }
61008 #endif
61009   p->pc = -1;
61010   p->rc = SQLCIPHER_OK;
61011   p->errorAction = OE_Abort;
61012   p->magic = VDBE_MAGIC_RUN;
61013   p->nChange = 0;
61014   p->cacheCtr = 1;
61015   p->minWriteFileFormat = 255;
61016   p->iStatement = 0;
61017   p->nFkConstraint = 0;
61018 #ifdef VDBE_PROFILE
61019   for(i=0; i<p->nOp; i++){
61020     p->aOp[i].cnt = 0;
61021     p->aOp[i].cycles = 0;
61022   }
61023 #endif
61024 }
61025
61026 /*
61027 ** Prepare a virtual machine for execution for the first time after
61028 ** creating the virtual machine.  This involves things such
61029 ** as allocating stack space and initializing the program counter.
61030 ** After the VDBE has be prepped, it can be executed by one or more
61031 ** calls to sqlcipher3VdbeExec().  
61032 **
61033 ** This function may be called exact once on a each virtual machine.
61034 ** After this routine is called the VM has been "packaged" and is ready
61035 ** to run.  After this routine is called, futher calls to 
61036 ** sqlcipher3VdbeAddOp() functions are prohibited.  This routine disconnects
61037 ** the Vdbe from the Parse object that helped generate it so that the
61038 ** the Vdbe becomes an independent entity and the Parse object can be
61039 ** destroyed.
61040 **
61041 ** Use the sqlcipher3VdbeRewind() procedure to restore a virtual machine back
61042 ** to its initial state after it has been run.
61043 */
61044 SQLCIPHER_PRIVATE void sqlcipher3VdbeMakeReady(
61045   Vdbe *p,                       /* The VDBE */
61046   Parse *pParse                  /* Parsing context */
61047 ){
61048   sqlcipher3 *db;                   /* The database connection */
61049   int nVar;                      /* Number of parameters */
61050   int nMem;                      /* Number of VM memory registers */
61051   int nCursor;                   /* Number of cursors required */
61052   int nArg;                      /* Number of arguments in subprograms */
61053   int n;                         /* Loop counter */
61054   u8 *zCsr;                      /* Memory available for allocation */
61055   u8 *zEnd;                      /* First byte past allocated memory */
61056   int nByte;                     /* How much extra memory is needed */
61057
61058   assert( p!=0 );
61059   assert( p->nOp>0 );
61060   assert( pParse!=0 );
61061   assert( p->magic==VDBE_MAGIC_INIT );
61062   db = p->db;
61063   assert( db->mallocFailed==0 );
61064   nVar = pParse->nVar;
61065   nMem = pParse->nMem;
61066   nCursor = pParse->nTab;
61067   nArg = pParse->nMaxArg;
61068   
61069   /* For each cursor required, also allocate a memory cell. Memory
61070   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
61071   ** the vdbe program. Instead they are used to allocate space for
61072   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
61073   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
61074   ** stores the blob of memory associated with cursor 1, etc.
61075   **
61076   ** See also: allocateCursor().
61077   */
61078   nMem += nCursor;
61079
61080   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
61081   ** an array to marshal SQL function arguments in.
61082   */
61083   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
61084   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
61085
61086   resolveP2Values(p, &nArg);
61087   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
61088   if( pParse->explain && nMem<10 ){
61089     nMem = 10;
61090   }
61091   memset(zCsr, 0, zEnd-zCsr);
61092   zCsr += (zCsr - (u8*)0)&7;
61093   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
61094   p->expired = 0;
61095
61096   /* Memory for registers, parameters, cursor, etc, is allocated in two
61097   ** passes.  On the first pass, we try to reuse unused space at the 
61098   ** end of the opcode array.  If we are unable to satisfy all memory
61099   ** requirements by reusing the opcode array tail, then the second
61100   ** pass will fill in the rest using a fresh allocation.  
61101   **
61102   ** This two-pass approach that reuses as much memory as possible from
61103   ** the leftover space at the end of the opcode array can significantly
61104   ** reduce the amount of memory held by a prepared statement.
61105   */
61106   do {
61107     nByte = 0;
61108     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
61109     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
61110     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
61111     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
61112     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
61113                           &zCsr, zEnd, &nByte);
61114     if( nByte ){
61115       p->pFree = sqlcipher3DbMallocZero(db, nByte);
61116     }
61117     zCsr = p->pFree;
61118     zEnd = &zCsr[nByte];
61119   }while( nByte && !db->mallocFailed );
61120
61121   p->nCursor = (u16)nCursor;
61122   if( p->aVar ){
61123     p->nVar = (ynVar)nVar;
61124     for(n=0; n<nVar; n++){
61125       p->aVar[n].flags = MEM_Null;
61126       p->aVar[n].db = db;
61127     }
61128   }
61129   if( p->azVar ){
61130     p->nzVar = pParse->nzVar;
61131     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
61132     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
61133   }
61134   if( p->aMem ){
61135     p->aMem--;                      /* aMem[] goes from 1..nMem */
61136     p->nMem = nMem;                 /*       not from 0..nMem-1 */
61137     for(n=1; n<=nMem; n++){
61138       p->aMem[n].flags = MEM_Null;
61139       p->aMem[n].db = db;
61140     }
61141   }
61142   p->explain = pParse->explain;
61143   sqlcipher3VdbeRewind(p);
61144 }
61145
61146 /*
61147 ** Close a VDBE cursor and release all the resources that cursor 
61148 ** happens to hold.
61149 */
61150 SQLCIPHER_PRIVATE void sqlcipher3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
61151   if( pCx==0 ){
61152     return;
61153   }
61154   sqlcipher3VdbeSorterClose(p->db, pCx);
61155   if( pCx->pBt ){
61156     sqlcipher3BtreeClose(pCx->pBt);
61157     /* The pCx->pCursor will be close automatically, if it exists, by
61158     ** the call above. */
61159   }else if( pCx->pCursor ){
61160     sqlcipher3BtreeCloseCursor(pCx->pCursor);
61161   }
61162 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
61163   if( pCx->pVtabCursor ){
61164     sqlcipher3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
61165     const sqlcipher3_module *pModule = pCx->pModule;
61166     p->inVtabMethod = 1;
61167     pModule->xClose(pVtabCursor);
61168     p->inVtabMethod = 0;
61169   }
61170 #endif
61171 }
61172
61173 /*
61174 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
61175 ** is used, for example, when a trigger sub-program is halted to restore
61176 ** control to the main program.
61177 */
61178 SQLCIPHER_PRIVATE int sqlcipher3VdbeFrameRestore(VdbeFrame *pFrame){
61179   Vdbe *v = pFrame->v;
61180   v->aOp = pFrame->aOp;
61181   v->nOp = pFrame->nOp;
61182   v->aMem = pFrame->aMem;
61183   v->nMem = pFrame->nMem;
61184   v->apCsr = pFrame->apCsr;
61185   v->nCursor = pFrame->nCursor;
61186   v->db->lastRowid = pFrame->lastRowid;
61187   v->nChange = pFrame->nChange;
61188   return pFrame->pc;
61189 }
61190
61191 /*
61192 ** Close all cursors.
61193 **
61194 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
61195 ** cell array. This is necessary as the memory cell array may contain
61196 ** pointers to VdbeFrame objects, which may in turn contain pointers to
61197 ** open cursors.
61198 */
61199 static void closeAllCursors(Vdbe *p){
61200   if( p->pFrame ){
61201     VdbeFrame *pFrame;
61202     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
61203     sqlcipher3VdbeFrameRestore(pFrame);
61204   }
61205   p->pFrame = 0;
61206   p->nFrame = 0;
61207
61208   if( p->apCsr ){
61209     int i;
61210     for(i=0; i<p->nCursor; i++){
61211       VdbeCursor *pC = p->apCsr[i];
61212       if( pC ){
61213         sqlcipher3VdbeFreeCursor(p, pC);
61214         p->apCsr[i] = 0;
61215       }
61216     }
61217   }
61218   if( p->aMem ){
61219     releaseMemArray(&p->aMem[1], p->nMem);
61220   }
61221   while( p->pDelFrame ){
61222     VdbeFrame *pDel = p->pDelFrame;
61223     p->pDelFrame = pDel->pParent;
61224     sqlcipher3VdbeFrameDelete(pDel);
61225   }
61226 }
61227
61228 /*
61229 ** Clean up the VM after execution.
61230 **
61231 ** This routine will automatically close any cursors, lists, and/or
61232 ** sorters that were left open.  It also deletes the values of
61233 ** variables in the aVar[] array.
61234 */
61235 static void Cleanup(Vdbe *p){
61236   sqlcipher3 *db = p->db;
61237
61238 #ifdef SQLCIPHER_DEBUG
61239   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
61240   ** Vdbe.aMem[] arrays have already been cleaned up.  */
61241   int i;
61242   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
61243   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
61244 #endif
61245
61246   sqlcipher3DbFree(db, p->zErrMsg);
61247   p->zErrMsg = 0;
61248   p->pResultSet = 0;
61249 }
61250
61251 /*
61252 ** Set the number of result columns that will be returned by this SQL
61253 ** statement. This is now set at compile time, rather than during
61254 ** execution of the vdbe program so that sqlcipher3_column_count() can
61255 ** be called on an SQL statement before sqlcipher3_step().
61256 */
61257 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetNumCols(Vdbe *p, int nResColumn){
61258   Mem *pColName;
61259   int n;
61260   sqlcipher3 *db = p->db;
61261
61262   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
61263   sqlcipher3DbFree(db, p->aColName);
61264   n = nResColumn*COLNAME_N;
61265   p->nResColumn = (u16)nResColumn;
61266   p->aColName = pColName = (Mem*)sqlcipher3DbMallocZero(db, sizeof(Mem)*n );
61267   if( p->aColName==0 ) return;
61268   while( n-- > 0 ){
61269     pColName->flags = MEM_Null;
61270     pColName->db = p->db;
61271     pColName++;
61272   }
61273 }
61274
61275 /*
61276 ** Set the name of the idx'th column to be returned by the SQL statement.
61277 ** zName must be a pointer to a nul terminated string.
61278 **
61279 ** This call must be made after a call to sqlcipher3VdbeSetNumCols().
61280 **
61281 ** The final parameter, xDel, must be one of SQLCIPHER_DYNAMIC, SQLCIPHER_STATIC
61282 ** or SQLCIPHER_TRANSIENT. If it is SQLCIPHER_DYNAMIC, then the buffer pointed
61283 ** to by zName will be freed by sqlcipher3DbFree() when the vdbe is destroyed.
61284 */
61285 SQLCIPHER_PRIVATE int sqlcipher3VdbeSetColName(
61286   Vdbe *p,                         /* Vdbe being configured */
61287   int idx,                         /* Index of column zName applies to */
61288   int var,                         /* One of the COLNAME_* constants */
61289   const char *zName,               /* Pointer to buffer containing name */
61290   void (*xDel)(void*)              /* Memory management strategy for zName */
61291 ){
61292   int rc;
61293   Mem *pColName;
61294   assert( idx<p->nResColumn );
61295   assert( var<COLNAME_N );
61296   if( p->db->mallocFailed ){
61297     assert( !zName || xDel!=SQLCIPHER_DYNAMIC );
61298     return SQLCIPHER_NOMEM;
61299   }
61300   assert( p->aColName!=0 );
61301   pColName = &(p->aColName[idx+var*p->nResColumn]);
61302   rc = sqlcipher3VdbeMemSetStr(pColName, zName, -1, SQLCIPHER_UTF8, xDel);
61303   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
61304   return rc;
61305 }
61306
61307 /*
61308 ** A read or write transaction may or may not be active on database handle
61309 ** db. If a transaction is active, commit it. If there is a
61310 ** write-transaction spanning more than one database file, this routine
61311 ** takes care of the master journal trickery.
61312 */
61313 static int vdbeCommit(sqlcipher3 *db, Vdbe *p){
61314   int i;
61315   int nTrans = 0;  /* Number of databases with an active write-transaction */
61316   int rc = SQLCIPHER_OK;
61317   int needXcommit = 0;
61318
61319 #ifdef SQLCIPHER_OMIT_VIRTUALTABLE
61320   /* With this option, sqlcipher3VtabSync() is defined to be simply 
61321   ** SQLCIPHER_OK so p is not used. 
61322   */
61323   UNUSED_PARAMETER(p);
61324 #endif
61325
61326   /* Before doing anything else, call the xSync() callback for any
61327   ** virtual module tables written in this transaction. This has to
61328   ** be done before determining whether a master journal file is 
61329   ** required, as an xSync() callback may add an attached database
61330   ** to the transaction.
61331   */
61332   rc = sqlcipher3VtabSync(db, &p->zErrMsg);
61333
61334   /* This loop determines (a) if the commit hook should be invoked and
61335   ** (b) how many database files have open write transactions, not 
61336   ** including the temp database. (b) is important because if more than 
61337   ** one database file has an open write transaction, a master journal
61338   ** file is required for an atomic commit.
61339   */ 
61340   for(i=0; rc==SQLCIPHER_OK && i<db->nDb; i++){ 
61341     Btree *pBt = db->aDb[i].pBt;
61342     if( sqlcipher3BtreeIsInTrans(pBt) ){
61343       needXcommit = 1;
61344       if( i!=1 ) nTrans++;
61345       rc = sqlcipher3PagerExclusiveLock(sqlcipher3BtreePager(pBt));
61346     }
61347   }
61348   if( rc!=SQLCIPHER_OK ){
61349     return rc;
61350   }
61351
61352   /* If there are any write-transactions at all, invoke the commit hook */
61353   if( needXcommit && db->xCommitCallback ){
61354     rc = db->xCommitCallback(db->pCommitArg);
61355     if( rc ){
61356       return SQLCIPHER_CONSTRAINT;
61357     }
61358   }
61359
61360   /* The simple case - no more than one database file (not counting the
61361   ** TEMP database) has a transaction active.   There is no need for the
61362   ** master-journal.
61363   **
61364   ** If the return value of sqlcipher3BtreeGetFilename() is a zero length
61365   ** string, it means the main database is :memory: or a temp file.  In 
61366   ** that case we do not support atomic multi-file commits, so use the 
61367   ** simple case then too.
61368   */
61369   if( 0==sqlcipher3Strlen30(sqlcipher3BtreeGetFilename(db->aDb[0].pBt))
61370    || nTrans<=1
61371   ){
61372     for(i=0; rc==SQLCIPHER_OK && i<db->nDb; i++){
61373       Btree *pBt = db->aDb[i].pBt;
61374       if( pBt ){
61375         rc = sqlcipher3BtreeCommitPhaseOne(pBt, 0);
61376       }
61377     }
61378
61379     /* Do the commit only if all databases successfully complete phase 1. 
61380     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
61381     ** IO error while deleting or truncating a journal file. It is unlikely,
61382     ** but could happen. In this case abandon processing and return the error.
61383     */
61384     for(i=0; rc==SQLCIPHER_OK && i<db->nDb; i++){
61385       Btree *pBt = db->aDb[i].pBt;
61386       if( pBt ){
61387         rc = sqlcipher3BtreeCommitPhaseTwo(pBt, 0);
61388       }
61389     }
61390     if( rc==SQLCIPHER_OK ){
61391       sqlcipher3VtabCommit(db);
61392     }
61393   }
61394
61395   /* The complex case - There is a multi-file write-transaction active.
61396   ** This requires a master journal file to ensure the transaction is
61397   ** committed atomicly.
61398   */
61399 #ifndef SQLCIPHER_OMIT_DISKIO
61400   else{
61401     sqlcipher3_vfs *pVfs = db->pVfs;
61402     int needSync = 0;
61403     char *zMaster = 0;   /* File-name for the master journal */
61404     char const *zMainFile = sqlcipher3BtreeGetFilename(db->aDb[0].pBt);
61405     sqlcipher3_file *pMaster = 0;
61406     i64 offset = 0;
61407     int res;
61408
61409     /* Select a master journal file name */
61410     do {
61411       u32 iRandom;
61412       sqlcipher3DbFree(db, zMaster);
61413       sqlcipher3_randomness(sizeof(iRandom), &iRandom);
61414       zMaster = sqlcipher3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
61415       if( !zMaster ){
61416         return SQLCIPHER_NOMEM;
61417       }
61418       sqlcipher3FileSuffix3(zMainFile, zMaster);
61419       rc = sqlcipher3OsAccess(pVfs, zMaster, SQLCIPHER_ACCESS_EXISTS, &res);
61420     }while( rc==SQLCIPHER_OK && res );
61421     if( rc==SQLCIPHER_OK ){
61422       /* Open the master journal. */
61423       rc = sqlcipher3OsOpenMalloc(pVfs, zMaster, &pMaster, 
61424           SQLCIPHER_OPEN_READWRITE|SQLCIPHER_OPEN_CREATE|
61425           SQLCIPHER_OPEN_EXCLUSIVE|SQLCIPHER_OPEN_MASTER_JOURNAL, 0
61426       );
61427     }
61428     if( rc!=SQLCIPHER_OK ){
61429       sqlcipher3DbFree(db, zMaster);
61430       return rc;
61431     }
61432  
61433     /* Write the name of each database file in the transaction into the new
61434     ** master journal file. If an error occurs at this point close
61435     ** and delete the master journal file. All the individual journal files
61436     ** still have 'null' as the master journal pointer, so they will roll
61437     ** back independently if a failure occurs.
61438     */
61439     for(i=0; i<db->nDb; i++){
61440       Btree *pBt = db->aDb[i].pBt;
61441       if( sqlcipher3BtreeIsInTrans(pBt) ){
61442         char const *zFile = sqlcipher3BtreeGetJournalname(pBt);
61443         if( zFile==0 ){
61444           continue;  /* Ignore TEMP and :memory: databases */
61445         }
61446         assert( zFile[0]!=0 );
61447         if( !needSync && !sqlcipher3BtreeSyncDisabled(pBt) ){
61448           needSync = 1;
61449         }
61450         rc = sqlcipher3OsWrite(pMaster, zFile, sqlcipher3Strlen30(zFile)+1, offset);
61451         offset += sqlcipher3Strlen30(zFile)+1;
61452         if( rc!=SQLCIPHER_OK ){
61453           sqlcipher3OsCloseFree(pMaster);
61454           sqlcipher3OsDelete(pVfs, zMaster, 0);
61455           sqlcipher3DbFree(db, zMaster);
61456           return rc;
61457         }
61458       }
61459     }
61460
61461     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
61462     ** flag is set this is not required.
61463     */
61464     if( needSync 
61465      && 0==(sqlcipher3OsDeviceCharacteristics(pMaster)&SQLCIPHER_IOCAP_SEQUENTIAL)
61466      && SQLCIPHER_OK!=(rc = sqlcipher3OsSync(pMaster, SQLCIPHER_SYNC_NORMAL))
61467     ){
61468       sqlcipher3OsCloseFree(pMaster);
61469       sqlcipher3OsDelete(pVfs, zMaster, 0);
61470       sqlcipher3DbFree(db, zMaster);
61471       return rc;
61472     }
61473
61474     /* Sync all the db files involved in the transaction. The same call
61475     ** sets the master journal pointer in each individual journal. If
61476     ** an error occurs here, do not delete the master journal file.
61477     **
61478     ** If the error occurs during the first call to
61479     ** sqlcipher3BtreeCommitPhaseOne(), then there is a chance that the
61480     ** master journal file will be orphaned. But we cannot delete it,
61481     ** in case the master journal file name was written into the journal
61482     ** file before the failure occurred.
61483     */
61484     for(i=0; rc==SQLCIPHER_OK && i<db->nDb; i++){ 
61485       Btree *pBt = db->aDb[i].pBt;
61486       if( pBt ){
61487         rc = sqlcipher3BtreeCommitPhaseOne(pBt, zMaster);
61488       }
61489     }
61490     sqlcipher3OsCloseFree(pMaster);
61491     assert( rc!=SQLCIPHER_BUSY );
61492     if( rc!=SQLCIPHER_OK ){
61493       sqlcipher3DbFree(db, zMaster);
61494       return rc;
61495     }
61496
61497     /* Delete the master journal file. This commits the transaction. After
61498     ** doing this the directory is synced again before any individual
61499     ** transaction files are deleted.
61500     */
61501     rc = sqlcipher3OsDelete(pVfs, zMaster, 1);
61502     sqlcipher3DbFree(db, zMaster);
61503     zMaster = 0;
61504     if( rc ){
61505       return rc;
61506     }
61507
61508     /* All files and directories have already been synced, so the following
61509     ** calls to sqlcipher3BtreeCommitPhaseTwo() are only closing files and
61510     ** deleting or truncating journals. If something goes wrong while
61511     ** this is happening we don't really care. The integrity of the
61512     ** transaction is already guaranteed, but some stray 'cold' journals
61513     ** may be lying around. Returning an error code won't help matters.
61514     */
61515     disable_simulated_io_errors();
61516     sqlcipher3BeginBenignMalloc();
61517     for(i=0; i<db->nDb; i++){ 
61518       Btree *pBt = db->aDb[i].pBt;
61519       if( pBt ){
61520         sqlcipher3BtreeCommitPhaseTwo(pBt, 1);
61521       }
61522     }
61523     sqlcipher3EndBenignMalloc();
61524     enable_simulated_io_errors();
61525
61526     sqlcipher3VtabCommit(db);
61527   }
61528 #endif
61529
61530   return rc;
61531 }
61532
61533 /* 
61534 ** This routine checks that the sqlcipher3.activeVdbeCnt count variable
61535 ** matches the number of vdbe's in the list sqlcipher3.pVdbe that are
61536 ** currently active. An assertion fails if the two counts do not match.
61537 ** This is an internal self-check only - it is not an essential processing
61538 ** step.
61539 **
61540 ** This is a no-op if NDEBUG is defined.
61541 */
61542 #ifndef NDEBUG
61543 static void checkActiveVdbeCnt(sqlcipher3 *db){
61544   Vdbe *p;
61545   int cnt = 0;
61546   int nWrite = 0;
61547   p = db->pVdbe;
61548   while( p ){
61549     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
61550       cnt++;
61551       if( p->readOnly==0 ) nWrite++;
61552     }
61553     p = p->pNext;
61554   }
61555   assert( cnt==db->activeVdbeCnt );
61556   assert( nWrite==db->writeVdbeCnt );
61557 }
61558 #else
61559 #define checkActiveVdbeCnt(x)
61560 #endif
61561
61562 /*
61563 ** For every Btree that in database connection db which 
61564 ** has been modified, "trip" or invalidate each cursor in
61565 ** that Btree might have been modified so that the cursor
61566 ** can never be used again.  This happens when a rollback
61567 *** occurs.  We have to trip all the other cursors, even
61568 ** cursor from other VMs in different database connections,
61569 ** so that none of them try to use the data at which they
61570 ** were pointing and which now may have been changed due
61571 ** to the rollback.
61572 **
61573 ** Remember that a rollback can delete tables complete and
61574 ** reorder rootpages.  So it is not sufficient just to save
61575 ** the state of the cursor.  We have to invalidate the cursor
61576 ** so that it is never used again.
61577 */
61578 static void invalidateCursorsOnModifiedBtrees(sqlcipher3 *db){
61579   int i;
61580   for(i=0; i<db->nDb; i++){
61581     Btree *p = db->aDb[i].pBt;
61582     if( p && sqlcipher3BtreeIsInTrans(p) ){
61583       sqlcipher3BtreeTripAllCursors(p, SQLCIPHER_ABORT);
61584     }
61585   }
61586 }
61587
61588 /*
61589 ** If the Vdbe passed as the first argument opened a statement-transaction,
61590 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
61591 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
61592 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
61593 ** statement transaction is commtted.
61594 **
61595 ** If an IO error occurs, an SQLCIPHER_IOERR_XXX error code is returned. 
61596 ** Otherwise SQLCIPHER_OK.
61597 */
61598 SQLCIPHER_PRIVATE int sqlcipher3VdbeCloseStatement(Vdbe *p, int eOp){
61599   sqlcipher3 *const db = p->db;
61600   int rc = SQLCIPHER_OK;
61601
61602   /* If p->iStatement is greater than zero, then this Vdbe opened a 
61603   ** statement transaction that should be closed here. The only exception
61604   ** is that an IO error may have occured, causing an emergency rollback.
61605   ** In this case (db->nStatement==0), and there is nothing to do.
61606   */
61607   if( db->nStatement && p->iStatement ){
61608     int i;
61609     const int iSavepoint = p->iStatement-1;
61610
61611     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
61612     assert( db->nStatement>0 );
61613     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
61614
61615     for(i=0; i<db->nDb; i++){ 
61616       int rc2 = SQLCIPHER_OK;
61617       Btree *pBt = db->aDb[i].pBt;
61618       if( pBt ){
61619         if( eOp==SAVEPOINT_ROLLBACK ){
61620           rc2 = sqlcipher3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
61621         }
61622         if( rc2==SQLCIPHER_OK ){
61623           rc2 = sqlcipher3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
61624         }
61625         if( rc==SQLCIPHER_OK ){
61626           rc = rc2;
61627         }
61628       }
61629     }
61630     db->nStatement--;
61631     p->iStatement = 0;
61632
61633     if( rc==SQLCIPHER_OK ){
61634       if( eOp==SAVEPOINT_ROLLBACK ){
61635         rc = sqlcipher3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
61636       }
61637       if( rc==SQLCIPHER_OK ){
61638         rc = sqlcipher3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
61639       }
61640     }
61641
61642     /* If the statement transaction is being rolled back, also restore the 
61643     ** database handles deferred constraint counter to the value it had when 
61644     ** the statement transaction was opened.  */
61645     if( eOp==SAVEPOINT_ROLLBACK ){
61646       db->nDeferredCons = p->nStmtDefCons;
61647     }
61648   }
61649   return rc;
61650 }
61651
61652 /*
61653 ** This function is called when a transaction opened by the database 
61654 ** handle associated with the VM passed as an argument is about to be 
61655 ** committed. If there are outstanding deferred foreign key constraint
61656 ** violations, return SQLCIPHER_ERROR. Otherwise, SQLCIPHER_OK.
61657 **
61658 ** If there are outstanding FK violations and this function returns 
61659 ** SQLCIPHER_ERROR, set the result of the VM to SQLCIPHER_CONSTRAINT and write
61660 ** an error message to it. Then return SQLCIPHER_ERROR.
61661 */
61662 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
61663 SQLCIPHER_PRIVATE int sqlcipher3VdbeCheckFk(Vdbe *p, int deferred){
61664   sqlcipher3 *db = p->db;
61665   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
61666     p->rc = SQLCIPHER_CONSTRAINT;
61667     p->errorAction = OE_Abort;
61668     sqlcipher3SetString(&p->zErrMsg, db, "foreign key constraint failed");
61669     return SQLCIPHER_ERROR;
61670   }
61671   return SQLCIPHER_OK;
61672 }
61673 #endif
61674
61675 /*
61676 ** This routine is called the when a VDBE tries to halt.  If the VDBE
61677 ** has made changes and is in autocommit mode, then commit those
61678 ** changes.  If a rollback is needed, then do the rollback.
61679 **
61680 ** This routine is the only way to move the state of a VM from
61681 ** SQLCIPHER_MAGIC_RUN to SQLCIPHER_MAGIC_HALT.  It is harmless to
61682 ** call this on a VM that is in the SQLCIPHER_MAGIC_HALT state.
61683 **
61684 ** Return an error code.  If the commit could not complete because of
61685 ** lock contention, return SQLCIPHER_BUSY.  If SQLCIPHER_BUSY is returned, it
61686 ** means the close did not happen and needs to be repeated.
61687 */
61688 SQLCIPHER_PRIVATE int sqlcipher3VdbeHalt(Vdbe *p){
61689   int rc;                         /* Used to store transient return codes */
61690   sqlcipher3 *db = p->db;
61691
61692   /* This function contains the logic that determines if a statement or
61693   ** transaction will be committed or rolled back as a result of the
61694   ** execution of this virtual machine. 
61695   **
61696   ** If any of the following errors occur:
61697   **
61698   **     SQLCIPHER_NOMEM
61699   **     SQLCIPHER_IOERR
61700   **     SQLCIPHER_FULL
61701   **     SQLCIPHER_INTERRUPT
61702   **
61703   ** Then the internal cache might have been left in an inconsistent
61704   ** state.  We need to rollback the statement transaction, if there is
61705   ** one, or the complete transaction if there is no statement transaction.
61706   */
61707
61708   if( p->db->mallocFailed ){
61709     p->rc = SQLCIPHER_NOMEM;
61710   }
61711   closeAllCursors(p);
61712   if( p->magic!=VDBE_MAGIC_RUN ){
61713     return SQLCIPHER_OK;
61714   }
61715   checkActiveVdbeCnt(db);
61716
61717   /* No commit or rollback needed if the program never started */
61718   if( p->pc>=0 ){
61719     int mrc;   /* Primary error code from p->rc */
61720     int eStatementOp = 0;
61721     int isSpecialError;            /* Set to true if a 'special' error */
61722
61723     /* Lock all btrees used by the statement */
61724     sqlcipher3VdbeEnter(p);
61725
61726     /* Check for one of the special errors */
61727     mrc = p->rc & 0xff;
61728     assert( p->rc!=SQLCIPHER_IOERR_BLOCKED );  /* This error no longer exists */
61729     isSpecialError = mrc==SQLCIPHER_NOMEM || mrc==SQLCIPHER_IOERR
61730                      || mrc==SQLCIPHER_INTERRUPT || mrc==SQLCIPHER_FULL;
61731     if( isSpecialError ){
61732       /* If the query was read-only and the error code is SQLCIPHER_INTERRUPT, 
61733       ** no rollback is necessary. Otherwise, at least a savepoint 
61734       ** transaction must be rolled back to restore the database to a 
61735       ** consistent state.
61736       **
61737       ** Even if the statement is read-only, it is important to perform
61738       ** a statement or transaction rollback operation. If the error 
61739       ** occured while writing to the journal, sub-journal or database
61740       ** file as part of an effort to free up cache space (see function
61741       ** pagerStress() in pager.c), the rollback is required to restore 
61742       ** the pager to a consistent state.
61743       */
61744       if( !p->readOnly || mrc!=SQLCIPHER_INTERRUPT ){
61745         if( (mrc==SQLCIPHER_NOMEM || mrc==SQLCIPHER_FULL) && p->usesStmtJournal ){
61746           eStatementOp = SAVEPOINT_ROLLBACK;
61747         }else{
61748           /* We are forced to roll back the active transaction. Before doing
61749           ** so, abort any other statements this handle currently has active.
61750           */
61751           invalidateCursorsOnModifiedBtrees(db);
61752           sqlcipher3RollbackAll(db);
61753           sqlcipher3CloseSavepoints(db);
61754           db->autoCommit = 1;
61755         }
61756       }
61757     }
61758
61759     /* Check for immediate foreign key violations. */
61760     if( p->rc==SQLCIPHER_OK ){
61761       sqlcipher3VdbeCheckFk(p, 0);
61762     }
61763   
61764     /* If the auto-commit flag is set and this is the only active writer 
61765     ** VM, then we do either a commit or rollback of the current transaction. 
61766     **
61767     ** Note: This block also runs if one of the special errors handled 
61768     ** above has occurred. 
61769     */
61770     if( !sqlcipher3VtabInSync(db) 
61771      && db->autoCommit 
61772      && db->writeVdbeCnt==(p->readOnly==0) 
61773     ){
61774       if( p->rc==SQLCIPHER_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
61775         rc = sqlcipher3VdbeCheckFk(p, 1);
61776         if( rc!=SQLCIPHER_OK ){
61777           if( NEVER(p->readOnly) ){
61778             sqlcipher3VdbeLeave(p);
61779             return SQLCIPHER_ERROR;
61780           }
61781           rc = SQLCIPHER_CONSTRAINT;
61782         }else{ 
61783           /* The auto-commit flag is true, the vdbe program was successful 
61784           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
61785           ** key constraints to hold up the transaction. This means a commit 
61786           ** is required. */
61787           rc = vdbeCommit(db, p);
61788         }
61789         if( rc==SQLCIPHER_BUSY && p->readOnly ){
61790           sqlcipher3VdbeLeave(p);
61791           return SQLCIPHER_BUSY;
61792         }else if( rc!=SQLCIPHER_OK ){
61793           p->rc = rc;
61794           sqlcipher3RollbackAll(db);
61795         }else{
61796           db->nDeferredCons = 0;
61797           sqlcipher3CommitInternalChanges(db);
61798         }
61799       }else{
61800         sqlcipher3RollbackAll(db);
61801       }
61802       db->nStatement = 0;
61803     }else if( eStatementOp==0 ){
61804       if( p->rc==SQLCIPHER_OK || p->errorAction==OE_Fail ){
61805         eStatementOp = SAVEPOINT_RELEASE;
61806       }else if( p->errorAction==OE_Abort ){
61807         eStatementOp = SAVEPOINT_ROLLBACK;
61808       }else{
61809         invalidateCursorsOnModifiedBtrees(db);
61810         sqlcipher3RollbackAll(db);
61811         sqlcipher3CloseSavepoints(db);
61812         db->autoCommit = 1;
61813       }
61814     }
61815   
61816     /* If eStatementOp is non-zero, then a statement transaction needs to
61817     ** be committed or rolled back. Call sqlcipher3VdbeCloseStatement() to
61818     ** do so. If this operation returns an error, and the current statement
61819     ** error code is SQLCIPHER_OK or SQLCIPHER_CONSTRAINT, then promote the
61820     ** current statement error code.
61821     */
61822     if( eStatementOp ){
61823       rc = sqlcipher3VdbeCloseStatement(p, eStatementOp);
61824       if( rc ){
61825         if( p->rc==SQLCIPHER_OK || p->rc==SQLCIPHER_CONSTRAINT ){
61826           p->rc = rc;
61827           sqlcipher3DbFree(db, p->zErrMsg);
61828           p->zErrMsg = 0;
61829         }
61830         invalidateCursorsOnModifiedBtrees(db);
61831         sqlcipher3RollbackAll(db);
61832         sqlcipher3CloseSavepoints(db);
61833         db->autoCommit = 1;
61834       }
61835     }
61836   
61837     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
61838     ** has been rolled back, update the database connection change-counter. 
61839     */
61840     if( p->changeCntOn ){
61841       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
61842         sqlcipher3VdbeSetChanges(db, p->nChange);
61843       }else{
61844         sqlcipher3VdbeSetChanges(db, 0);
61845       }
61846       p->nChange = 0;
61847     }
61848   
61849     /* Rollback or commit any schema changes that occurred. */
61850     if( p->rc!=SQLCIPHER_OK && db->flags&SQLCIPHER_InternChanges ){
61851       sqlcipher3ResetInternalSchema(db, -1);
61852       db->flags = (db->flags | SQLCIPHER_InternChanges);
61853     }
61854
61855     /* Release the locks */
61856     sqlcipher3VdbeLeave(p);
61857   }
61858
61859   /* We have successfully halted and closed the VM.  Record this fact. */
61860   if( p->pc>=0 ){
61861     db->activeVdbeCnt--;
61862     if( !p->readOnly ){
61863       db->writeVdbeCnt--;
61864     }
61865     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
61866   }
61867   p->magic = VDBE_MAGIC_HALT;
61868   checkActiveVdbeCnt(db);
61869   if( p->db->mallocFailed ){
61870     p->rc = SQLCIPHER_NOMEM;
61871   }
61872
61873   /* If the auto-commit flag is set to true, then any locks that were held
61874   ** by connection db have now been released. Call sqlcipher3ConnectionUnlocked() 
61875   ** to invoke any required unlock-notify callbacks.
61876   */
61877   if( db->autoCommit ){
61878     sqlcipher3ConnectionUnlocked(db);
61879   }
61880
61881   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
61882   return (p->rc==SQLCIPHER_BUSY ? SQLCIPHER_BUSY : SQLCIPHER_OK);
61883 }
61884
61885
61886 /*
61887 ** Each VDBE holds the result of the most recent sqlcipher3_step() call
61888 ** in p->rc.  This routine sets that result back to SQLCIPHER_OK.
61889 */
61890 SQLCIPHER_PRIVATE void sqlcipher3VdbeResetStepResult(Vdbe *p){
61891   p->rc = SQLCIPHER_OK;
61892 }
61893
61894 /*
61895 ** Copy the error code and error message belonging to the VDBE passed
61896 ** as the first argument to its database handle (so that they will be 
61897 ** returned by calls to sqlcipher3_errcode() and sqlcipher3_errmsg()).
61898 **
61899 ** This function does not clear the VDBE error code or message, just
61900 ** copies them to the database handle.
61901 */
61902 SQLCIPHER_PRIVATE int sqlcipher3VdbeTransferError(Vdbe *p){
61903   sqlcipher3 *db = p->db;
61904   int rc = p->rc;
61905   if( p->zErrMsg ){
61906     u8 mallocFailed = db->mallocFailed;
61907     sqlcipher3BeginBenignMalloc();
61908     sqlcipher3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLCIPHER_UTF8, SQLCIPHER_TRANSIENT);
61909     sqlcipher3EndBenignMalloc();
61910     db->mallocFailed = mallocFailed;
61911     db->errCode = rc;
61912   }else{
61913     sqlcipher3Error(db, rc, 0);
61914   }
61915   return rc;
61916 }
61917
61918 /*
61919 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
61920 ** Write any error messages into *pzErrMsg.  Return the result code.
61921 **
61922 ** After this routine is run, the VDBE should be ready to be executed
61923 ** again.
61924 **
61925 ** To look at it another way, this routine resets the state of the
61926 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
61927 ** VDBE_MAGIC_INIT.
61928 */
61929 SQLCIPHER_PRIVATE int sqlcipher3VdbeReset(Vdbe *p){
61930   sqlcipher3 *db;
61931   db = p->db;
61932
61933   /* If the VM did not run to completion or if it encountered an
61934   ** error, then it might not have been halted properly.  So halt
61935   ** it now.
61936   */
61937   sqlcipher3VdbeHalt(p);
61938
61939   /* If the VDBE has be run even partially, then transfer the error code
61940   ** and error message from the VDBE into the main database structure.  But
61941   ** if the VDBE has just been set to run but has not actually executed any
61942   ** instructions yet, leave the main database error information unchanged.
61943   */
61944   if( p->pc>=0 ){
61945     sqlcipher3VdbeTransferError(p);
61946     sqlcipher3DbFree(db, p->zErrMsg);
61947     p->zErrMsg = 0;
61948     if( p->runOnlyOnce ) p->expired = 1;
61949   }else if( p->rc && p->expired ){
61950     /* The expired flag was set on the VDBE before the first call
61951     ** to sqlcipher3_step(). For consistency (since sqlcipher3_step() was
61952     ** called), set the database error in this case as well.
61953     */
61954     sqlcipher3Error(db, p->rc, 0);
61955     sqlcipher3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLCIPHER_UTF8, SQLCIPHER_TRANSIENT);
61956     sqlcipher3DbFree(db, p->zErrMsg);
61957     p->zErrMsg = 0;
61958   }
61959
61960   /* Reclaim all memory used by the VDBE
61961   */
61962   Cleanup(p);
61963
61964   /* Save profiling information from this VDBE run.
61965   */
61966 #ifdef VDBE_PROFILE
61967   {
61968     FILE *out = fopen("vdbe_profile.out", "a");
61969     if( out ){
61970       int i;
61971       fprintf(out, "---- ");
61972       for(i=0; i<p->nOp; i++){
61973         fprintf(out, "%02x", p->aOp[i].opcode);
61974       }
61975       fprintf(out, "\n");
61976       for(i=0; i<p->nOp; i++){
61977         fprintf(out, "%6d %10lld %8lld ",
61978            p->aOp[i].cnt,
61979            p->aOp[i].cycles,
61980            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
61981         );
61982         sqlcipher3VdbePrintOp(out, i, &p->aOp[i]);
61983       }
61984       fclose(out);
61985     }
61986   }
61987 #endif
61988   p->magic = VDBE_MAGIC_INIT;
61989   return p->rc & db->errMask;
61990 }
61991  
61992 /*
61993 ** Clean up and delete a VDBE after execution.  Return an integer which is
61994 ** the result code.  Write any error message text into *pzErrMsg.
61995 */
61996 SQLCIPHER_PRIVATE int sqlcipher3VdbeFinalize(Vdbe *p){
61997   int rc = SQLCIPHER_OK;
61998   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
61999     rc = sqlcipher3VdbeReset(p);
62000     assert( (rc & p->db->errMask)==rc );
62001   }
62002   sqlcipher3VdbeDelete(p);
62003   return rc;
62004 }
62005
62006 /*
62007 ** Call the destructor for each auxdata entry in pVdbeFunc for which
62008 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
62009 ** are always destroyed.  To destroy all auxdata entries, call this
62010 ** routine with mask==0.
62011 */
62012 SQLCIPHER_PRIVATE void sqlcipher3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
62013   int i;
62014   for(i=0; i<pVdbeFunc->nAux; i++){
62015     struct AuxData *pAux = &pVdbeFunc->apAux[i];
62016     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
62017       if( pAux->xDelete ){
62018         pAux->xDelete(pAux->pAux);
62019       }
62020       pAux->pAux = 0;
62021     }
62022   }
62023 }
62024
62025 /*
62026 ** Free all memory associated with the Vdbe passed as the second argument.
62027 ** The difference between this function and sqlcipher3VdbeDelete() is that
62028 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
62029 ** the database connection.
62030 */
62031 SQLCIPHER_PRIVATE void sqlcipher3VdbeDeleteObject(sqlcipher3 *db, Vdbe *p){
62032   SubProgram *pSub, *pNext;
62033   int i;
62034   assert( p->db==0 || p->db==db );
62035   releaseMemArray(p->aVar, p->nVar);
62036   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
62037   for(pSub=p->pProgram; pSub; pSub=pNext){
62038     pNext = pSub->pNext;
62039     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
62040     sqlcipher3DbFree(db, pSub);
62041   }
62042   for(i=p->nzVar-1; i>=0; i--) sqlcipher3DbFree(db, p->azVar[i]);
62043   vdbeFreeOpArray(db, p->aOp, p->nOp);
62044   sqlcipher3DbFree(db, p->aLabel);
62045   sqlcipher3DbFree(db, p->aColName);
62046   sqlcipher3DbFree(db, p->zSql);
62047   sqlcipher3DbFree(db, p->pFree);
62048   sqlcipher3DbFree(db, p);
62049 }
62050
62051 /*
62052 ** Delete an entire VDBE.
62053 */
62054 SQLCIPHER_PRIVATE void sqlcipher3VdbeDelete(Vdbe *p){
62055   sqlcipher3 *db;
62056
62057   if( NEVER(p==0) ) return;
62058   db = p->db;
62059   if( p->pPrev ){
62060     p->pPrev->pNext = p->pNext;
62061   }else{
62062     assert( db->pVdbe==p );
62063     db->pVdbe = p->pNext;
62064   }
62065   if( p->pNext ){
62066     p->pNext->pPrev = p->pPrev;
62067   }
62068   p->magic = VDBE_MAGIC_DEAD;
62069   p->db = 0;
62070   sqlcipher3VdbeDeleteObject(db, p);
62071 }
62072
62073 /*
62074 ** Make sure the cursor p is ready to read or write the row to which it
62075 ** was last positioned.  Return an error code if an OOM fault or I/O error
62076 ** prevents us from positioning the cursor to its correct position.
62077 **
62078 ** If a MoveTo operation is pending on the given cursor, then do that
62079 ** MoveTo now.  If no move is pending, check to see if the row has been
62080 ** deleted out from under the cursor and if it has, mark the row as
62081 ** a NULL row.
62082 **
62083 ** If the cursor is already pointing to the correct row and that row has
62084 ** not been deleted out from under the cursor, then this routine is a no-op.
62085 */
62086 SQLCIPHER_PRIVATE int sqlcipher3VdbeCursorMoveto(VdbeCursor *p){
62087   if( p->deferredMoveto ){
62088     int res, rc;
62089 #ifdef SQLCIPHER_TEST
62090     extern int sqlcipher3_search_count;
62091 #endif
62092     assert( p->isTable );
62093     rc = sqlcipher3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
62094     if( rc ) return rc;
62095     p->lastRowid = p->movetoTarget;
62096     if( res!=0 ) return SQLCIPHER_CORRUPT_BKPT;
62097     p->rowidIsValid = 1;
62098 #ifdef SQLCIPHER_TEST
62099     sqlcipher3_search_count++;
62100 #endif
62101     p->deferredMoveto = 0;
62102     p->cacheStatus = CACHE_STALE;
62103   }else if( ALWAYS(p->pCursor) ){
62104     int hasMoved;
62105     int rc = sqlcipher3BtreeCursorHasMoved(p->pCursor, &hasMoved);
62106     if( rc ) return rc;
62107     if( hasMoved ){
62108       p->cacheStatus = CACHE_STALE;
62109       p->nullRow = 1;
62110     }
62111   }
62112   return SQLCIPHER_OK;
62113 }
62114
62115 /*
62116 ** The following functions:
62117 **
62118 ** sqlcipher3VdbeSerialType()
62119 ** sqlcipher3VdbeSerialTypeLen()
62120 ** sqlcipher3VdbeSerialLen()
62121 ** sqlcipher3VdbeSerialPut()
62122 ** sqlcipher3VdbeSerialGet()
62123 **
62124 ** encapsulate the code that serializes values for storage in SQLite
62125 ** data and index records. Each serialized value consists of a
62126 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
62127 ** integer, stored as a varint.
62128 **
62129 ** In an SQLite index record, the serial type is stored directly before
62130 ** the blob of data that it corresponds to. In a table record, all serial
62131 ** types are stored at the start of the record, and the blobs of data at
62132 ** the end. Hence these functions allow the caller to handle the
62133 ** serial-type and data blob seperately.
62134 **
62135 ** The following table describes the various storage classes for data:
62136 **
62137 **   serial type        bytes of data      type
62138 **   --------------     ---------------    ---------------
62139 **      0                     0            NULL
62140 **      1                     1            signed integer
62141 **      2                     2            signed integer
62142 **      3                     3            signed integer
62143 **      4                     4            signed integer
62144 **      5                     6            signed integer
62145 **      6                     8            signed integer
62146 **      7                     8            IEEE float
62147 **      8                     0            Integer constant 0
62148 **      9                     0            Integer constant 1
62149 **     10,11                               reserved for expansion
62150 **    N>=12 and even       (N-12)/2        BLOB
62151 **    N>=13 and odd        (N-13)/2        text
62152 **
62153 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
62154 ** of SQLite will not understand those serial types.
62155 */
62156
62157 /*
62158 ** Return the serial-type for the value stored in pMem.
62159 */
62160 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialType(Mem *pMem, int file_format){
62161   int flags = pMem->flags;
62162   int n;
62163
62164   if( flags&MEM_Null ){
62165     return 0;
62166   }
62167   if( flags&MEM_Int ){
62168     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
62169 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
62170     i64 i = pMem->u.i;
62171     u64 u;
62172     if( file_format>=4 && (i&1)==i ){
62173       return 8+(u32)i;
62174     }
62175     if( i<0 ){
62176       if( i<(-MAX_6BYTE) ) return 6;
62177       /* Previous test prevents:  u = -(-9223372036854775808) */
62178       u = -i;
62179     }else{
62180       u = i;
62181     }
62182     if( u<=127 ) return 1;
62183     if( u<=32767 ) return 2;
62184     if( u<=8388607 ) return 3;
62185     if( u<=2147483647 ) return 4;
62186     if( u<=MAX_6BYTE ) return 5;
62187     return 6;
62188   }
62189   if( flags&MEM_Real ){
62190     return 7;
62191   }
62192   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
62193   n = pMem->n;
62194   if( flags & MEM_Zero ){
62195     n += pMem->u.nZero;
62196   }
62197   assert( n>=0 );
62198   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
62199 }
62200
62201 /*
62202 ** Return the length of the data corresponding to the supplied serial-type.
62203 */
62204 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialTypeLen(u32 serial_type){
62205   if( serial_type>=12 ){
62206     return (serial_type-12)/2;
62207   }else{
62208     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
62209     return aSize[serial_type];
62210   }
62211 }
62212
62213 /*
62214 ** If we are on an architecture with mixed-endian floating 
62215 ** points (ex: ARM7) then swap the lower 4 bytes with the 
62216 ** upper 4 bytes.  Return the result.
62217 **
62218 ** For most architectures, this is a no-op.
62219 **
62220 ** (later):  It is reported to me that the mixed-endian problem
62221 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
62222 ** that early versions of GCC stored the two words of a 64-bit
62223 ** float in the wrong order.  And that error has been propagated
62224 ** ever since.  The blame is not necessarily with GCC, though.
62225 ** GCC might have just copying the problem from a prior compiler.
62226 ** I am also told that newer versions of GCC that follow a different
62227 ** ABI get the byte order right.
62228 **
62229 ** Developers using SQLite on an ARM7 should compile and run their
62230 ** application using -DSQLCIPHER_DEBUG=1 at least once.  With DEBUG
62231 ** enabled, some asserts below will ensure that the byte order of
62232 ** floating point values is correct.
62233 **
62234 ** (2007-08-30)  Frank van Vugt has studied this problem closely
62235 ** and has send his findings to the SQLite developers.  Frank
62236 ** writes that some Linux kernels offer floating point hardware
62237 ** emulation that uses only 32-bit mantissas instead of a full 
62238 ** 48-bits as required by the IEEE standard.  (This is the
62239 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
62240 ** byte swapping becomes very complicated.  To avoid problems,
62241 ** the necessary byte swapping is carried out using a 64-bit integer
62242 ** rather than a 64-bit float.  Frank assures us that the code here
62243 ** works for him.  We, the developers, have no way to independently
62244 ** verify this, but Frank seems to know what he is talking about
62245 ** so we trust him.
62246 */
62247 #ifdef SQLCIPHER_MIXED_ENDIAN_64BIT_FLOAT
62248 static u64 floatSwap(u64 in){
62249   union {
62250     u64 r;
62251     u32 i[2];
62252   } u;
62253   u32 t;
62254
62255   u.r = in;
62256   t = u.i[0];
62257   u.i[0] = u.i[1];
62258   u.i[1] = t;
62259   return u.r;
62260 }
62261 # define swapMixedEndianFloat(X)  X = floatSwap(X)
62262 #else
62263 # define swapMixedEndianFloat(X)
62264 #endif
62265
62266 /*
62267 ** Write the serialized data blob for the value stored in pMem into 
62268 ** buf. It is assumed that the caller has allocated sufficient space.
62269 ** Return the number of bytes written.
62270 **
62271 ** nBuf is the amount of space left in buf[].  nBuf must always be
62272 ** large enough to hold the entire field.  Except, if the field is
62273 ** a blob with a zero-filled tail, then buf[] might be just the right
62274 ** size to hold everything except for the zero-filled tail.  If buf[]
62275 ** is only big enough to hold the non-zero prefix, then only write that
62276 ** prefix into buf[].  But if buf[] is large enough to hold both the
62277 ** prefix and the tail then write the prefix and set the tail to all
62278 ** zeros.
62279 **
62280 ** Return the number of bytes actually written into buf[].  The number
62281 ** of bytes in the zero-filled tail is included in the return value only
62282 ** if those bytes were zeroed in buf[].
62283 */ 
62284 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
62285   u32 serial_type = sqlcipher3VdbeSerialType(pMem, file_format);
62286   u32 len;
62287
62288   /* Integer and Real */
62289   if( serial_type<=7 && serial_type>0 ){
62290     u64 v;
62291     u32 i;
62292     if( serial_type==7 ){
62293       assert( sizeof(v)==sizeof(pMem->r) );
62294       memcpy(&v, &pMem->r, sizeof(v));
62295       swapMixedEndianFloat(v);
62296     }else{
62297       v = pMem->u.i;
62298     }
62299     len = i = sqlcipher3VdbeSerialTypeLen(serial_type);
62300     assert( len<=(u32)nBuf );
62301     while( i-- ){
62302       buf[i] = (u8)(v&0xFF);
62303       v >>= 8;
62304     }
62305     return len;
62306   }
62307
62308   /* String or blob */
62309   if( serial_type>=12 ){
62310     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
62311              == (int)sqlcipher3VdbeSerialTypeLen(serial_type) );
62312     assert( pMem->n<=nBuf );
62313     len = pMem->n;
62314     memcpy(buf, pMem->z, len);
62315     if( pMem->flags & MEM_Zero ){
62316       len += pMem->u.nZero;
62317       assert( nBuf>=0 );
62318       if( len > (u32)nBuf ){
62319         len = (u32)nBuf;
62320       }
62321       memset(&buf[pMem->n], 0, len-pMem->n);
62322     }
62323     return len;
62324   }
62325
62326   /* NULL or constants 0 or 1 */
62327   return 0;
62328 }
62329
62330 /*
62331 ** Deserialize the data blob pointed to by buf as serial type serial_type
62332 ** and store the result in pMem.  Return the number of bytes read.
62333 */ 
62334 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialGet(
62335   const unsigned char *buf,     /* Buffer to deserialize from */
62336   u32 serial_type,              /* Serial type to deserialize */
62337   Mem *pMem                     /* Memory cell to write value into */
62338 ){
62339   switch( serial_type ){
62340     case 10:   /* Reserved for future use */
62341     case 11:   /* Reserved for future use */
62342     case 0: {  /* NULL */
62343       pMem->flags = MEM_Null;
62344       break;
62345     }
62346     case 1: { /* 1-byte signed integer */
62347       pMem->u.i = (signed char)buf[0];
62348       pMem->flags = MEM_Int;
62349       return 1;
62350     }
62351     case 2: { /* 2-byte signed integer */
62352       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
62353       pMem->flags = MEM_Int;
62354       return 2;
62355     }
62356     case 3: { /* 3-byte signed integer */
62357       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
62358       pMem->flags = MEM_Int;
62359       return 3;
62360     }
62361     case 4: { /* 4-byte signed integer */
62362       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62363       pMem->flags = MEM_Int;
62364       return 4;
62365     }
62366     case 5: { /* 6-byte signed integer */
62367       u64 x = (((signed char)buf[0])<<8) | buf[1];
62368       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
62369       x = (x<<32) | y;
62370       pMem->u.i = *(i64*)&x;
62371       pMem->flags = MEM_Int;
62372       return 6;
62373     }
62374     case 6:   /* 8-byte signed integer */
62375     case 7: { /* IEEE floating point */
62376       u64 x;
62377       u32 y;
62378 #if !defined(NDEBUG) && !defined(SQLCIPHER_OMIT_FLOATING_POINT)
62379       /* Verify that integers and floating point values use the same
62380       ** byte order.  Or, that if SQLCIPHER_MIXED_ENDIAN_64BIT_FLOAT is
62381       ** defined that 64-bit floating point values really are mixed
62382       ** endian.
62383       */
62384       static const u64 t1 = ((u64)0x3ff00000)<<32;
62385       static const double r1 = 1.0;
62386       u64 t2 = t1;
62387       swapMixedEndianFloat(t2);
62388       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
62389 #endif
62390
62391       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62392       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
62393       x = (x<<32) | y;
62394       if( serial_type==6 ){
62395         pMem->u.i = *(i64*)&x;
62396         pMem->flags = MEM_Int;
62397       }else{
62398         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
62399         swapMixedEndianFloat(x);
62400         memcpy(&pMem->r, &x, sizeof(x));
62401         pMem->flags = sqlcipher3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
62402       }
62403       return 8;
62404     }
62405     case 8:    /* Integer 0 */
62406     case 9: {  /* Integer 1 */
62407       pMem->u.i = serial_type-8;
62408       pMem->flags = MEM_Int;
62409       return 0;
62410     }
62411     default: {
62412       u32 len = (serial_type-12)/2;
62413       pMem->z = (char *)buf;
62414       pMem->n = len;
62415       pMem->xDel = 0;
62416       if( serial_type&0x01 ){
62417         pMem->flags = MEM_Str | MEM_Ephem;
62418       }else{
62419         pMem->flags = MEM_Blob | MEM_Ephem;
62420       }
62421       return len;
62422     }
62423   }
62424   return 0;
62425 }
62426
62427 /*
62428 ** This routine is used to allocate sufficient space for an UnpackedRecord
62429 ** structure large enough to be used with sqlcipher3VdbeRecordUnpack() if
62430 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
62431 **
62432 ** The space is either allocated using sqlcipher3DbMallocRaw() or from within
62433 ** the unaligned buffer passed via the second and third arguments (presumably
62434 ** stack space). If the former, then *ppFree is set to a pointer that should
62435 ** be eventually freed by the caller using sqlcipher3DbFree(). Or, if the 
62436 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
62437 ** before returning.
62438 **
62439 ** If an OOM error occurs, NULL is returned.
62440 */
62441 SQLCIPHER_PRIVATE UnpackedRecord *sqlcipher3VdbeAllocUnpackedRecord(
62442   KeyInfo *pKeyInfo,              /* Description of the record */
62443   char *pSpace,                   /* Unaligned space available */
62444   int szSpace,                    /* Size of pSpace[] in bytes */
62445   char **ppFree                   /* OUT: Caller should free this pointer */
62446 ){
62447   UnpackedRecord *p;              /* Unpacked record to return */
62448   int nOff;                       /* Increment pSpace by nOff to align it */
62449   int nByte;                      /* Number of bytes required for *p */
62450
62451   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
62452   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
62453   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
62454   */
62455   nOff = (8 - (SQLCIPHER_PTR_TO_INT(pSpace) & 7)) & 7;
62456   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
62457   if( nByte>szSpace+nOff ){
62458     p = (UnpackedRecord *)sqlcipher3DbMallocRaw(pKeyInfo->db, nByte);
62459     *ppFree = (char *)p;
62460     if( !p ) return 0;
62461   }else{
62462     p = (UnpackedRecord*)&pSpace[nOff];
62463     *ppFree = 0;
62464   }
62465
62466   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
62467   p->pKeyInfo = pKeyInfo;
62468   p->nField = pKeyInfo->nField + 1;
62469   return p;
62470 }
62471
62472 /*
62473 ** Given the nKey-byte encoding of a record in pKey[], populate the 
62474 ** UnpackedRecord structure indicated by the fourth argument with the
62475 ** contents of the decoded record.
62476 */ 
62477 SQLCIPHER_PRIVATE void sqlcipher3VdbeRecordUnpack(
62478   KeyInfo *pKeyInfo,     /* Information about the record format */
62479   int nKey,              /* Size of the binary record */
62480   const void *pKey,      /* The binary record */
62481   UnpackedRecord *p      /* Populate this structure before returning. */
62482 ){
62483   const unsigned char *aKey = (const unsigned char *)pKey;
62484   int d; 
62485   u32 idx;                        /* Offset in aKey[] to read from */
62486   u16 u;                          /* Unsigned loop counter */
62487   u32 szHdr;
62488   Mem *pMem = p->aMem;
62489
62490   p->flags = 0;
62491   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62492   idx = getVarint32(aKey, szHdr);
62493   d = szHdr;
62494   u = 0;
62495   while( idx<szHdr && u<p->nField && d<=nKey ){
62496     u32 serial_type;
62497
62498     idx += getVarint32(&aKey[idx], serial_type);
62499     pMem->enc = pKeyInfo->enc;
62500     pMem->db = pKeyInfo->db;
62501     /* pMem->flags = 0; // sqlcipher3VdbeSerialGet() will set this for us */
62502     pMem->zMalloc = 0;
62503     d += sqlcipher3VdbeSerialGet(&aKey[d], serial_type, pMem);
62504     pMem++;
62505     u++;
62506   }
62507   assert( u<=pKeyInfo->nField + 1 );
62508   p->nField = u;
62509 }
62510
62511 /*
62512 ** This function compares the two table rows or index records
62513 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
62514 ** or positive integer if key1 is less than, equal to or 
62515 ** greater than key2.  The {nKey1, pKey1} key must be a blob
62516 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
62517 ** key must be a parsed key such as obtained from
62518 ** sqlcipher3VdbeParseRecord.
62519 **
62520 ** Key1 and Key2 do not have to contain the same number of fields.
62521 ** The key with fewer fields is usually compares less than the 
62522 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
62523 ** and the common prefixes are equal, then key1 is less than key2.
62524 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
62525 ** equal, then the keys are considered to be equal and
62526 ** the parts beyond the common prefix are ignored.
62527 **
62528 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
62529 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
62530 ** an index key, and thus ends with a rowid value.  The last byte
62531 ** of the header will therefore be the serial type of the rowid:
62532 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
62533 ** The serial type of the final rowid will always be a single byte.
62534 ** By ignoring this last byte of the header, we force the comparison
62535 ** to ignore the rowid at the end of key1.
62536 */
62537 SQLCIPHER_PRIVATE int sqlcipher3VdbeRecordCompare(
62538   int nKey1, const void *pKey1, /* Left key */
62539   UnpackedRecord *pPKey2        /* Right key */
62540 ){
62541   int d1;            /* Offset into aKey[] of next data element */
62542   u32 idx1;          /* Offset into aKey[] of next header element */
62543   u32 szHdr1;        /* Number of bytes in header */
62544   int i = 0;
62545   int nField;
62546   int rc = 0;
62547   const unsigned char *aKey1 = (const unsigned char *)pKey1;
62548   KeyInfo *pKeyInfo;
62549   Mem mem1;
62550
62551   pKeyInfo = pPKey2->pKeyInfo;
62552   mem1.enc = pKeyInfo->enc;
62553   mem1.db = pKeyInfo->db;
62554   /* mem1.flags = 0;  // Will be initialized by sqlcipher3VdbeSerialGet() */
62555   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
62556
62557   /* Compilers may complain that mem1.u.i is potentially uninitialized.
62558   ** We could initialize it, as shown here, to silence those complaints.
62559   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
62560   ** the unnecessary initialization has a measurable negative performance
62561   ** impact, since this routine is a very high runner.  And so, we choose
62562   ** to ignore the compiler warnings and leave this variable uninitialized.
62563   */
62564   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
62565   
62566   idx1 = getVarint32(aKey1, szHdr1);
62567   d1 = szHdr1;
62568   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
62569     szHdr1--;
62570   }
62571   nField = pKeyInfo->nField;
62572   while( idx1<szHdr1 && i<pPKey2->nField ){
62573     u32 serial_type1;
62574
62575     /* Read the serial types for the next element in each key. */
62576     idx1 += getVarint32( aKey1+idx1, serial_type1 );
62577     if( d1>=nKey1 && sqlcipher3VdbeSerialTypeLen(serial_type1)>0 ) break;
62578
62579     /* Extract the values to be compared.
62580     */
62581     d1 += sqlcipher3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
62582
62583     /* Do the comparison
62584     */
62585     rc = sqlcipher3MemCompare(&mem1, &pPKey2->aMem[i],
62586                            i<nField ? pKeyInfo->aColl[i] : 0);
62587     if( rc!=0 ){
62588       assert( mem1.zMalloc==0 );  /* See comment below */
62589
62590       /* Invert the result if we are using DESC sort order. */
62591       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
62592         rc = -rc;
62593       }
62594     
62595       /* If the PREFIX_SEARCH flag is set and all fields except the final
62596       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
62597       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
62598       ** This is used by the OP_IsUnique opcode.
62599       */
62600       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
62601         assert( idx1==szHdr1 && rc );
62602         assert( mem1.flags & MEM_Int );
62603         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
62604         pPKey2->rowid = mem1.u.i;
62605       }
62606     
62607       return rc;
62608     }
62609     i++;
62610   }
62611
62612   /* No memory allocation is ever used on mem1.  Prove this using
62613   ** the following assert().  If the assert() fails, it indicates a
62614   ** memory leak and a need to call sqlcipher3VdbeMemRelease(&mem1).
62615   */
62616   assert( mem1.zMalloc==0 );
62617
62618   /* rc==0 here means that one of the keys ran out of fields and
62619   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
62620   ** flag is set, then break the tie by treating key2 as larger.
62621   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
62622   ** are considered to be equal.  Otherwise, the longer key is the 
62623   ** larger.  As it happens, the pPKey2 will always be the longer
62624   ** if there is a difference.
62625   */
62626   assert( rc==0 );
62627   if( pPKey2->flags & UNPACKED_INCRKEY ){
62628     rc = -1;
62629   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
62630     /* Leave rc==0 */
62631   }else if( idx1<szHdr1 ){
62632     rc = 1;
62633   }
62634   return rc;
62635 }
62636  
62637
62638 /*
62639 ** pCur points at an index entry created using the OP_MakeRecord opcode.
62640 ** Read the rowid (the last field in the record) and store it in *rowid.
62641 ** Return SQLCIPHER_OK if everything works, or an error code otherwise.
62642 **
62643 ** pCur might be pointing to text obtained from a corrupt database file.
62644 ** So the content cannot be trusted.  Do appropriate checks on the content.
62645 */
62646 SQLCIPHER_PRIVATE int sqlcipher3VdbeIdxRowid(sqlcipher3 *db, BtCursor *pCur, i64 *rowid){
62647   i64 nCellKey = 0;
62648   int rc;
62649   u32 szHdr;        /* Size of the header */
62650   u32 typeRowid;    /* Serial type of the rowid */
62651   u32 lenRowid;     /* Size of the rowid */
62652   Mem m, v;
62653
62654   UNUSED_PARAMETER(db);
62655
62656   /* Get the size of the index entry.  Only indices entries of less
62657   ** than 2GiB are support - anything large must be database corruption.
62658   ** Any corruption is detected in sqlcipher3BtreeParseCellPtr(), though, so
62659   ** this code can safely assume that nCellKey is 32-bits  
62660   */
62661   assert( sqlcipher3BtreeCursorIsValid(pCur) );
62662   VVA_ONLY(rc =) sqlcipher3BtreeKeySize(pCur, &nCellKey);
62663   assert( rc==SQLCIPHER_OK );     /* pCur is always valid so KeySize cannot fail */
62664   assert( (nCellKey & SQLCIPHER_MAX_U32)==(u64)nCellKey );
62665
62666   /* Read in the complete content of the index entry */
62667   memset(&m, 0, sizeof(m));
62668   rc = sqlcipher3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
62669   if( rc ){
62670     return rc;
62671   }
62672
62673   /* The index entry must begin with a header size */
62674   (void)getVarint32((u8*)m.z, szHdr);
62675   testcase( szHdr==3 );
62676   testcase( szHdr==m.n );
62677   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
62678     goto idx_rowid_corruption;
62679   }
62680
62681   /* The last field of the index should be an integer - the ROWID.
62682   ** Verify that the last entry really is an integer. */
62683   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
62684   testcase( typeRowid==1 );
62685   testcase( typeRowid==2 );
62686   testcase( typeRowid==3 );
62687   testcase( typeRowid==4 );
62688   testcase( typeRowid==5 );
62689   testcase( typeRowid==6 );
62690   testcase( typeRowid==8 );
62691   testcase( typeRowid==9 );
62692   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
62693     goto idx_rowid_corruption;
62694   }
62695   lenRowid = sqlcipher3VdbeSerialTypeLen(typeRowid);
62696   testcase( (u32)m.n==szHdr+lenRowid );
62697   if( unlikely((u32)m.n<szHdr+lenRowid) ){
62698     goto idx_rowid_corruption;
62699   }
62700
62701   /* Fetch the integer off the end of the index record */
62702   sqlcipher3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
62703   *rowid = v.u.i;
62704   sqlcipher3VdbeMemRelease(&m);
62705   return SQLCIPHER_OK;
62706
62707   /* Jump here if database corruption is detected after m has been
62708   ** allocated.  Free the m object and return SQLCIPHER_CORRUPT. */
62709 idx_rowid_corruption:
62710   testcase( m.zMalloc!=0 );
62711   sqlcipher3VdbeMemRelease(&m);
62712   return SQLCIPHER_CORRUPT_BKPT;
62713 }
62714
62715 /*
62716 ** Compare the key of the index entry that cursor pC is pointing to against
62717 ** the key string in pUnpacked.  Write into *pRes a number
62718 ** that is negative, zero, or positive if pC is less than, equal to,
62719 ** or greater than pUnpacked.  Return SQLCIPHER_OK on success.
62720 **
62721 ** pUnpacked is either created without a rowid or is truncated so that it
62722 ** omits the rowid at the end.  The rowid at the end of the index entry
62723 ** is ignored as well.  Hence, this routine only compares the prefixes 
62724 ** of the keys prior to the final rowid, not the entire key.
62725 */
62726 SQLCIPHER_PRIVATE int sqlcipher3VdbeIdxKeyCompare(
62727   VdbeCursor *pC,             /* The cursor to compare against */
62728   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
62729   int *res                    /* Write the comparison result here */
62730 ){
62731   i64 nCellKey = 0;
62732   int rc;
62733   BtCursor *pCur = pC->pCursor;
62734   Mem m;
62735
62736   assert( sqlcipher3BtreeCursorIsValid(pCur) );
62737   VVA_ONLY(rc =) sqlcipher3BtreeKeySize(pCur, &nCellKey);
62738   assert( rc==SQLCIPHER_OK );    /* pCur is always valid so KeySize cannot fail */
62739   /* nCellKey will always be between 0 and 0xffffffff because of the say
62740   ** that btreeParseCellPtr() and sqlcipher3GetVarint32() are implemented */
62741   if( nCellKey<=0 || nCellKey>0x7fffffff ){
62742     *res = 0;
62743     return SQLCIPHER_CORRUPT_BKPT;
62744   }
62745   memset(&m, 0, sizeof(m));
62746   rc = sqlcipher3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
62747   if( rc ){
62748     return rc;
62749   }
62750   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
62751   *res = sqlcipher3VdbeRecordCompare(m.n, m.z, pUnpacked);
62752   sqlcipher3VdbeMemRelease(&m);
62753   return SQLCIPHER_OK;
62754 }
62755
62756 /*
62757 ** This routine sets the value to be returned by subsequent calls to
62758 ** sqlcipher3_changes() on the database handle 'db'. 
62759 */
62760 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetChanges(sqlcipher3 *db, int nChange){
62761   assert( sqlcipher3_mutex_held(db->mutex) );
62762   db->nChange = nChange;
62763   db->nTotalChange += nChange;
62764 }
62765
62766 /*
62767 ** Set a flag in the vdbe to update the change counter when it is finalised
62768 ** or reset.
62769 */
62770 SQLCIPHER_PRIVATE void sqlcipher3VdbeCountChanges(Vdbe *v){
62771   v->changeCntOn = 1;
62772 }
62773
62774 /*
62775 ** Mark every prepared statement associated with a database connection
62776 ** as expired.
62777 **
62778 ** An expired statement means that recompilation of the statement is
62779 ** recommend.  Statements expire when things happen that make their
62780 ** programs obsolete.  Removing user-defined functions or collating
62781 ** sequences, or changing an authorization function are the types of
62782 ** things that make prepared statements obsolete.
62783 */
62784 SQLCIPHER_PRIVATE void sqlcipher3ExpirePreparedStatements(sqlcipher3 *db){
62785   Vdbe *p;
62786   for(p = db->pVdbe; p; p=p->pNext){
62787     p->expired = 1;
62788   }
62789 }
62790
62791 /*
62792 ** Return the database associated with the Vdbe.
62793 */
62794 SQLCIPHER_PRIVATE sqlcipher3 *sqlcipher3VdbeDb(Vdbe *v){
62795   return v->db;
62796 }
62797
62798 /*
62799 ** Return a pointer to an sqlcipher3_value structure containing the value bound
62800 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
62801 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLCIPHER_AFF_*
62802 ** constants) to the value before returning it.
62803 **
62804 ** The returned value must be freed by the caller using sqlcipher3ValueFree().
62805 */
62806 SQLCIPHER_PRIVATE sqlcipher3_value *sqlcipher3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
62807   assert( iVar>0 );
62808   if( v ){
62809     Mem *pMem = &v->aVar[iVar-1];
62810     if( 0==(pMem->flags & MEM_Null) ){
62811       sqlcipher3_value *pRet = sqlcipher3ValueNew(v->db);
62812       if( pRet ){
62813         sqlcipher3VdbeMemCopy((Mem *)pRet, pMem);
62814         sqlcipher3ValueApplyAffinity(pRet, aff, SQLCIPHER_UTF8);
62815         sqlcipher3VdbeMemStoreType((Mem *)pRet);
62816       }
62817       return pRet;
62818     }
62819   }
62820   return 0;
62821 }
62822
62823 /*
62824 ** Configure SQL variable iVar so that binding a new value to it signals
62825 ** to sqlcipher3_reoptimize() that re-preparing the statement may result
62826 ** in a better query plan.
62827 */
62828 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetVarmask(Vdbe *v, int iVar){
62829   assert( iVar>0 );
62830   if( iVar>32 ){
62831     v->expmask = 0xffffffff;
62832   }else{
62833     v->expmask |= ((u32)1 << (iVar-1));
62834   }
62835 }
62836
62837 /************** End of vdbeaux.c *********************************************/
62838 /************** Begin file vdbeapi.c *****************************************/
62839 /*
62840 ** 2004 May 26
62841 **
62842 ** The author disclaims copyright to this source code.  In place of
62843 ** a legal notice, here is a blessing:
62844 **
62845 **    May you do good and not evil.
62846 **    May you find forgiveness for yourself and forgive others.
62847 **    May you share freely, never taking more than you give.
62848 **
62849 *************************************************************************
62850 **
62851 ** This file contains code use to implement APIs that are part of the
62852 ** VDBE.
62853 */
62854
62855 #ifndef SQLCIPHER_OMIT_DEPRECATED
62856 /*
62857 ** Return TRUE (non-zero) of the statement supplied as an argument needs
62858 ** to be recompiled.  A statement needs to be recompiled whenever the
62859 ** execution environment changes in a way that would alter the program
62860 ** that sqlcipher3_prepare() generates.  For example, if new functions or
62861 ** collating sequences are registered or if an authorizer function is
62862 ** added or changed.
62863 */
62864 SQLCIPHER_API int sqlcipher3_expired(sqlcipher3_stmt *pStmt){
62865   Vdbe *p = (Vdbe*)pStmt;
62866   return p==0 || p->expired;
62867 }
62868 #endif
62869
62870 /*
62871 ** Check on a Vdbe to make sure it has not been finalized.  Log
62872 ** an error and return true if it has been finalized (or is otherwise
62873 ** invalid).  Return false if it is ok.
62874 */
62875 static int vdbeSafety(Vdbe *p){
62876   if( p->db==0 ){
62877     sqlcipher3_log(SQLCIPHER_MISUSE, "API called with finalized prepared statement");
62878     return 1;
62879   }else{
62880     return 0;
62881   }
62882 }
62883 static int vdbeSafetyNotNull(Vdbe *p){
62884   if( p==0 ){
62885     sqlcipher3_log(SQLCIPHER_MISUSE, "API called with NULL prepared statement");
62886     return 1;
62887   }else{
62888     return vdbeSafety(p);
62889   }
62890 }
62891
62892 /*
62893 ** The following routine destroys a virtual machine that is created by
62894 ** the sqlcipher3_compile() routine. The integer returned is an SQLCIPHER_
62895 ** success/failure code that describes the result of executing the virtual
62896 ** machine.
62897 **
62898 ** This routine sets the error code and string returned by
62899 ** sqlcipher3_errcode(), sqlcipher3_errmsg() and sqlcipher3_errmsg16().
62900 */
62901 SQLCIPHER_API int sqlcipher3_finalize(sqlcipher3_stmt *pStmt){
62902   int rc;
62903   if( pStmt==0 ){
62904     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlcipher3_finalize() on a NULL
62905     ** pointer is a harmless no-op. */
62906     rc = SQLCIPHER_OK;
62907   }else{
62908     Vdbe *v = (Vdbe*)pStmt;
62909     sqlcipher3 *db = v->db;
62910 #if SQLCIPHER_THREADSAFE
62911     sqlcipher3_mutex *mutex;
62912 #endif
62913     if( vdbeSafety(v) ) return SQLCIPHER_MISUSE_BKPT;
62914 #if SQLCIPHER_THREADSAFE
62915     mutex = v->db->mutex;
62916 #endif
62917     sqlcipher3_mutex_enter(mutex);
62918     rc = sqlcipher3VdbeFinalize(v);
62919     rc = sqlcipher3ApiExit(db, rc);
62920     sqlcipher3_mutex_leave(mutex);
62921   }
62922   return rc;
62923 }
62924
62925 /*
62926 ** Terminate the current execution of an SQL statement and reset it
62927 ** back to its starting state so that it can be reused. A success code from
62928 ** the prior execution is returned.
62929 **
62930 ** This routine sets the error code and string returned by
62931 ** sqlcipher3_errcode(), sqlcipher3_errmsg() and sqlcipher3_errmsg16().
62932 */
62933 SQLCIPHER_API int sqlcipher3_reset(sqlcipher3_stmt *pStmt){
62934   int rc;
62935   if( pStmt==0 ){
62936     rc = SQLCIPHER_OK;
62937   }else{
62938     Vdbe *v = (Vdbe*)pStmt;
62939     sqlcipher3_mutex_enter(v->db->mutex);
62940     rc = sqlcipher3VdbeReset(v);
62941     sqlcipher3VdbeRewind(v);
62942     assert( (rc & (v->db->errMask))==rc );
62943     rc = sqlcipher3ApiExit(v->db, rc);
62944     sqlcipher3_mutex_leave(v->db->mutex);
62945   }
62946   return rc;
62947 }
62948
62949 /*
62950 ** Set all the parameters in the compiled SQL statement to NULL.
62951 */
62952 SQLCIPHER_API int sqlcipher3_clear_bindings(sqlcipher3_stmt *pStmt){
62953   int i;
62954   int rc = SQLCIPHER_OK;
62955   Vdbe *p = (Vdbe*)pStmt;
62956 #if SQLCIPHER_THREADSAFE
62957   sqlcipher3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
62958 #endif
62959   sqlcipher3_mutex_enter(mutex);
62960   for(i=0; i<p->nVar; i++){
62961     sqlcipher3VdbeMemRelease(&p->aVar[i]);
62962     p->aVar[i].flags = MEM_Null;
62963   }
62964   if( p->isPrepareV2 && p->expmask ){
62965     p->expired = 1;
62966   }
62967   sqlcipher3_mutex_leave(mutex);
62968   return rc;
62969 }
62970
62971
62972 /**************************** sqlcipher3_value_  *******************************
62973 ** The following routines extract information from a Mem or sqlcipher3_value
62974 ** structure.
62975 */
62976 SQLCIPHER_API const void *sqlcipher3_value_blob(sqlcipher3_value *pVal){
62977   Mem *p = (Mem*)pVal;
62978   if( p->flags & (MEM_Blob|MEM_Str) ){
62979     sqlcipher3VdbeMemExpandBlob(p);
62980     p->flags &= ~MEM_Str;
62981     p->flags |= MEM_Blob;
62982     return p->n ? p->z : 0;
62983   }else{
62984     return sqlcipher3_value_text(pVal);
62985   }
62986 }
62987 SQLCIPHER_API int sqlcipher3_value_bytes(sqlcipher3_value *pVal){
62988   return sqlcipher3ValueBytes(pVal, SQLCIPHER_UTF8);
62989 }
62990 SQLCIPHER_API int sqlcipher3_value_bytes16(sqlcipher3_value *pVal){
62991   return sqlcipher3ValueBytes(pVal, SQLCIPHER_UTF16NATIVE);
62992 }
62993 SQLCIPHER_API double sqlcipher3_value_double(sqlcipher3_value *pVal){
62994   return sqlcipher3VdbeRealValue((Mem*)pVal);
62995 }
62996 SQLCIPHER_API int sqlcipher3_value_int(sqlcipher3_value *pVal){
62997   return (int)sqlcipher3VdbeIntValue((Mem*)pVal);
62998 }
62999 SQLCIPHER_API sqlcipher_int64 sqlcipher3_value_int64(sqlcipher3_value *pVal){
63000   return sqlcipher3VdbeIntValue((Mem*)pVal);
63001 }
63002 SQLCIPHER_API const unsigned char *sqlcipher3_value_text(sqlcipher3_value *pVal){
63003   return (const unsigned char *)sqlcipher3ValueText(pVal, SQLCIPHER_UTF8);
63004 }
63005 #ifndef SQLCIPHER_OMIT_UTF16
63006 SQLCIPHER_API const void *sqlcipher3_value_text16(sqlcipher3_value* pVal){
63007   return sqlcipher3ValueText(pVal, SQLCIPHER_UTF16NATIVE);
63008 }
63009 SQLCIPHER_API const void *sqlcipher3_value_text16be(sqlcipher3_value *pVal){
63010   return sqlcipher3ValueText(pVal, SQLCIPHER_UTF16BE);
63011 }
63012 SQLCIPHER_API const void *sqlcipher3_value_text16le(sqlcipher3_value *pVal){
63013   return sqlcipher3ValueText(pVal, SQLCIPHER_UTF16LE);
63014 }
63015 #endif /* SQLCIPHER_OMIT_UTF16 */
63016 SQLCIPHER_API int sqlcipher3_value_type(sqlcipher3_value* pVal){
63017   return pVal->type;
63018 }
63019
63020 /**************************** sqlcipher3_result_  *******************************
63021 ** The following routines are used by user-defined functions to specify
63022 ** the function result.
63023 **
63024 ** The setStrOrError() funtion calls sqlcipher3VdbeMemSetStr() to store the
63025 ** result as a string or blob but if the string or blob is too large, it
63026 ** then sets the error code to SQLCIPHER_TOOBIG
63027 */
63028 static void setResultStrOrError(
63029   sqlcipher3_context *pCtx,  /* Function context */
63030   const char *z,          /* String pointer */
63031   int n,                  /* Bytes in string, or negative */
63032   u8 enc,                 /* Encoding of z.  0 for BLOBs */
63033   void (*xDel)(void*)     /* Destructor function */
63034 ){
63035   if( sqlcipher3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLCIPHER_TOOBIG ){
63036     sqlcipher3_result_error_toobig(pCtx);
63037   }
63038 }
63039 SQLCIPHER_API void sqlcipher3_result_blob(
63040   sqlcipher3_context *pCtx, 
63041   const void *z, 
63042   int n, 
63043   void (*xDel)(void *)
63044 ){
63045   assert( n>=0 );
63046   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63047   setResultStrOrError(pCtx, z, n, 0, xDel);
63048 }
63049 SQLCIPHER_API void sqlcipher3_result_double(sqlcipher3_context *pCtx, double rVal){
63050   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63051   sqlcipher3VdbeMemSetDouble(&pCtx->s, rVal);
63052 }
63053 SQLCIPHER_API void sqlcipher3_result_error(sqlcipher3_context *pCtx, const char *z, int n){
63054   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63055   pCtx->isError = SQLCIPHER_ERROR;
63056   sqlcipher3VdbeMemSetStr(&pCtx->s, z, n, SQLCIPHER_UTF8, SQLCIPHER_TRANSIENT);
63057 }
63058 #ifndef SQLCIPHER_OMIT_UTF16
63059 SQLCIPHER_API void sqlcipher3_result_error16(sqlcipher3_context *pCtx, const void *z, int n){
63060   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63061   pCtx->isError = SQLCIPHER_ERROR;
63062   sqlcipher3VdbeMemSetStr(&pCtx->s, z, n, SQLCIPHER_UTF16NATIVE, SQLCIPHER_TRANSIENT);
63063 }
63064 #endif
63065 SQLCIPHER_API void sqlcipher3_result_int(sqlcipher3_context *pCtx, int iVal){
63066   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63067   sqlcipher3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
63068 }
63069 SQLCIPHER_API void sqlcipher3_result_int64(sqlcipher3_context *pCtx, i64 iVal){
63070   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63071   sqlcipher3VdbeMemSetInt64(&pCtx->s, iVal);
63072 }
63073 SQLCIPHER_API void sqlcipher3_result_null(sqlcipher3_context *pCtx){
63074   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63075   sqlcipher3VdbeMemSetNull(&pCtx->s);
63076 }
63077 SQLCIPHER_API void sqlcipher3_result_text(
63078   sqlcipher3_context *pCtx, 
63079   const char *z, 
63080   int n,
63081   void (*xDel)(void *)
63082 ){
63083   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63084   setResultStrOrError(pCtx, z, n, SQLCIPHER_UTF8, xDel);
63085 }
63086 #ifndef SQLCIPHER_OMIT_UTF16
63087 SQLCIPHER_API void sqlcipher3_result_text16(
63088   sqlcipher3_context *pCtx, 
63089   const void *z, 
63090   int n, 
63091   void (*xDel)(void *)
63092 ){
63093   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63094   setResultStrOrError(pCtx, z, n, SQLCIPHER_UTF16NATIVE, xDel);
63095 }
63096 SQLCIPHER_API void sqlcipher3_result_text16be(
63097   sqlcipher3_context *pCtx, 
63098   const void *z, 
63099   int n, 
63100   void (*xDel)(void *)
63101 ){
63102   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63103   setResultStrOrError(pCtx, z, n, SQLCIPHER_UTF16BE, xDel);
63104 }
63105 SQLCIPHER_API void sqlcipher3_result_text16le(
63106   sqlcipher3_context *pCtx, 
63107   const void *z, 
63108   int n, 
63109   void (*xDel)(void *)
63110 ){
63111   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63112   setResultStrOrError(pCtx, z, n, SQLCIPHER_UTF16LE, xDel);
63113 }
63114 #endif /* SQLCIPHER_OMIT_UTF16 */
63115 SQLCIPHER_API void sqlcipher3_result_value(sqlcipher3_context *pCtx, sqlcipher3_value *pValue){
63116   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63117   sqlcipher3VdbeMemCopy(&pCtx->s, pValue);
63118 }
63119 SQLCIPHER_API void sqlcipher3_result_zeroblob(sqlcipher3_context *pCtx, int n){
63120   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63121   sqlcipher3VdbeMemSetZeroBlob(&pCtx->s, n);
63122 }
63123 SQLCIPHER_API void sqlcipher3_result_error_code(sqlcipher3_context *pCtx, int errCode){
63124   pCtx->isError = errCode;
63125   if( pCtx->s.flags & MEM_Null ){
63126     sqlcipher3VdbeMemSetStr(&pCtx->s, sqlcipher3ErrStr(errCode), -1, 
63127                          SQLCIPHER_UTF8, SQLCIPHER_STATIC);
63128   }
63129 }
63130
63131 /* Force an SQLCIPHER_TOOBIG error. */
63132 SQLCIPHER_API void sqlcipher3_result_error_toobig(sqlcipher3_context *pCtx){
63133   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63134   pCtx->isError = SQLCIPHER_TOOBIG;
63135   sqlcipher3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
63136                        SQLCIPHER_UTF8, SQLCIPHER_STATIC);
63137 }
63138
63139 /* An SQLCIPHER_NOMEM error. */
63140 SQLCIPHER_API void sqlcipher3_result_error_nomem(sqlcipher3_context *pCtx){
63141   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63142   sqlcipher3VdbeMemSetNull(&pCtx->s);
63143   pCtx->isError = SQLCIPHER_NOMEM;
63144   pCtx->s.db->mallocFailed = 1;
63145 }
63146
63147 /*
63148 ** This function is called after a transaction has been committed. It 
63149 ** invokes callbacks registered with sqlcipher3_wal_hook() as required.
63150 */
63151 static int doWalCallbacks(sqlcipher3 *db){
63152   int rc = SQLCIPHER_OK;
63153 #ifndef SQLCIPHER_OMIT_WAL
63154   int i;
63155   for(i=0; i<db->nDb; i++){
63156     Btree *pBt = db->aDb[i].pBt;
63157     if( pBt ){
63158       int nEntry = sqlcipher3PagerWalCallback(sqlcipher3BtreePager(pBt));
63159       if( db->xWalCallback && nEntry>0 && rc==SQLCIPHER_OK ){
63160         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
63161       }
63162     }
63163   }
63164 #endif
63165   return rc;
63166 }
63167
63168 /*
63169 ** Execute the statement pStmt, either until a row of data is ready, the
63170 ** statement is completely executed or an error occurs.
63171 **
63172 ** This routine implements the bulk of the logic behind the sqlcipher_step()
63173 ** API.  The only thing omitted is the automatic recompile if a 
63174 ** schema change has occurred.  That detail is handled by the
63175 ** outer sqlcipher3_step() wrapper procedure.
63176 */
63177 static int sqlcipher3Step(Vdbe *p){
63178   sqlcipher3 *db;
63179   int rc;
63180
63181   assert(p);
63182   if( p->magic!=VDBE_MAGIC_RUN ){
63183     /* We used to require that sqlcipher3_reset() be called before retrying
63184     ** sqlcipher3_step() after any error or after SQLCIPHER_DONE.  But beginning
63185     ** with version 3.7.0, we changed this so that sqlcipher3_reset() would
63186     ** be called automatically instead of throwing the SQLCIPHER_MISUSE error.
63187     ** This "automatic-reset" change is not technically an incompatibility, 
63188     ** since any application that receives an SQLCIPHER_MISUSE is broken by
63189     ** definition.
63190     **
63191     ** Nevertheless, some published applications that were originally written
63192     ** for version 3.6.23 or earlier do in fact depend on SQLCIPHER_MISUSE 
63193     ** returns, and the so were broken by the automatic-reset change.  As a
63194     ** a work-around, the SQLCIPHER_OMIT_AUTORESET compile-time restores the
63195     ** legacy behavior of returning SQLCIPHER_MISUSE for cases where the 
63196     ** previous sqlcipher3_step() returned something other than a SQLCIPHER_LOCKED
63197     ** or SQLCIPHER_BUSY error.
63198     */
63199 #ifdef SQLCIPHER_OMIT_AUTORESET
63200     if( p->rc==SQLCIPHER_BUSY || p->rc==SQLCIPHER_LOCKED ){
63201       sqlcipher3_reset((sqlcipher3_stmt*)p);
63202     }else{
63203       return SQLCIPHER_MISUSE_BKPT;
63204     }
63205 #else
63206     sqlcipher3_reset((sqlcipher3_stmt*)p);
63207 #endif
63208   }
63209
63210   /* Check that malloc() has not failed. If it has, return early. */
63211   db = p->db;
63212   if( db->mallocFailed ){
63213     p->rc = SQLCIPHER_NOMEM;
63214     return SQLCIPHER_NOMEM;
63215   }
63216
63217   if( p->pc<=0 && p->expired ){
63218     p->rc = SQLCIPHER_SCHEMA;
63219     rc = SQLCIPHER_ERROR;
63220     goto end_of_step;
63221   }
63222   if( p->pc<0 ){
63223     /* If there are no other statements currently running, then
63224     ** reset the interrupt flag.  This prevents a call to sqlcipher3_interrupt
63225     ** from interrupting a statement that has not yet started.
63226     */
63227     if( db->activeVdbeCnt==0 ){
63228       db->u1.isInterrupted = 0;
63229     }
63230
63231     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
63232
63233 #ifndef SQLCIPHER_OMIT_TRACE
63234     if( db->xProfile && !db->init.busy ){
63235       sqlcipher3OsCurrentTimeInt64(db->pVfs, &p->startTime);
63236     }
63237 #endif
63238
63239     db->activeVdbeCnt++;
63240     if( p->readOnly==0 ) db->writeVdbeCnt++;
63241     p->pc = 0;
63242   }
63243 #ifndef SQLCIPHER_OMIT_EXPLAIN
63244   if( p->explain ){
63245     rc = sqlcipher3VdbeList(p);
63246   }else
63247 #endif /* SQLCIPHER_OMIT_EXPLAIN */
63248   {
63249     db->vdbeExecCnt++;
63250     rc = sqlcipher3VdbeExec(p);
63251     db->vdbeExecCnt--;
63252   }
63253
63254 #ifndef SQLCIPHER_OMIT_TRACE
63255   /* Invoke the profile callback if there is one
63256   */
63257   if( rc!=SQLCIPHER_ROW && db->xProfile && !db->init.busy && p->zSql ){
63258     sqlcipher3_int64 iNow;
63259     sqlcipher3OsCurrentTimeInt64(db->pVfs, &iNow);
63260     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
63261   }
63262 #endif
63263
63264   if( rc==SQLCIPHER_DONE ){
63265     assert( p->rc==SQLCIPHER_OK );
63266     p->rc = doWalCallbacks(db);
63267     if( p->rc!=SQLCIPHER_OK ){
63268       rc = SQLCIPHER_ERROR;
63269     }
63270   }
63271
63272   db->errCode = rc;
63273   if( SQLCIPHER_NOMEM==sqlcipher3ApiExit(p->db, p->rc) ){
63274     p->rc = SQLCIPHER_NOMEM;
63275   }
63276 end_of_step:
63277   /* At this point local variable rc holds the value that should be 
63278   ** returned if this statement was compiled using the legacy 
63279   ** sqlcipher3_prepare() interface. According to the docs, this can only
63280   ** be one of the values in the first assert() below. Variable p->rc 
63281   ** contains the value that would be returned if sqlcipher3_finalize() 
63282   ** were called on statement p.
63283   */
63284   assert( rc==SQLCIPHER_ROW  || rc==SQLCIPHER_DONE   || rc==SQLCIPHER_ERROR 
63285        || rc==SQLCIPHER_BUSY || rc==SQLCIPHER_MISUSE
63286   );
63287   assert( p->rc!=SQLCIPHER_ROW && p->rc!=SQLCIPHER_DONE );
63288   if( p->isPrepareV2 && rc!=SQLCIPHER_ROW && rc!=SQLCIPHER_DONE ){
63289     /* If this statement was prepared using sqlcipher3_prepare_v2(), and an
63290     ** error has occured, then return the error code in p->rc to the
63291     ** caller. Set the error code in the database handle to the same value.
63292     */ 
63293     rc = sqlcipher3VdbeTransferError(p);
63294   }
63295   return (rc&db->errMask);
63296 }
63297
63298 /*
63299 ** The maximum number of times that a statement will try to reparse
63300 ** itself before giving up and returning SQLCIPHER_SCHEMA.
63301 */
63302 #ifndef SQLCIPHER_MAX_SCHEMA_RETRY
63303 # define SQLCIPHER_MAX_SCHEMA_RETRY 5
63304 #endif
63305
63306 /*
63307 ** This is the top-level implementation of sqlcipher3_step().  Call
63308 ** sqlcipher3Step() to do most of the work.  If a schema error occurs,
63309 ** call sqlcipher3Reprepare() and try again.
63310 */
63311 SQLCIPHER_API int sqlcipher3_step(sqlcipher3_stmt *pStmt){
63312   int rc = SQLCIPHER_OK;      /* Result from sqlcipher3Step() */
63313   int rc2 = SQLCIPHER_OK;     /* Result from sqlcipher3Reprepare() */
63314   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
63315   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
63316   sqlcipher3 *db;             /* The database connection */
63317
63318   if( vdbeSafetyNotNull(v) ){
63319     return SQLCIPHER_MISUSE_BKPT;
63320   }
63321   db = v->db;
63322   sqlcipher3_mutex_enter(db->mutex);
63323   while( (rc = sqlcipher3Step(v))==SQLCIPHER_SCHEMA
63324          && cnt++ < SQLCIPHER_MAX_SCHEMA_RETRY
63325          && (rc2 = rc = sqlcipher3Reprepare(v))==SQLCIPHER_OK ){
63326     sqlcipher3_reset(pStmt);
63327     assert( v->expired==0 );
63328   }
63329   if( rc2!=SQLCIPHER_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
63330     /* This case occurs after failing to recompile an sql statement. 
63331     ** The error message from the SQL compiler has already been loaded 
63332     ** into the database handle. This block copies the error message 
63333     ** from the database handle into the statement and sets the statement
63334     ** program counter to 0 to ensure that when the statement is 
63335     ** finalized or reset the parser error message is available via
63336     ** sqlcipher3_errmsg() and sqlcipher3_errcode().
63337     */
63338     const char *zErr = (const char *)sqlcipher3_value_text(db->pErr); 
63339     sqlcipher3DbFree(db, v->zErrMsg);
63340     if( !db->mallocFailed ){
63341       v->zErrMsg = sqlcipher3DbStrDup(db, zErr);
63342       v->rc = rc2;
63343     } else {
63344       v->zErrMsg = 0;
63345       v->rc = rc = SQLCIPHER_NOMEM;
63346     }
63347   }
63348   rc = sqlcipher3ApiExit(db, rc);
63349   sqlcipher3_mutex_leave(db->mutex);
63350   return rc;
63351 }
63352
63353 /*
63354 ** Extract the user data from a sqlcipher3_context structure and return a
63355 ** pointer to it.
63356 */
63357 SQLCIPHER_API void *sqlcipher3_user_data(sqlcipher3_context *p){
63358   assert( p && p->pFunc );
63359   return p->pFunc->pUserData;
63360 }
63361
63362 /*
63363 ** Extract the user data from a sqlcipher3_context structure and return a
63364 ** pointer to it.
63365 **
63366 ** IMPLEMENTATION-OF: R-46798-50301 The sqlcipher3_context_db_handle() interface
63367 ** returns a copy of the pointer to the database connection (the 1st
63368 ** parameter) of the sqlcipher3_create_function() and
63369 ** sqlcipher3_create_function16() routines that originally registered the
63370 ** application defined function.
63371 */
63372 SQLCIPHER_API sqlcipher3 *sqlcipher3_context_db_handle(sqlcipher3_context *p){
63373   assert( p && p->pFunc );
63374   return p->s.db;
63375 }
63376
63377 /*
63378 ** The following is the implementation of an SQL function that always
63379 ** fails with an error message stating that the function is used in the
63380 ** wrong context.  The sqlcipher3_overload_function() API might construct
63381 ** SQL function that use this routine so that the functions will exist
63382 ** for name resolution but are actually overloaded by the xFindFunction
63383 ** method of virtual tables.
63384 */
63385 SQLCIPHER_PRIVATE void sqlcipher3InvalidFunction(
63386   sqlcipher3_context *context,  /* The function calling context */
63387   int NotUsed,               /* Number of arguments to the function */
63388   sqlcipher3_value **NotUsed2   /* Value of each argument */
63389 ){
63390   const char *zName = context->pFunc->zName;
63391   char *zErr;
63392   UNUSED_PARAMETER2(NotUsed, NotUsed2);
63393   zErr = sqlcipher3_mprintf(
63394       "unable to use function %s in the requested context", zName);
63395   sqlcipher3_result_error(context, zErr, -1);
63396   sqlcipher3_free(zErr);
63397 }
63398
63399 /*
63400 ** Allocate or return the aggregate context for a user function.  A new
63401 ** context is allocated on the first call.  Subsequent calls return the
63402 ** same context that was returned on prior calls.
63403 */
63404 SQLCIPHER_API void *sqlcipher3_aggregate_context(sqlcipher3_context *p, int nByte){
63405   Mem *pMem;
63406   assert( p && p->pFunc && p->pFunc->xStep );
63407   assert( sqlcipher3_mutex_held(p->s.db->mutex) );
63408   pMem = p->pMem;
63409   testcase( nByte<0 );
63410   if( (pMem->flags & MEM_Agg)==0 ){
63411     if( nByte<=0 ){
63412       sqlcipher3VdbeMemReleaseExternal(pMem);
63413       pMem->flags = MEM_Null;
63414       pMem->z = 0;
63415     }else{
63416       sqlcipher3VdbeMemGrow(pMem, nByte, 0);
63417       pMem->flags = MEM_Agg;
63418       pMem->u.pDef = p->pFunc;
63419       if( pMem->z ){
63420         memset(pMem->z, 0, nByte);
63421       }
63422     }
63423   }
63424   return (void*)pMem->z;
63425 }
63426
63427 /*
63428 ** Return the auxilary data pointer, if any, for the iArg'th argument to
63429 ** the user-function defined by pCtx.
63430 */
63431 SQLCIPHER_API void *sqlcipher3_get_auxdata(sqlcipher3_context *pCtx, int iArg){
63432   VdbeFunc *pVdbeFunc;
63433
63434   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63435   pVdbeFunc = pCtx->pVdbeFunc;
63436   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
63437     return 0;
63438   }
63439   return pVdbeFunc->apAux[iArg].pAux;
63440 }
63441
63442 /*
63443 ** Set the auxilary data pointer and delete function, for the iArg'th
63444 ** argument to the user-function defined by pCtx. Any previous value is
63445 ** deleted by calling the delete function specified when it was set.
63446 */
63447 SQLCIPHER_API void sqlcipher3_set_auxdata(
63448   sqlcipher3_context *pCtx, 
63449   int iArg, 
63450   void *pAux, 
63451   void (*xDelete)(void*)
63452 ){
63453   struct AuxData *pAuxData;
63454   VdbeFunc *pVdbeFunc;
63455   if( iArg<0 ) goto failed;
63456
63457   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63458   pVdbeFunc = pCtx->pVdbeFunc;
63459   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
63460     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
63461     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
63462     pVdbeFunc = sqlcipher3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
63463     if( !pVdbeFunc ){
63464       goto failed;
63465     }
63466     pCtx->pVdbeFunc = pVdbeFunc;
63467     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
63468     pVdbeFunc->nAux = iArg+1;
63469     pVdbeFunc->pFunc = pCtx->pFunc;
63470   }
63471
63472   pAuxData = &pVdbeFunc->apAux[iArg];
63473   if( pAuxData->pAux && pAuxData->xDelete ){
63474     pAuxData->xDelete(pAuxData->pAux);
63475   }
63476   pAuxData->pAux = pAux;
63477   pAuxData->xDelete = xDelete;
63478   return;
63479
63480 failed:
63481   if( xDelete ){
63482     xDelete(pAux);
63483   }
63484 }
63485
63486 #ifndef SQLCIPHER_OMIT_DEPRECATED
63487 /*
63488 ** Return the number of times the Step function of a aggregate has been 
63489 ** called.
63490 **
63491 ** This function is deprecated.  Do not use it for new code.  It is
63492 ** provide only to avoid breaking legacy code.  New aggregate function
63493 ** implementations should keep their own counts within their aggregate
63494 ** context.
63495 */
63496 SQLCIPHER_API int sqlcipher3_aggregate_count(sqlcipher3_context *p){
63497   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
63498   return p->pMem->n;
63499 }
63500 #endif
63501
63502 /*
63503 ** Return the number of columns in the result set for the statement pStmt.
63504 */
63505 SQLCIPHER_API int sqlcipher3_column_count(sqlcipher3_stmt *pStmt){
63506   Vdbe *pVm = (Vdbe *)pStmt;
63507   return pVm ? pVm->nResColumn : 0;
63508 }
63509
63510 /*
63511 ** Return the number of values available from the current row of the
63512 ** currently executing statement pStmt.
63513 */
63514 SQLCIPHER_API int sqlcipher3_data_count(sqlcipher3_stmt *pStmt){
63515   Vdbe *pVm = (Vdbe *)pStmt;
63516   if( pVm==0 || pVm->pResultSet==0 ) return 0;
63517   return pVm->nResColumn;
63518 }
63519
63520
63521 /*
63522 ** Check to see if column iCol of the given statement is valid.  If
63523 ** it is, return a pointer to the Mem for the value of that column.
63524 ** If iCol is not valid, return a pointer to a Mem which has a value
63525 ** of NULL.
63526 */
63527 static Mem *columnMem(sqlcipher3_stmt *pStmt, int i){
63528   Vdbe *pVm;
63529   Mem *pOut;
63530
63531   pVm = (Vdbe *)pStmt;
63532   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
63533     sqlcipher3_mutex_enter(pVm->db->mutex);
63534     pOut = &pVm->pResultSet[i];
63535   }else{
63536     /* If the value passed as the second argument is out of range, return
63537     ** a pointer to the following static Mem object which contains the
63538     ** value SQL NULL. Even though the Mem structure contains an element
63539     ** of type i64, on certain architecture (x86) with certain compiler
63540     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
63541     ** instead of an 8-byte one. This all works fine, except that when
63542     ** running with SQLCIPHER_DEBUG defined the SQLite code sometimes assert()s
63543     ** that a Mem structure is located on an 8-byte boundary. To prevent
63544     ** this assert() from failing, when building with SQLCIPHER_DEBUG defined
63545     ** using gcc, force nullMem to be 8-byte aligned using the magical
63546     ** __attribute__((aligned(8))) macro.  */
63547     static const Mem nullMem 
63548 #if defined(SQLCIPHER_DEBUG) && defined(__GNUC__)
63549       __attribute__((aligned(8))) 
63550 #endif
63551       = {0, "", (double)0, {0}, 0, MEM_Null, SQLCIPHER_NULL, 0,
63552 #ifdef SQLCIPHER_DEBUG
63553          0, 0,  /* pScopyFrom, pFiller */
63554 #endif
63555          0, 0 };
63556
63557     if( pVm && ALWAYS(pVm->db) ){
63558       sqlcipher3_mutex_enter(pVm->db->mutex);
63559       sqlcipher3Error(pVm->db, SQLCIPHER_RANGE, 0);
63560     }
63561     pOut = (Mem*)&nullMem;
63562   }
63563   return pOut;
63564 }
63565
63566 /*
63567 ** This function is called after invoking an sqlcipher3_value_XXX function on a 
63568 ** column value (i.e. a value returned by evaluating an SQL expression in the
63569 ** select list of a SELECT statement) that may cause a malloc() failure. If 
63570 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
63571 ** code of statement pStmt set to SQLCIPHER_NOMEM.
63572 **
63573 ** Specifically, this is called from within:
63574 **
63575 **     sqlcipher3_column_int()
63576 **     sqlcipher3_column_int64()
63577 **     sqlcipher3_column_text()
63578 **     sqlcipher3_column_text16()
63579 **     sqlcipher3_column_real()
63580 **     sqlcipher3_column_bytes()
63581 **     sqlcipher3_column_bytes16()
63582 **     sqiite3_column_blob()
63583 */
63584 static void columnMallocFailure(sqlcipher3_stmt *pStmt)
63585 {
63586   /* If malloc() failed during an encoding conversion within an
63587   ** sqlcipher3_column_XXX API, then set the return code of the statement to
63588   ** SQLCIPHER_NOMEM. The next call to _step() (if any) will return SQLCIPHER_ERROR
63589   ** and _finalize() will return NOMEM.
63590   */
63591   Vdbe *p = (Vdbe *)pStmt;
63592   if( p ){
63593     p->rc = sqlcipher3ApiExit(p->db, p->rc);
63594     sqlcipher3_mutex_leave(p->db->mutex);
63595   }
63596 }
63597
63598 /**************************** sqlcipher3_column_  *******************************
63599 ** The following routines are used to access elements of the current row
63600 ** in the result set.
63601 */
63602 SQLCIPHER_API const void *sqlcipher3_column_blob(sqlcipher3_stmt *pStmt, int i){
63603   const void *val;
63604   val = sqlcipher3_value_blob( columnMem(pStmt,i) );
63605   /* Even though there is no encoding conversion, value_blob() might
63606   ** need to call malloc() to expand the result of a zeroblob() 
63607   ** expression. 
63608   */
63609   columnMallocFailure(pStmt);
63610   return val;
63611 }
63612 SQLCIPHER_API int sqlcipher3_column_bytes(sqlcipher3_stmt *pStmt, int i){
63613   int val = sqlcipher3_value_bytes( columnMem(pStmt,i) );
63614   columnMallocFailure(pStmt);
63615   return val;
63616 }
63617 SQLCIPHER_API int sqlcipher3_column_bytes16(sqlcipher3_stmt *pStmt, int i){
63618   int val = sqlcipher3_value_bytes16( columnMem(pStmt,i) );
63619   columnMallocFailure(pStmt);
63620   return val;
63621 }
63622 SQLCIPHER_API double sqlcipher3_column_double(sqlcipher3_stmt *pStmt, int i){
63623   double val = sqlcipher3_value_double( columnMem(pStmt,i) );
63624   columnMallocFailure(pStmt);
63625   return val;
63626 }
63627 SQLCIPHER_API int sqlcipher3_column_int(sqlcipher3_stmt *pStmt, int i){
63628   int val = sqlcipher3_value_int( columnMem(pStmt,i) );
63629   columnMallocFailure(pStmt);
63630   return val;
63631 }
63632 SQLCIPHER_API sqlcipher_int64 sqlcipher3_column_int64(sqlcipher3_stmt *pStmt, int i){
63633   sqlcipher_int64 val = sqlcipher3_value_int64( columnMem(pStmt,i) );
63634   columnMallocFailure(pStmt);
63635   return val;
63636 }
63637 SQLCIPHER_API const unsigned char *sqlcipher3_column_text(sqlcipher3_stmt *pStmt, int i){
63638   const unsigned char *val = sqlcipher3_value_text( columnMem(pStmt,i) );
63639   columnMallocFailure(pStmt);
63640   return val;
63641 }
63642 SQLCIPHER_API sqlcipher3_value *sqlcipher3_column_value(sqlcipher3_stmt *pStmt, int i){
63643   Mem *pOut = columnMem(pStmt, i);
63644   if( pOut->flags&MEM_Static ){
63645     pOut->flags &= ~MEM_Static;
63646     pOut->flags |= MEM_Ephem;
63647   }
63648   columnMallocFailure(pStmt);
63649   return (sqlcipher3_value *)pOut;
63650 }
63651 #ifndef SQLCIPHER_OMIT_UTF16
63652 SQLCIPHER_API const void *sqlcipher3_column_text16(sqlcipher3_stmt *pStmt, int i){
63653   const void *val = sqlcipher3_value_text16( columnMem(pStmt,i) );
63654   columnMallocFailure(pStmt);
63655   return val;
63656 }
63657 #endif /* SQLCIPHER_OMIT_UTF16 */
63658 SQLCIPHER_API int sqlcipher3_column_type(sqlcipher3_stmt *pStmt, int i){
63659   int iType = sqlcipher3_value_type( columnMem(pStmt,i) );
63660   columnMallocFailure(pStmt);
63661   return iType;
63662 }
63663
63664 /* The following function is experimental and subject to change or
63665 ** removal */
63666 /*int sqlcipher3_column_numeric_type(sqlcipher3_stmt *pStmt, int i){
63667 **  return sqlcipher3_value_numeric_type( columnMem(pStmt,i) );
63668 **}
63669 */
63670
63671 /*
63672 ** Convert the N-th element of pStmt->pColName[] into a string using
63673 ** xFunc() then return that string.  If N is out of range, return 0.
63674 **
63675 ** There are up to 5 names for each column.  useType determines which
63676 ** name is returned.  Here are the names:
63677 **
63678 **    0      The column name as it should be displayed for output
63679 **    1      The datatype name for the column
63680 **    2      The name of the database that the column derives from
63681 **    3      The name of the table that the column derives from
63682 **    4      The name of the table column that the result column derives from
63683 **
63684 ** If the result is not a simple column reference (if it is an expression
63685 ** or a constant) then useTypes 2, 3, and 4 return NULL.
63686 */
63687 static const void *columnName(
63688   sqlcipher3_stmt *pStmt,
63689   int N,
63690   const void *(*xFunc)(Mem*),
63691   int useType
63692 ){
63693   const void *ret = 0;
63694   Vdbe *p = (Vdbe *)pStmt;
63695   int n;
63696   sqlcipher3 *db = p->db;
63697   
63698   assert( db!=0 );
63699   n = sqlcipher3_column_count(pStmt);
63700   if( N<n && N>=0 ){
63701     N += useType*n;
63702     sqlcipher3_mutex_enter(db->mutex);
63703     assert( db->mallocFailed==0 );
63704     ret = xFunc(&p->aColName[N]);
63705      /* A malloc may have failed inside of the xFunc() call. If this
63706     ** is the case, clear the mallocFailed flag and return NULL.
63707     */
63708     if( db->mallocFailed ){
63709       db->mallocFailed = 0;
63710       ret = 0;
63711     }
63712     sqlcipher3_mutex_leave(db->mutex);
63713   }
63714   return ret;
63715 }
63716
63717 /*
63718 ** Return the name of the Nth column of the result set returned by SQL
63719 ** statement pStmt.
63720 */
63721 SQLCIPHER_API const char *sqlcipher3_column_name(sqlcipher3_stmt *pStmt, int N){
63722   return columnName(
63723       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text, COLNAME_NAME);
63724 }
63725 #ifndef SQLCIPHER_OMIT_UTF16
63726 SQLCIPHER_API const void *sqlcipher3_column_name16(sqlcipher3_stmt *pStmt, int N){
63727   return columnName(
63728       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text16, COLNAME_NAME);
63729 }
63730 #endif
63731
63732 /*
63733 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
63734 ** not define OMIT_DECLTYPE.
63735 */
63736 #if defined(SQLCIPHER_OMIT_DECLTYPE) && defined(SQLCIPHER_ENABLE_COLUMN_METADATA)
63737 # error "Must not define both SQLCIPHER_OMIT_DECLTYPE \
63738          and SQLCIPHER_ENABLE_COLUMN_METADATA"
63739 #endif
63740
63741 #ifndef SQLCIPHER_OMIT_DECLTYPE
63742 /*
63743 ** Return the column declaration type (if applicable) of the 'i'th column
63744 ** of the result set of SQL statement pStmt.
63745 */
63746 SQLCIPHER_API const char *sqlcipher3_column_decltype(sqlcipher3_stmt *pStmt, int N){
63747   return columnName(
63748       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text, COLNAME_DECLTYPE);
63749 }
63750 #ifndef SQLCIPHER_OMIT_UTF16
63751 SQLCIPHER_API const void *sqlcipher3_column_decltype16(sqlcipher3_stmt *pStmt, int N){
63752   return columnName(
63753       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text16, COLNAME_DECLTYPE);
63754 }
63755 #endif /* SQLCIPHER_OMIT_UTF16 */
63756 #endif /* SQLCIPHER_OMIT_DECLTYPE */
63757
63758 #ifdef SQLCIPHER_ENABLE_COLUMN_METADATA
63759 /*
63760 ** Return the name of the database from which a result column derives.
63761 ** NULL is returned if the result column is an expression or constant or
63762 ** anything else which is not an unabiguous reference to a database column.
63763 */
63764 SQLCIPHER_API const char *sqlcipher3_column_database_name(sqlcipher3_stmt *pStmt, int N){
63765   return columnName(
63766       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text, COLNAME_DATABASE);
63767 }
63768 #ifndef SQLCIPHER_OMIT_UTF16
63769 SQLCIPHER_API const void *sqlcipher3_column_database_name16(sqlcipher3_stmt *pStmt, int N){
63770   return columnName(
63771       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text16, COLNAME_DATABASE);
63772 }
63773 #endif /* SQLCIPHER_OMIT_UTF16 */
63774
63775 /*
63776 ** Return the name of the table from which a result column derives.
63777 ** NULL is returned if the result column is an expression or constant or
63778 ** anything else which is not an unabiguous reference to a database column.
63779 */
63780 SQLCIPHER_API const char *sqlcipher3_column_table_name(sqlcipher3_stmt *pStmt, int N){
63781   return columnName(
63782       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text, COLNAME_TABLE);
63783 }
63784 #ifndef SQLCIPHER_OMIT_UTF16
63785 SQLCIPHER_API const void *sqlcipher3_column_table_name16(sqlcipher3_stmt *pStmt, int N){
63786   return columnName(
63787       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text16, COLNAME_TABLE);
63788 }
63789 #endif /* SQLCIPHER_OMIT_UTF16 */
63790
63791 /*
63792 ** Return the name of the table column from which a result column derives.
63793 ** NULL is returned if the result column is an expression or constant or
63794 ** anything else which is not an unabiguous reference to a database column.
63795 */
63796 SQLCIPHER_API const char *sqlcipher3_column_origin_name(sqlcipher3_stmt *pStmt, int N){
63797   return columnName(
63798       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text, COLNAME_COLUMN);
63799 }
63800 #ifndef SQLCIPHER_OMIT_UTF16
63801 SQLCIPHER_API const void *sqlcipher3_column_origin_name16(sqlcipher3_stmt *pStmt, int N){
63802   return columnName(
63803       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text16, COLNAME_COLUMN);
63804 }
63805 #endif /* SQLCIPHER_OMIT_UTF16 */
63806 #endif /* SQLCIPHER_ENABLE_COLUMN_METADATA */
63807
63808
63809 /******************************* sqlcipher3_bind_  ***************************
63810 ** 
63811 ** Routines used to attach values to wildcards in a compiled SQL statement.
63812 */
63813 /*
63814 ** Unbind the value bound to variable i in virtual machine p. This is the 
63815 ** the same as binding a NULL value to the column. If the "i" parameter is
63816 ** out of range, then SQLCIPHER_RANGE is returned. Othewise SQLCIPHER_OK.
63817 **
63818 ** A successful evaluation of this routine acquires the mutex on p.
63819 ** the mutex is released if any kind of error occurs.
63820 **
63821 ** The error code stored in database p->db is overwritten with the return
63822 ** value in any case.
63823 */
63824 static int vdbeUnbind(Vdbe *p, int i){
63825   Mem *pVar;
63826   if( vdbeSafetyNotNull(p) ){
63827     return SQLCIPHER_MISUSE_BKPT;
63828   }
63829   sqlcipher3_mutex_enter(p->db->mutex);
63830   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
63831     sqlcipher3Error(p->db, SQLCIPHER_MISUSE, 0);
63832     sqlcipher3_mutex_leave(p->db->mutex);
63833     sqlcipher3_log(SQLCIPHER_MISUSE, 
63834         "bind on a busy prepared statement: [%s]", p->zSql);
63835     return SQLCIPHER_MISUSE_BKPT;
63836   }
63837   if( i<1 || i>p->nVar ){
63838     sqlcipher3Error(p->db, SQLCIPHER_RANGE, 0);
63839     sqlcipher3_mutex_leave(p->db->mutex);
63840     return SQLCIPHER_RANGE;
63841   }
63842   i--;
63843   pVar = &p->aVar[i];
63844   sqlcipher3VdbeMemRelease(pVar);
63845   pVar->flags = MEM_Null;
63846   sqlcipher3Error(p->db, SQLCIPHER_OK, 0);
63847
63848   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
63849   ** binding a new value to this variable invalidates the current query plan.
63850   **
63851   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
63852   ** parameter in the WHERE clause might influence the choice of query plan
63853   ** for a statement, then the statement will be automatically recompiled,
63854   ** as if there had been a schema change, on the first sqlcipher3_step() call
63855   ** following any change to the bindings of that parameter.
63856   */
63857   if( p->isPrepareV2 &&
63858      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
63859   ){
63860     p->expired = 1;
63861   }
63862   return SQLCIPHER_OK;
63863 }
63864
63865 /*
63866 ** Bind a text or BLOB value.
63867 */
63868 static int bindText(
63869   sqlcipher3_stmt *pStmt,   /* The statement to bind against */
63870   int i,                 /* Index of the parameter to bind */
63871   const void *zData,     /* Pointer to the data to be bound */
63872   int nData,             /* Number of bytes of data to be bound */
63873   void (*xDel)(void*),   /* Destructor for the data */
63874   u8 encoding            /* Encoding for the data */
63875 ){
63876   Vdbe *p = (Vdbe *)pStmt;
63877   Mem *pVar;
63878   int rc;
63879
63880   rc = vdbeUnbind(p, i);
63881   if( rc==SQLCIPHER_OK ){
63882     if( zData!=0 ){
63883       pVar = &p->aVar[i-1];
63884       rc = sqlcipher3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
63885       if( rc==SQLCIPHER_OK && encoding!=0 ){
63886         rc = sqlcipher3VdbeChangeEncoding(pVar, ENC(p->db));
63887       }
63888       sqlcipher3Error(p->db, rc, 0);
63889       rc = sqlcipher3ApiExit(p->db, rc);
63890     }
63891     sqlcipher3_mutex_leave(p->db->mutex);
63892   }else if( xDel!=SQLCIPHER_STATIC && xDel!=SQLCIPHER_TRANSIENT ){
63893     xDel((void*)zData);
63894   }
63895   return rc;
63896 }
63897
63898
63899 /*
63900 ** Bind a blob value to an SQL statement variable.
63901 */
63902 SQLCIPHER_API int sqlcipher3_bind_blob(
63903   sqlcipher3_stmt *pStmt, 
63904   int i, 
63905   const void *zData, 
63906   int nData, 
63907   void (*xDel)(void*)
63908 ){
63909   return bindText(pStmt, i, zData, nData, xDel, 0);
63910 }
63911 SQLCIPHER_API int sqlcipher3_bind_double(sqlcipher3_stmt *pStmt, int i, double rValue){
63912   int rc;
63913   Vdbe *p = (Vdbe *)pStmt;
63914   rc = vdbeUnbind(p, i);
63915   if( rc==SQLCIPHER_OK ){
63916     sqlcipher3VdbeMemSetDouble(&p->aVar[i-1], rValue);
63917     sqlcipher3_mutex_leave(p->db->mutex);
63918   }
63919   return rc;
63920 }
63921 SQLCIPHER_API int sqlcipher3_bind_int(sqlcipher3_stmt *p, int i, int iValue){
63922   return sqlcipher3_bind_int64(p, i, (i64)iValue);
63923 }
63924 SQLCIPHER_API int sqlcipher3_bind_int64(sqlcipher3_stmt *pStmt, int i, sqlcipher_int64 iValue){
63925   int rc;
63926   Vdbe *p = (Vdbe *)pStmt;
63927   rc = vdbeUnbind(p, i);
63928   if( rc==SQLCIPHER_OK ){
63929     sqlcipher3VdbeMemSetInt64(&p->aVar[i-1], iValue);
63930     sqlcipher3_mutex_leave(p->db->mutex);
63931   }
63932   return rc;
63933 }
63934 SQLCIPHER_API int sqlcipher3_bind_null(sqlcipher3_stmt *pStmt, int i){
63935   int rc;
63936   Vdbe *p = (Vdbe*)pStmt;
63937   rc = vdbeUnbind(p, i);
63938   if( rc==SQLCIPHER_OK ){
63939     sqlcipher3_mutex_leave(p->db->mutex);
63940   }
63941   return rc;
63942 }
63943 SQLCIPHER_API int sqlcipher3_bind_text( 
63944   sqlcipher3_stmt *pStmt, 
63945   int i, 
63946   const char *zData, 
63947   int nData, 
63948   void (*xDel)(void*)
63949 ){
63950   return bindText(pStmt, i, zData, nData, xDel, SQLCIPHER_UTF8);
63951 }
63952 #ifndef SQLCIPHER_OMIT_UTF16
63953 SQLCIPHER_API int sqlcipher3_bind_text16(
63954   sqlcipher3_stmt *pStmt, 
63955   int i, 
63956   const void *zData, 
63957   int nData, 
63958   void (*xDel)(void*)
63959 ){
63960   return bindText(pStmt, i, zData, nData, xDel, SQLCIPHER_UTF16NATIVE);
63961 }
63962 #endif /* SQLCIPHER_OMIT_UTF16 */
63963 SQLCIPHER_API int sqlcipher3_bind_value(sqlcipher3_stmt *pStmt, int i, const sqlcipher3_value *pValue){
63964   int rc;
63965   switch( pValue->type ){
63966     case SQLCIPHER_INTEGER: {
63967       rc = sqlcipher3_bind_int64(pStmt, i, pValue->u.i);
63968       break;
63969     }
63970     case SQLCIPHER_FLOAT: {
63971       rc = sqlcipher3_bind_double(pStmt, i, pValue->r);
63972       break;
63973     }
63974     case SQLCIPHER_BLOB: {
63975       if( pValue->flags & MEM_Zero ){
63976         rc = sqlcipher3_bind_zeroblob(pStmt, i, pValue->u.nZero);
63977       }else{
63978         rc = sqlcipher3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLCIPHER_TRANSIENT);
63979       }
63980       break;
63981     }
63982     case SQLCIPHER_TEXT: {
63983       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLCIPHER_TRANSIENT,
63984                               pValue->enc);
63985       break;
63986     }
63987     default: {
63988       rc = sqlcipher3_bind_null(pStmt, i);
63989       break;
63990     }
63991   }
63992   return rc;
63993 }
63994 SQLCIPHER_API int sqlcipher3_bind_zeroblob(sqlcipher3_stmt *pStmt, int i, int n){
63995   int rc;
63996   Vdbe *p = (Vdbe *)pStmt;
63997   rc = vdbeUnbind(p, i);
63998   if( rc==SQLCIPHER_OK ){
63999     sqlcipher3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
64000     sqlcipher3_mutex_leave(p->db->mutex);
64001   }
64002   return rc;
64003 }
64004
64005 /*
64006 ** Return the number of wildcards that can be potentially bound to.
64007 ** This routine is added to support DBD::SQLite.  
64008 */
64009 SQLCIPHER_API int sqlcipher3_bind_parameter_count(sqlcipher3_stmt *pStmt){
64010   Vdbe *p = (Vdbe*)pStmt;
64011   return p ? p->nVar : 0;
64012 }
64013
64014 /*
64015 ** Return the name of a wildcard parameter.  Return NULL if the index
64016 ** is out of range or if the wildcard is unnamed.
64017 **
64018 ** The result is always UTF-8.
64019 */
64020 SQLCIPHER_API const char *sqlcipher3_bind_parameter_name(sqlcipher3_stmt *pStmt, int i){
64021   Vdbe *p = (Vdbe*)pStmt;
64022   if( p==0 || i<1 || i>p->nzVar ){
64023     return 0;
64024   }
64025   return p->azVar[i-1];
64026 }
64027
64028 /*
64029 ** Given a wildcard parameter name, return the index of the variable
64030 ** with that name.  If there is no variable with the given name,
64031 ** return 0.
64032 */
64033 SQLCIPHER_PRIVATE int sqlcipher3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
64034   int i;
64035   if( p==0 ){
64036     return 0;
64037   }
64038   if( zName ){
64039     for(i=0; i<p->nzVar; i++){
64040       const char *z = p->azVar[i];
64041       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
64042         return i+1;
64043       }
64044     }
64045   }
64046   return 0;
64047 }
64048 SQLCIPHER_API int sqlcipher3_bind_parameter_index(sqlcipher3_stmt *pStmt, const char *zName){
64049   return sqlcipher3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlcipher3Strlen30(zName));
64050 }
64051
64052 /*
64053 ** Transfer all bindings from the first statement over to the second.
64054 */
64055 SQLCIPHER_PRIVATE int sqlcipher3TransferBindings(sqlcipher3_stmt *pFromStmt, sqlcipher3_stmt *pToStmt){
64056   Vdbe *pFrom = (Vdbe*)pFromStmt;
64057   Vdbe *pTo = (Vdbe*)pToStmt;
64058   int i;
64059   assert( pTo->db==pFrom->db );
64060   assert( pTo->nVar==pFrom->nVar );
64061   sqlcipher3_mutex_enter(pTo->db->mutex);
64062   for(i=0; i<pFrom->nVar; i++){
64063     sqlcipher3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
64064   }
64065   sqlcipher3_mutex_leave(pTo->db->mutex);
64066   return SQLCIPHER_OK;
64067 }
64068
64069 #ifndef SQLCIPHER_OMIT_DEPRECATED
64070 /*
64071 ** Deprecated external interface.  Internal/core SQLite code
64072 ** should call sqlcipher3TransferBindings.
64073 **
64074 ** Is is misuse to call this routine with statements from different
64075 ** database connections.  But as this is a deprecated interface, we
64076 ** will not bother to check for that condition.
64077 **
64078 ** If the two statements contain a different number of bindings, then
64079 ** an SQLCIPHER_ERROR is returned.  Nothing else can go wrong, so otherwise
64080 ** SQLCIPHER_OK is returned.
64081 */
64082 SQLCIPHER_API int sqlcipher3_transfer_bindings(sqlcipher3_stmt *pFromStmt, sqlcipher3_stmt *pToStmt){
64083   Vdbe *pFrom = (Vdbe*)pFromStmt;
64084   Vdbe *pTo = (Vdbe*)pToStmt;
64085   if( pFrom->nVar!=pTo->nVar ){
64086     return SQLCIPHER_ERROR;
64087   }
64088   if( pTo->isPrepareV2 && pTo->expmask ){
64089     pTo->expired = 1;
64090   }
64091   if( pFrom->isPrepareV2 && pFrom->expmask ){
64092     pFrom->expired = 1;
64093   }
64094   return sqlcipher3TransferBindings(pFromStmt, pToStmt);
64095 }
64096 #endif
64097
64098 /*
64099 ** Return the sqlcipher3* database handle to which the prepared statement given
64100 ** in the argument belongs.  This is the same database handle that was
64101 ** the first argument to the sqlcipher3_prepare() that was used to create
64102 ** the statement in the first place.
64103 */
64104 SQLCIPHER_API sqlcipher3 *sqlcipher3_db_handle(sqlcipher3_stmt *pStmt){
64105   return pStmt ? ((Vdbe*)pStmt)->db : 0;
64106 }
64107
64108 /*
64109 ** Return true if the prepared statement is guaranteed to not modify the
64110 ** database.
64111 */
64112 SQLCIPHER_API int sqlcipher3_stmt_readonly(sqlcipher3_stmt *pStmt){
64113   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
64114 }
64115
64116 /*
64117 ** Return a pointer to the next prepared statement after pStmt associated
64118 ** with database connection pDb.  If pStmt is NULL, return the first
64119 ** prepared statement for the database connection.  Return NULL if there
64120 ** are no more.
64121 */
64122 SQLCIPHER_API sqlcipher3_stmt *sqlcipher3_next_stmt(sqlcipher3 *pDb, sqlcipher3_stmt *pStmt){
64123   sqlcipher3_stmt *pNext;
64124   sqlcipher3_mutex_enter(pDb->mutex);
64125   if( pStmt==0 ){
64126     pNext = (sqlcipher3_stmt*)pDb->pVdbe;
64127   }else{
64128     pNext = (sqlcipher3_stmt*)((Vdbe*)pStmt)->pNext;
64129   }
64130   sqlcipher3_mutex_leave(pDb->mutex);
64131   return pNext;
64132 }
64133
64134 /*
64135 ** Return the value of a status counter for a prepared statement
64136 */
64137 SQLCIPHER_API int sqlcipher3_stmt_status(sqlcipher3_stmt *pStmt, int op, int resetFlag){
64138   Vdbe *pVdbe = (Vdbe*)pStmt;
64139   int v = pVdbe->aCounter[op-1];
64140   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
64141   return v;
64142 }
64143
64144 /************** End of vdbeapi.c *********************************************/
64145 /************** Begin file vdbetrace.c ***************************************/
64146 /*
64147 ** 2009 November 25
64148 **
64149 ** The author disclaims copyright to this source code.  In place of
64150 ** a legal notice, here is a blessing:
64151 **
64152 **    May you do good and not evil.
64153 **    May you find forgiveness for yourself and forgive others.
64154 **    May you share freely, never taking more than you give.
64155 **
64156 *************************************************************************
64157 **
64158 ** This file contains code used to insert the values of host parameters
64159 ** (aka "wildcards") into the SQL text output by sqlcipher3_trace().
64160 */
64161
64162 #ifndef SQLCIPHER_OMIT_TRACE
64163
64164 /*
64165 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
64166 ** bytes in this text up to but excluding the first character in
64167 ** a host parameter.  If the text contains no host parameters, return
64168 ** the total number of bytes in the text.
64169 */
64170 static int findNextHostParameter(const char *zSql, int *pnToken){
64171   int tokenType;
64172   int nTotal = 0;
64173   int n;
64174
64175   *pnToken = 0;
64176   while( zSql[0] ){
64177     n = sqlcipher3GetToken((u8*)zSql, &tokenType);
64178     assert( n>0 && tokenType!=TK_ILLEGAL );
64179     if( tokenType==TK_VARIABLE ){
64180       *pnToken = n;
64181       break;
64182     }
64183     nTotal += n;
64184     zSql += n;
64185   }
64186   return nTotal;
64187 }
64188
64189 /*
64190 ** This function returns a pointer to a nul-terminated string in memory
64191 ** obtained from sqlcipher3DbMalloc(). If sqlcipher3.vdbeExecCnt is 1, then the
64192 ** string contains a copy of zRawSql but with host parameters expanded to 
64193 ** their current bindings. Or, if sqlcipher3.vdbeExecCnt is greater than 1, 
64194 ** then the returned string holds a copy of zRawSql with "-- " prepended
64195 ** to each line of text.
64196 **
64197 ** The calling function is responsible for making sure the memory returned
64198 ** is eventually freed.
64199 **
64200 ** ALGORITHM:  Scan the input string looking for host parameters in any of
64201 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
64202 ** string literals, quoted identifier names, and comments.  For text forms,
64203 ** the host parameter index is found by scanning the perpared
64204 ** statement for the corresponding OP_Variable opcode.  Once the host
64205 ** parameter index is known, locate the value in p->aVar[].  Then render
64206 ** the value as a literal in place of the host parameter name.
64207 */
64208 SQLCIPHER_PRIVATE char *sqlcipher3VdbeExpandSql(
64209   Vdbe *p,                 /* The prepared statement being evaluated */
64210   const char *zRawSql      /* Raw text of the SQL statement */
64211 ){
64212   sqlcipher3 *db;             /* The database connection */
64213   int idx = 0;             /* Index of a host parameter */
64214   int nextIndex = 1;       /* Index of next ? host parameter */
64215   int n;                   /* Length of a token prefix */
64216   int nToken;              /* Length of the parameter token */
64217   int i;                   /* Loop counter */
64218   Mem *pVar;               /* Value of a host parameter */
64219   StrAccum out;            /* Accumulate the output here */
64220   char zBase[100];         /* Initial working space */
64221
64222   db = p->db;
64223   sqlcipher3StrAccumInit(&out, zBase, sizeof(zBase), 
64224                       db->aLimit[SQLCIPHER_LIMIT_LENGTH]);
64225   out.db = db;
64226   if( db->vdbeExecCnt>1 ){
64227     while( *zRawSql ){
64228       const char *zStart = zRawSql;
64229       while( *(zRawSql++)!='\n' && *zRawSql );
64230       sqlcipher3StrAccumAppend(&out, "-- ", 3);
64231       sqlcipher3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
64232     }
64233   }else{
64234     while( zRawSql[0] ){
64235       n = findNextHostParameter(zRawSql, &nToken);
64236       assert( n>0 );
64237       sqlcipher3StrAccumAppend(&out, zRawSql, n);
64238       zRawSql += n;
64239       assert( zRawSql[0] || nToken==0 );
64240       if( nToken==0 ) break;
64241       if( zRawSql[0]=='?' ){
64242         if( nToken>1 ){
64243           assert( sqlcipher3Isdigit(zRawSql[1]) );
64244           sqlcipher3GetInt32(&zRawSql[1], &idx);
64245         }else{
64246           idx = nextIndex;
64247         }
64248       }else{
64249         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
64250         testcase( zRawSql[0]==':' );
64251         testcase( zRawSql[0]=='$' );
64252         testcase( zRawSql[0]=='@' );
64253         idx = sqlcipher3VdbeParameterIndex(p, zRawSql, nToken);
64254         assert( idx>0 );
64255       }
64256       zRawSql += nToken;
64257       nextIndex = idx + 1;
64258       assert( idx>0 && idx<=p->nVar );
64259       pVar = &p->aVar[idx-1];
64260       if( pVar->flags & MEM_Null ){
64261         sqlcipher3StrAccumAppend(&out, "NULL", 4);
64262       }else if( pVar->flags & MEM_Int ){
64263         sqlcipher3XPrintf(&out, "%lld", pVar->u.i);
64264       }else if( pVar->flags & MEM_Real ){
64265         sqlcipher3XPrintf(&out, "%!.15g", pVar->r);
64266       }else if( pVar->flags & MEM_Str ){
64267 #ifndef SQLCIPHER_OMIT_UTF16
64268         u8 enc = ENC(db);
64269         if( enc!=SQLCIPHER_UTF8 ){
64270           Mem utf8;
64271           memset(&utf8, 0, sizeof(utf8));
64272           utf8.db = db;
64273           sqlcipher3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLCIPHER_STATIC);
64274           sqlcipher3VdbeChangeEncoding(&utf8, SQLCIPHER_UTF8);
64275           sqlcipher3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
64276           sqlcipher3VdbeMemRelease(&utf8);
64277         }else
64278 #endif
64279         {
64280           sqlcipher3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
64281         }
64282       }else if( pVar->flags & MEM_Zero ){
64283         sqlcipher3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
64284       }else{
64285         assert( pVar->flags & MEM_Blob );
64286         sqlcipher3StrAccumAppend(&out, "x'", 2);
64287         for(i=0; i<pVar->n; i++){
64288           sqlcipher3XPrintf(&out, "%02x", pVar->z[i]&0xff);
64289         }
64290         sqlcipher3StrAccumAppend(&out, "'", 1);
64291       }
64292     }
64293   }
64294   return sqlcipher3StrAccumFinish(&out);
64295 }
64296
64297 #endif /* #ifndef SQLCIPHER_OMIT_TRACE */
64298
64299 /************** End of vdbetrace.c *******************************************/
64300 /************** Begin file vdbe.c ********************************************/
64301 /*
64302 ** 2001 September 15
64303 **
64304 ** The author disclaims copyright to this source code.  In place of
64305 ** a legal notice, here is a blessing:
64306 **
64307 **    May you do good and not evil.
64308 **    May you find forgiveness for yourself and forgive others.
64309 **    May you share freely, never taking more than you give.
64310 **
64311 *************************************************************************
64312 ** The code in this file implements execution method of the 
64313 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
64314 ** handles housekeeping details such as creating and deleting
64315 ** VDBE instances.  This file is solely interested in executing
64316 ** the VDBE program.
64317 **
64318 ** In the external interface, an "sqlcipher3_stmt*" is an opaque pointer
64319 ** to a VDBE.
64320 **
64321 ** The SQL parser generates a program which is then executed by
64322 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
64323 ** similar in form to assembly language.  The program consists of
64324 ** a linear sequence of operations.  Each operation has an opcode 
64325 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
64326 ** is a null-terminated string.  Operand P5 is an unsigned character.
64327 ** Few opcodes use all 5 operands.
64328 **
64329 ** Computation results are stored on a set of registers numbered beginning
64330 ** with 1 and going up to Vdbe.nMem.  Each register can store
64331 ** either an integer, a null-terminated string, a floating point
64332 ** number, or the SQL "NULL" value.  An implicit conversion from one
64333 ** type to the other occurs as necessary.
64334 ** 
64335 ** Most of the code in this file is taken up by the sqlcipher3VdbeExec()
64336 ** function which does the work of interpreting a VDBE program.
64337 ** But other routines are also provided to help in building up
64338 ** a program instruction by instruction.
64339 **
64340 ** Various scripts scan this source file in order to generate HTML
64341 ** documentation, headers files, or other derived files.  The formatting
64342 ** of the code in this file is, therefore, important.  See other comments
64343 ** in this file for details.  If in doubt, do not deviate from existing
64344 ** commenting and indentation practices when changing or adding code.
64345 */
64346
64347 /*
64348 ** Invoke this macro on memory cells just prior to changing the
64349 ** value of the cell.  This macro verifies that shallow copies are
64350 ** not misused.
64351 */
64352 #ifdef SQLCIPHER_DEBUG
64353 # define memAboutToChange(P,M) sqlcipher3VdbeMemPrepareToChange(P,M)
64354 #else
64355 # define memAboutToChange(P,M)
64356 #endif
64357
64358 /*
64359 ** The following global variable is incremented every time a cursor
64360 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
64361 ** procedures use this information to make sure that indices are
64362 ** working correctly.  This variable has no function other than to
64363 ** help verify the correct operation of the library.
64364 */
64365 #ifdef SQLCIPHER_TEST
64366 SQLCIPHER_API int sqlcipher3_search_count = 0;
64367 #endif
64368
64369 /*
64370 ** When this global variable is positive, it gets decremented once before
64371 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
64372 ** field of the sqlcipher3 structure is set in order to simulate and interrupt.
64373 **
64374 ** This facility is used for testing purposes only.  It does not function
64375 ** in an ordinary build.
64376 */
64377 #ifdef SQLCIPHER_TEST
64378 SQLCIPHER_API int sqlcipher3_interrupt_count = 0;
64379 #endif
64380
64381 /*
64382 ** The next global variable is incremented each type the OP_Sort opcode
64383 ** is executed.  The test procedures use this information to make sure that
64384 ** sorting is occurring or not occurring at appropriate times.   This variable
64385 ** has no function other than to help verify the correct operation of the
64386 ** library.
64387 */
64388 #ifdef SQLCIPHER_TEST
64389 SQLCIPHER_API int sqlcipher3_sort_count = 0;
64390 #endif
64391
64392 /*
64393 ** The next global variable records the size of the largest MEM_Blob
64394 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
64395 ** use this information to make sure that the zero-blob functionality
64396 ** is working correctly.   This variable has no function other than to
64397 ** help verify the correct operation of the library.
64398 */
64399 #ifdef SQLCIPHER_TEST
64400 SQLCIPHER_API int sqlcipher3_max_blobsize = 0;
64401 static void updateMaxBlobsize(Mem *p){
64402   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlcipher3_max_blobsize ){
64403     sqlcipher3_max_blobsize = p->n;
64404   }
64405 }
64406 #endif
64407
64408 /*
64409 ** The next global variable is incremented each type the OP_Found opcode
64410 ** is executed. This is used to test whether or not the foreign key
64411 ** operation implemented using OP_FkIsZero is working. This variable
64412 ** has no function other than to help verify the correct operation of the
64413 ** library.
64414 */
64415 #ifdef SQLCIPHER_TEST
64416 SQLCIPHER_API int sqlcipher3_found_count = 0;
64417 #endif
64418
64419 /*
64420 ** Test a register to see if it exceeds the current maximum blob size.
64421 ** If it does, record the new maximum blob size.
64422 */
64423 #if defined(SQLCIPHER_TEST) && !defined(SQLCIPHER_OMIT_BUILTIN_TEST)
64424 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
64425 #else
64426 # define UPDATE_MAX_BLOBSIZE(P)
64427 #endif
64428
64429 /*
64430 ** Convert the given register into a string if it isn't one
64431 ** already. Return non-zero if a malloc() fails.
64432 */
64433 #define Stringify(P, enc) \
64434    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlcipher3VdbeMemStringify(P,enc)) \
64435      { goto no_mem; }
64436
64437 /*
64438 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
64439 ** a pointer to a dynamically allocated string where some other entity
64440 ** is responsible for deallocating that string.  Because the register
64441 ** does not control the string, it might be deleted without the register
64442 ** knowing it.
64443 **
64444 ** This routine converts an ephemeral string into a dynamically allocated
64445 ** string that the register itself controls.  In other words, it
64446 ** converts an MEM_Ephem string into an MEM_Dyn string.
64447 */
64448 #define Deephemeralize(P) \
64449    if( ((P)->flags&MEM_Ephem)!=0 \
64450        && sqlcipher3VdbeMemMakeWriteable(P) ){ goto no_mem;}
64451
64452 /*
64453 ** Call sqlcipher3VdbeMemExpandBlob() on the supplied value (type Mem*)
64454 ** P if required.
64455 */
64456 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlcipher3VdbeMemExpandBlob(P):0)
64457
64458 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
64459 #ifdef SQLCIPHER_OMIT_MERGE_SORT
64460 # define isSorter(x) 0
64461 #else
64462 # define isSorter(x) ((x)->pSorter!=0)
64463 #endif
64464
64465 /*
64466 ** Argument pMem points at a register that will be passed to a
64467 ** user-defined function or returned to the user as the result of a query.
64468 ** This routine sets the pMem->type variable used by the sqlcipher3_value_*() 
64469 ** routines.
64470 */
64471 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemStoreType(Mem *pMem){
64472   int flags = pMem->flags;
64473   if( flags & MEM_Null ){
64474     pMem->type = SQLCIPHER_NULL;
64475   }
64476   else if( flags & MEM_Int ){
64477     pMem->type = SQLCIPHER_INTEGER;
64478   }
64479   else if( flags & MEM_Real ){
64480     pMem->type = SQLCIPHER_FLOAT;
64481   }
64482   else if( flags & MEM_Str ){
64483     pMem->type = SQLCIPHER_TEXT;
64484   }else{
64485     pMem->type = SQLCIPHER_BLOB;
64486   }
64487 }
64488
64489 /*
64490 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
64491 ** if we run out of memory.
64492 */
64493 static VdbeCursor *allocateCursor(
64494   Vdbe *p,              /* The virtual machine */
64495   int iCur,             /* Index of the new VdbeCursor */
64496   int nField,           /* Number of fields in the table or index */
64497   int iDb,              /* When database the cursor belongs to, or -1 */
64498   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
64499 ){
64500   /* Find the memory cell that will be used to store the blob of memory
64501   ** required for this VdbeCursor structure. It is convenient to use a 
64502   ** vdbe memory cell to manage the memory allocation required for a
64503   ** VdbeCursor structure for the following reasons:
64504   **
64505   **   * Sometimes cursor numbers are used for a couple of different
64506   **     purposes in a vdbe program. The different uses might require
64507   **     different sized allocations. Memory cells provide growable
64508   **     allocations.
64509   **
64510   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
64511   **     be freed lazily via the sqlcipher3_release_memory() API. This
64512   **     minimizes the number of malloc calls made by the system.
64513   **
64514   ** Memory cells for cursors are allocated at the top of the address
64515   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
64516   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
64517   */
64518   Mem *pMem = &p->aMem[p->nMem-iCur];
64519
64520   int nByte;
64521   VdbeCursor *pCx = 0;
64522   nByte = 
64523       ROUND8(sizeof(VdbeCursor)) + 
64524       (isBtreeCursor?sqlcipher3BtreeCursorSize():0) + 
64525       2*nField*sizeof(u32);
64526
64527   assert( iCur<p->nCursor );
64528   if( p->apCsr[iCur] ){
64529     sqlcipher3VdbeFreeCursor(p, p->apCsr[iCur]);
64530     p->apCsr[iCur] = 0;
64531   }
64532   if( SQLCIPHER_OK==sqlcipher3VdbeMemGrow(pMem, nByte, 0) ){
64533     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
64534     memset(pCx, 0, sizeof(VdbeCursor));
64535     pCx->iDb = iDb;
64536     pCx->nField = nField;
64537     if( nField ){
64538       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
64539     }
64540     if( isBtreeCursor ){
64541       pCx->pCursor = (BtCursor*)
64542           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
64543       sqlcipher3BtreeCursorZero(pCx->pCursor);
64544     }
64545   }
64546   return pCx;
64547 }
64548
64549 /*
64550 ** Try to convert a value into a numeric representation if we can
64551 ** do so without loss of information.  In other words, if the string
64552 ** looks like a number, convert it into a number.  If it does not
64553 ** look like a number, leave it alone.
64554 */
64555 static void applyNumericAffinity(Mem *pRec){
64556   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
64557     double rValue;
64558     i64 iValue;
64559     u8 enc = pRec->enc;
64560     if( (pRec->flags&MEM_Str)==0 ) return;
64561     if( sqlcipher3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
64562     if( 0==sqlcipher3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
64563       pRec->u.i = iValue;
64564       pRec->flags |= MEM_Int;
64565     }else{
64566       pRec->r = rValue;
64567       pRec->flags |= MEM_Real;
64568     }
64569   }
64570 }
64571
64572 /*
64573 ** Processing is determine by the affinity parameter:
64574 **
64575 ** SQLCIPHER_AFF_INTEGER:
64576 ** SQLCIPHER_AFF_REAL:
64577 ** SQLCIPHER_AFF_NUMERIC:
64578 **    Try to convert pRec to an integer representation or a 
64579 **    floating-point representation if an integer representation
64580 **    is not possible.  Note that the integer representation is
64581 **    always preferred, even if the affinity is REAL, because
64582 **    an integer representation is more space efficient on disk.
64583 **
64584 ** SQLCIPHER_AFF_TEXT:
64585 **    Convert pRec to a text representation.
64586 **
64587 ** SQLCIPHER_AFF_NONE:
64588 **    No-op.  pRec is unchanged.
64589 */
64590 static void applyAffinity(
64591   Mem *pRec,          /* The value to apply affinity to */
64592   char affinity,      /* The affinity to be applied */
64593   u8 enc              /* Use this text encoding */
64594 ){
64595   if( affinity==SQLCIPHER_AFF_TEXT ){
64596     /* Only attempt the conversion to TEXT if there is an integer or real
64597     ** representation (blob and NULL do not get converted) but no string
64598     ** representation.
64599     */
64600     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
64601       sqlcipher3VdbeMemStringify(pRec, enc);
64602     }
64603     pRec->flags &= ~(MEM_Real|MEM_Int);
64604   }else if( affinity!=SQLCIPHER_AFF_NONE ){
64605     assert( affinity==SQLCIPHER_AFF_INTEGER || affinity==SQLCIPHER_AFF_REAL
64606              || affinity==SQLCIPHER_AFF_NUMERIC );
64607     applyNumericAffinity(pRec);
64608     if( pRec->flags & MEM_Real ){
64609       sqlcipher3VdbeIntegerAffinity(pRec);
64610     }
64611   }
64612 }
64613
64614 /*
64615 ** Try to convert the type of a function argument or a result column
64616 ** into a numeric representation.  Use either INTEGER or REAL whichever
64617 ** is appropriate.  But only do the conversion if it is possible without
64618 ** loss of information and return the revised type of the argument.
64619 */
64620 SQLCIPHER_API int sqlcipher3_value_numeric_type(sqlcipher3_value *pVal){
64621   Mem *pMem = (Mem*)pVal;
64622   if( pMem->type==SQLCIPHER_TEXT ){
64623     applyNumericAffinity(pMem);
64624     sqlcipher3VdbeMemStoreType(pMem);
64625   }
64626   return pMem->type;
64627 }
64628
64629 /*
64630 ** Exported version of applyAffinity(). This one works on sqlcipher3_value*, 
64631 ** not the internal Mem* type.
64632 */
64633 SQLCIPHER_PRIVATE void sqlcipher3ValueApplyAffinity(
64634   sqlcipher3_value *pVal, 
64635   u8 affinity, 
64636   u8 enc
64637 ){
64638   applyAffinity((Mem *)pVal, affinity, enc);
64639 }
64640
64641 #ifdef SQLCIPHER_DEBUG
64642 /*
64643 ** Write a nice string representation of the contents of cell pMem
64644 ** into buffer zBuf, length nBuf.
64645 */
64646 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
64647   char *zCsr = zBuf;
64648   int f = pMem->flags;
64649
64650   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
64651
64652   if( f&MEM_Blob ){
64653     int i;
64654     char c;
64655     if( f & MEM_Dyn ){
64656       c = 'z';
64657       assert( (f & (MEM_Static|MEM_Ephem))==0 );
64658     }else if( f & MEM_Static ){
64659       c = 't';
64660       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
64661     }else if( f & MEM_Ephem ){
64662       c = 'e';
64663       assert( (f & (MEM_Static|MEM_Dyn))==0 );
64664     }else{
64665       c = 's';
64666     }
64667
64668     sqlcipher3_snprintf(100, zCsr, "%c", c);
64669     zCsr += sqlcipher3Strlen30(zCsr);
64670     sqlcipher3_snprintf(100, zCsr, "%d[", pMem->n);
64671     zCsr += sqlcipher3Strlen30(zCsr);
64672     for(i=0; i<16 && i<pMem->n; i++){
64673       sqlcipher3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
64674       zCsr += sqlcipher3Strlen30(zCsr);
64675     }
64676     for(i=0; i<16 && i<pMem->n; i++){
64677       char z = pMem->z[i];
64678       if( z<32 || z>126 ) *zCsr++ = '.';
64679       else *zCsr++ = z;
64680     }
64681
64682     sqlcipher3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
64683     zCsr += sqlcipher3Strlen30(zCsr);
64684     if( f & MEM_Zero ){
64685       sqlcipher3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
64686       zCsr += sqlcipher3Strlen30(zCsr);
64687     }
64688     *zCsr = '\0';
64689   }else if( f & MEM_Str ){
64690     int j, k;
64691     zBuf[0] = ' ';
64692     if( f & MEM_Dyn ){
64693       zBuf[1] = 'z';
64694       assert( (f & (MEM_Static|MEM_Ephem))==0 );
64695     }else if( f & MEM_Static ){
64696       zBuf[1] = 't';
64697       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
64698     }else if( f & MEM_Ephem ){
64699       zBuf[1] = 'e';
64700       assert( (f & (MEM_Static|MEM_Dyn))==0 );
64701     }else{
64702       zBuf[1] = 's';
64703     }
64704     k = 2;
64705     sqlcipher3_snprintf(100, &zBuf[k], "%d", pMem->n);
64706     k += sqlcipher3Strlen30(&zBuf[k]);
64707     zBuf[k++] = '[';
64708     for(j=0; j<15 && j<pMem->n; j++){
64709       u8 c = pMem->z[j];
64710       if( c>=0x20 && c<0x7f ){
64711         zBuf[k++] = c;
64712       }else{
64713         zBuf[k++] = '.';
64714       }
64715     }
64716     zBuf[k++] = ']';
64717     sqlcipher3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
64718     k += sqlcipher3Strlen30(&zBuf[k]);
64719     zBuf[k++] = 0;
64720   }
64721 }
64722 #endif
64723
64724 #ifdef SQLCIPHER_DEBUG
64725 /*
64726 ** Print the value of a register for tracing purposes:
64727 */
64728 static void memTracePrint(FILE *out, Mem *p){
64729   if( p->flags & MEM_Null ){
64730     fprintf(out, " NULL");
64731   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
64732     fprintf(out, " si:%lld", p->u.i);
64733   }else if( p->flags & MEM_Int ){
64734     fprintf(out, " i:%lld", p->u.i);
64735 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
64736   }else if( p->flags & MEM_Real ){
64737     fprintf(out, " r:%g", p->r);
64738 #endif
64739   }else if( p->flags & MEM_RowSet ){
64740     fprintf(out, " (rowset)");
64741   }else{
64742     char zBuf[200];
64743     sqlcipher3VdbeMemPrettyPrint(p, zBuf);
64744     fprintf(out, " ");
64745     fprintf(out, "%s", zBuf);
64746   }
64747 }
64748 static void registerTrace(FILE *out, int iReg, Mem *p){
64749   fprintf(out, "REG[%d] = ", iReg);
64750   memTracePrint(out, p);
64751   fprintf(out, "\n");
64752 }
64753 #endif
64754
64755 #ifdef SQLCIPHER_DEBUG
64756 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
64757 #else
64758 #  define REGISTER_TRACE(R,M)
64759 #endif
64760
64761
64762 #ifdef VDBE_PROFILE
64763
64764 /* 
64765 ** hwtime.h contains inline assembler code for implementing 
64766 ** high-performance timing routines.
64767 */
64768 /************** Include hwtime.h in the middle of vdbe.c *********************/
64769 /************** Begin file hwtime.h ******************************************/
64770 /*
64771 ** 2008 May 27
64772 **
64773 ** The author disclaims copyright to this source code.  In place of
64774 ** a legal notice, here is a blessing:
64775 **
64776 **    May you do good and not evil.
64777 **    May you find forgiveness for yourself and forgive others.
64778 **    May you share freely, never taking more than you give.
64779 **
64780 ******************************************************************************
64781 **
64782 ** This file contains inline asm code for retrieving "high-performance"
64783 ** counters for x86 class CPUs.
64784 */
64785 #ifndef _HWTIME_H_
64786 #define _HWTIME_H_
64787
64788 /*
64789 ** The following routine only works on pentium-class (or newer) processors.
64790 ** It uses the RDTSC opcode to read the cycle count value out of the
64791 ** processor and returns that value.  This can be used for high-res
64792 ** profiling.
64793 */
64794 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
64795       (defined(i386) || defined(__i386__) || defined(_M_IX86))
64796
64797   #if defined(__GNUC__)
64798
64799   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
64800      unsigned int lo, hi;
64801      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
64802      return (sqlcipher_uint64)hi << 32 | lo;
64803   }
64804
64805   #elif defined(_MSC_VER)
64806
64807   __declspec(naked) __inline sqlcipher_uint64 __cdecl sqlcipher3Hwtime(void){
64808      __asm {
64809         rdtsc
64810         ret       ; return value at EDX:EAX
64811      }
64812   }
64813
64814   #endif
64815
64816 #elif (defined(__GNUC__) && defined(__x86_64__))
64817
64818   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
64819       unsigned long val;
64820       __asm__ __volatile__ ("rdtsc" : "=A" (val));
64821       return val;
64822   }
64823  
64824 #elif (defined(__GNUC__) && defined(__ppc__))
64825
64826   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
64827       unsigned long long retval;
64828       unsigned long junk;
64829       __asm__ __volatile__ ("\n\
64830           1:      mftbu   %1\n\
64831                   mftb    %L0\n\
64832                   mftbu   %0\n\
64833                   cmpw    %0,%1\n\
64834                   bne     1b"
64835                   : "=r" (retval), "=r" (junk));
64836       return retval;
64837   }
64838
64839 #else
64840
64841   #error Need implementation of sqlcipher3Hwtime() for your platform.
64842
64843   /*
64844   ** To compile without implementing sqlcipher3Hwtime() for your platform,
64845   ** you can remove the above #error and use the following
64846   ** stub function.  You will lose timing support for many
64847   ** of the debugging and testing utilities, but it should at
64848   ** least compile and run.
64849   */
64850 SQLCIPHER_PRIVATE   sqlcipher_uint64 sqlcipher3Hwtime(void){ return ((sqlcipher_uint64)0); }
64851
64852 #endif
64853
64854 #endif /* !defined(_HWTIME_H_) */
64855
64856 /************** End of hwtime.h **********************************************/
64857 /************** Continuing where we left off in vdbe.c ***********************/
64858
64859 #endif
64860
64861 /*
64862 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
64863 ** sqlcipher3_interrupt() routine has been called.  If it has been, then
64864 ** processing of the VDBE program is interrupted.
64865 **
64866 ** This macro added to every instruction that does a jump in order to
64867 ** implement a loop.  This test used to be on every single instruction,
64868 ** but that meant we more testing that we needed.  By only testing the
64869 ** flag on jump instructions, we get a (small) speed improvement.
64870 */
64871 #define CHECK_FOR_INTERRUPT \
64872    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
64873
64874
64875 #ifndef NDEBUG
64876 /*
64877 ** This function is only called from within an assert() expression. It
64878 ** checks that the sqlcipher3.nTransaction variable is correctly set to
64879 ** the number of non-transaction savepoints currently in the 
64880 ** linked list starting at sqlcipher3.pSavepoint.
64881 ** 
64882 ** Usage:
64883 **
64884 **     assert( checkSavepointCount(db) );
64885 */
64886 static int checkSavepointCount(sqlcipher3 *db){
64887   int n = 0;
64888   Savepoint *p;
64889   for(p=db->pSavepoint; p; p=p->pNext) n++;
64890   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
64891   return 1;
64892 }
64893 #endif
64894
64895 /*
64896 ** Transfer error message text from an sqlcipher3_vtab.zErrMsg (text stored
64897 ** in memory obtained from sqlcipher3_malloc) into a Vdbe.zErrMsg (text stored
64898 ** in memory obtained from sqlcipher3DbMalloc).
64899 */
64900 static void importVtabErrMsg(Vdbe *p, sqlcipher3_vtab *pVtab){
64901   sqlcipher3 *db = p->db;
64902   sqlcipher3DbFree(db, p->zErrMsg);
64903   p->zErrMsg = sqlcipher3DbStrDup(db, pVtab->zErrMsg);
64904   sqlcipher3_free(pVtab->zErrMsg);
64905   pVtab->zErrMsg = 0;
64906 }
64907
64908
64909 /*
64910 ** Execute as much of a VDBE program as we can then return.
64911 **
64912 ** sqlcipher3VdbeMakeReady() must be called before this routine in order to
64913 ** close the program with a final OP_Halt and to set up the callbacks
64914 ** and the error message pointer.
64915 **
64916 ** Whenever a row or result data is available, this routine will either
64917 ** invoke the result callback (if there is one) or return with
64918 ** SQLCIPHER_ROW.
64919 **
64920 ** If an attempt is made to open a locked database, then this routine
64921 ** will either invoke the busy callback (if there is one) or it will
64922 ** return SQLCIPHER_BUSY.
64923 **
64924 ** If an error occurs, an error message is written to memory obtained
64925 ** from sqlcipher3_malloc() and p->zErrMsg is made to point to that memory.
64926 ** The error code is stored in p->rc and this routine returns SQLCIPHER_ERROR.
64927 **
64928 ** If the callback ever returns non-zero, then the program exits
64929 ** immediately.  There will be no error message but the p->rc field is
64930 ** set to SQLCIPHER_ABORT and this routine will return SQLCIPHER_ERROR.
64931 **
64932 ** A memory allocation error causes p->rc to be set to SQLCIPHER_NOMEM and this
64933 ** routine to return SQLCIPHER_ERROR.
64934 **
64935 ** Other fatal errors return SQLCIPHER_ERROR.
64936 **
64937 ** After this routine has finished, sqlcipher3VdbeFinalize() should be
64938 ** used to clean up the mess that was left behind.
64939 */
64940 SQLCIPHER_PRIVATE int sqlcipher3VdbeExec(
64941   Vdbe *p                    /* The VDBE */
64942 ){
64943   int pc=0;                  /* The program counter */
64944   Op *aOp = p->aOp;          /* Copy of p->aOp */
64945   Op *pOp;                   /* Current operation */
64946   int rc = SQLCIPHER_OK;        /* Value to return */
64947   sqlcipher3 *db = p->db;       /* The database */
64948   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
64949   u8 encoding = ENC(db);     /* The database encoding */
64950 #ifndef SQLCIPHER_OMIT_PROGRESS_CALLBACK
64951   int checkProgress;         /* True if progress callbacks are enabled */
64952   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
64953 #endif
64954   Mem *aMem = p->aMem;       /* Copy of p->aMem */
64955   Mem *pIn1 = 0;             /* 1st input operand */
64956   Mem *pIn2 = 0;             /* 2nd input operand */
64957   Mem *pIn3 = 0;             /* 3rd input operand */
64958   Mem *pOut = 0;             /* Output operand */
64959   int iCompare = 0;          /* Result of last OP_Compare operation */
64960   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
64961   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
64962 #ifdef VDBE_PROFILE
64963   u64 start;                 /* CPU clock count at start of opcode */
64964   int origPc;                /* Program counter at start of opcode */
64965 #endif
64966   /********************************************************************
64967   ** Automatically generated code
64968   **
64969   ** The following union is automatically generated by the
64970   ** vdbe-compress.tcl script.  The purpose of this union is to
64971   ** reduce the amount of stack space required by this function.
64972   ** See comments in the vdbe-compress.tcl script for details.
64973   */
64974   union vdbeExecUnion {
64975     struct OP_Yield_stack_vars {
64976       int pcDest;
64977     } aa;
64978     struct OP_Variable_stack_vars {
64979       Mem *pVar;       /* Value being transferred */
64980     } ab;
64981     struct OP_Move_stack_vars {
64982       char *zMalloc;   /* Holding variable for allocated memory */
64983       int n;           /* Number of registers left to copy */
64984       int p1;          /* Register to copy from */
64985       int p2;          /* Register to copy to */
64986     } ac;
64987     struct OP_ResultRow_stack_vars {
64988       Mem *pMem;
64989       int i;
64990     } ad;
64991     struct OP_Concat_stack_vars {
64992       i64 nByte;
64993     } ae;
64994     struct OP_Remainder_stack_vars {
64995       int flags;      /* Combined MEM_* flags from both inputs */
64996       i64 iA;         /* Integer value of left operand */
64997       i64 iB;         /* Integer value of right operand */
64998       double rA;      /* Real value of left operand */
64999       double rB;      /* Real value of right operand */
65000     } af;
65001     struct OP_Function_stack_vars {
65002       int i;
65003       Mem *pArg;
65004       sqlcipher3_context ctx;
65005       sqlcipher3_value **apVal;
65006       int n;
65007     } ag;
65008     struct OP_ShiftRight_stack_vars {
65009       i64 iA;
65010       u64 uA;
65011       i64 iB;
65012       u8 op;
65013     } ah;
65014     struct OP_Ge_stack_vars {
65015       int res;            /* Result of the comparison of pIn1 against pIn3 */
65016       char affinity;      /* Affinity to use for comparison */
65017       u16 flags1;         /* Copy of initial value of pIn1->flags */
65018       u16 flags3;         /* Copy of initial value of pIn3->flags */
65019     } ai;
65020     struct OP_Compare_stack_vars {
65021       int n;
65022       int i;
65023       int p1;
65024       int p2;
65025       const KeyInfo *pKeyInfo;
65026       int idx;
65027       CollSeq *pColl;    /* Collating sequence to use on this term */
65028       int bRev;          /* True for DESCENDING sort order */
65029     } aj;
65030     struct OP_Or_stack_vars {
65031       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65032       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65033     } ak;
65034     struct OP_IfNot_stack_vars {
65035       int c;
65036     } al;
65037     struct OP_Column_stack_vars {
65038       u32 payloadSize;   /* Number of bytes in the record */
65039       i64 payloadSize64; /* Number of bytes in the record */
65040       int p1;            /* P1 value of the opcode */
65041       int p2;            /* column number to retrieve */
65042       VdbeCursor *pC;    /* The VDBE cursor */
65043       char *zRec;        /* Pointer to complete record-data */
65044       BtCursor *pCrsr;   /* The BTree cursor */
65045       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
65046       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
65047       int nField;        /* number of fields in the record */
65048       int len;           /* The length of the serialized data for the column */
65049       int i;             /* Loop counter */
65050       char *zData;       /* Part of the record being decoded */
65051       Mem *pDest;        /* Where to write the extracted value */
65052       Mem sMem;          /* For storing the record being decoded */
65053       u8 *zIdx;          /* Index into header */
65054       u8 *zEndHdr;       /* Pointer to first byte after the header */
65055       u32 offset;        /* Offset into the data */
65056       u32 szField;       /* Number of bytes in the content of a field */
65057       int szHdr;         /* Size of the header size field at start of record */
65058       int avail;         /* Number of bytes of available data */
65059       u32 t;             /* A type code from the record header */
65060       Mem *pReg;         /* PseudoTable input register */
65061     } am;
65062     struct OP_Affinity_stack_vars {
65063       const char *zAffinity;   /* The affinity to be applied */
65064       char cAff;               /* A single character of affinity */
65065     } an;
65066     struct OP_MakeRecord_stack_vars {
65067       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
65068       Mem *pRec;             /* The new record */
65069       u64 nData;             /* Number of bytes of data space */
65070       int nHdr;              /* Number of bytes of header space */
65071       i64 nByte;             /* Data space required for this record */
65072       int nZero;             /* Number of zero bytes at the end of the record */
65073       int nVarint;           /* Number of bytes in a varint */
65074       u32 serial_type;       /* Type field */
65075       Mem *pData0;           /* First field to be combined into the record */
65076       Mem *pLast;            /* Last field of the record */
65077       int nField;            /* Number of fields in the record */
65078       char *zAffinity;       /* The affinity string for the record */
65079       int file_format;       /* File format to use for encoding */
65080       int i;                 /* Space used in zNewRecord[] */
65081       int len;               /* Length of a field */
65082     } ao;
65083     struct OP_Count_stack_vars {
65084       i64 nEntry;
65085       BtCursor *pCrsr;
65086     } ap;
65087     struct OP_Savepoint_stack_vars {
65088       int p1;                         /* Value of P1 operand */
65089       char *zName;                    /* Name of savepoint */
65090       int nName;
65091       Savepoint *pNew;
65092       Savepoint *pSavepoint;
65093       Savepoint *pTmp;
65094       int iSavepoint;
65095       int ii;
65096     } aq;
65097     struct OP_AutoCommit_stack_vars {
65098       int desiredAutoCommit;
65099       int iRollback;
65100       int turnOnAC;
65101     } ar;
65102     struct OP_Transaction_stack_vars {
65103       Btree *pBt;
65104     } as;
65105     struct OP_ReadCookie_stack_vars {
65106       int iMeta;
65107       int iDb;
65108       int iCookie;
65109     } at;
65110     struct OP_SetCookie_stack_vars {
65111       Db *pDb;
65112     } au;
65113     struct OP_VerifyCookie_stack_vars {
65114       int iMeta;
65115       int iGen;
65116       Btree *pBt;
65117     } av;
65118     struct OP_OpenWrite_stack_vars {
65119       int nField;
65120       KeyInfo *pKeyInfo;
65121       int p2;
65122       int iDb;
65123       int wrFlag;
65124       Btree *pX;
65125       VdbeCursor *pCur;
65126       Db *pDb;
65127     } aw;
65128     struct OP_OpenEphemeral_stack_vars {
65129       VdbeCursor *pCx;
65130     } ax;
65131     struct OP_SorterOpen_stack_vars {
65132       VdbeCursor *pCx;
65133     } ay;
65134     struct OP_OpenPseudo_stack_vars {
65135       VdbeCursor *pCx;
65136     } az;
65137     struct OP_SeekGt_stack_vars {
65138       int res;
65139       int oc;
65140       VdbeCursor *pC;
65141       UnpackedRecord r;
65142       int nField;
65143       i64 iKey;      /* The rowid we are to seek to */
65144     } ba;
65145     struct OP_Seek_stack_vars {
65146       VdbeCursor *pC;
65147     } bb;
65148     struct OP_Found_stack_vars {
65149       int alreadyExists;
65150       VdbeCursor *pC;
65151       int res;
65152       char *pFree;
65153       UnpackedRecord *pIdxKey;
65154       UnpackedRecord r;
65155       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
65156     } bc;
65157     struct OP_IsUnique_stack_vars {
65158       u16 ii;
65159       VdbeCursor *pCx;
65160       BtCursor *pCrsr;
65161       u16 nField;
65162       Mem *aMx;
65163       UnpackedRecord r;                  /* B-Tree index search key */
65164       i64 R;                             /* Rowid stored in register P3 */
65165     } bd;
65166     struct OP_NotExists_stack_vars {
65167       VdbeCursor *pC;
65168       BtCursor *pCrsr;
65169       int res;
65170       u64 iKey;
65171     } be;
65172     struct OP_NewRowid_stack_vars {
65173       i64 v;                 /* The new rowid */
65174       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
65175       int res;               /* Result of an sqlcipher3BtreeLast() */
65176       int cnt;               /* Counter to limit the number of searches */
65177       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
65178       VdbeFrame *pFrame;     /* Root frame of VDBE */
65179     } bf;
65180     struct OP_InsertInt_stack_vars {
65181       Mem *pData;       /* MEM cell holding data for the record to be inserted */
65182       Mem *pKey;        /* MEM cell holding key  for the record */
65183       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
65184       VdbeCursor *pC;   /* Cursor to table into which insert is written */
65185       int nZero;        /* Number of zero-bytes to append */
65186       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
65187       const char *zDb;  /* database name - used by the update hook */
65188       const char *zTbl; /* Table name - used by the opdate hook */
65189       int op;           /* Opcode for update hook: SQLCIPHER_UPDATE or SQLCIPHER_INSERT */
65190     } bg;
65191     struct OP_Delete_stack_vars {
65192       i64 iKey;
65193       VdbeCursor *pC;
65194     } bh;
65195     struct OP_SorterCompare_stack_vars {
65196       VdbeCursor *pC;
65197       int res;
65198     } bi;
65199     struct OP_SorterData_stack_vars {
65200       VdbeCursor *pC;
65201     } bj;
65202     struct OP_RowData_stack_vars {
65203       VdbeCursor *pC;
65204       BtCursor *pCrsr;
65205       u32 n;
65206       i64 n64;
65207     } bk;
65208     struct OP_Rowid_stack_vars {
65209       VdbeCursor *pC;
65210       i64 v;
65211       sqlcipher3_vtab *pVtab;
65212       const sqlcipher3_module *pModule;
65213     } bl;
65214     struct OP_NullRow_stack_vars {
65215       VdbeCursor *pC;
65216     } bm;
65217     struct OP_Last_stack_vars {
65218       VdbeCursor *pC;
65219       BtCursor *pCrsr;
65220       int res;
65221     } bn;
65222     struct OP_Rewind_stack_vars {
65223       VdbeCursor *pC;
65224       BtCursor *pCrsr;
65225       int res;
65226     } bo;
65227     struct OP_Next_stack_vars {
65228       VdbeCursor *pC;
65229       int res;
65230     } bp;
65231     struct OP_IdxInsert_stack_vars {
65232       VdbeCursor *pC;
65233       BtCursor *pCrsr;
65234       int nKey;
65235       const char *zKey;
65236     } bq;
65237     struct OP_IdxDelete_stack_vars {
65238       VdbeCursor *pC;
65239       BtCursor *pCrsr;
65240       int res;
65241       UnpackedRecord r;
65242     } br;
65243     struct OP_IdxRowid_stack_vars {
65244       BtCursor *pCrsr;
65245       VdbeCursor *pC;
65246       i64 rowid;
65247     } bs;
65248     struct OP_IdxGE_stack_vars {
65249       VdbeCursor *pC;
65250       int res;
65251       UnpackedRecord r;
65252     } bt;
65253     struct OP_Destroy_stack_vars {
65254       int iMoved;
65255       int iCnt;
65256       Vdbe *pVdbe;
65257       int iDb;
65258     } bu;
65259     struct OP_Clear_stack_vars {
65260       int nChange;
65261     } bv;
65262     struct OP_CreateTable_stack_vars {
65263       int pgno;
65264       int flags;
65265       Db *pDb;
65266     } bw;
65267     struct OP_ParseSchema_stack_vars {
65268       int iDb;
65269       const char *zMaster;
65270       char *zSql;
65271       InitData initData;
65272     } bx;
65273     struct OP_IntegrityCk_stack_vars {
65274       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
65275       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
65276       int j;          /* Loop counter */
65277       int nErr;       /* Number of errors reported */
65278       char *z;        /* Text of the error report */
65279       Mem *pnErr;     /* Register keeping track of errors remaining */
65280     } by;
65281     struct OP_RowSetRead_stack_vars {
65282       i64 val;
65283     } bz;
65284     struct OP_RowSetTest_stack_vars {
65285       int iSet;
65286       int exists;
65287     } ca;
65288     struct OP_Program_stack_vars {
65289       int nMem;               /* Number of memory registers for sub-program */
65290       int nByte;              /* Bytes of runtime space required for sub-program */
65291       Mem *pRt;               /* Register to allocate runtime space */
65292       Mem *pMem;              /* Used to iterate through memory cells */
65293       Mem *pEnd;              /* Last memory cell in new array */
65294       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
65295       SubProgram *pProgram;   /* Sub-program to execute */
65296       void *t;                /* Token identifying trigger */
65297     } cb;
65298     struct OP_Param_stack_vars {
65299       VdbeFrame *pFrame;
65300       Mem *pIn;
65301     } cc;
65302     struct OP_MemMax_stack_vars {
65303       Mem *pIn1;
65304       VdbeFrame *pFrame;
65305     } cd;
65306     struct OP_AggStep_stack_vars {
65307       int n;
65308       int i;
65309       Mem *pMem;
65310       Mem *pRec;
65311       sqlcipher3_context ctx;
65312       sqlcipher3_value **apVal;
65313     } ce;
65314     struct OP_AggFinal_stack_vars {
65315       Mem *pMem;
65316     } cf;
65317     struct OP_Checkpoint_stack_vars {
65318       int i;                          /* Loop counter */
65319       int aRes[3];                    /* Results */
65320       Mem *pMem;                      /* Write results here */
65321     } cg;
65322     struct OP_JournalMode_stack_vars {
65323       Btree *pBt;                     /* Btree to change journal mode of */
65324       Pager *pPager;                  /* Pager associated with pBt */
65325       int eNew;                       /* New journal mode */
65326       int eOld;                       /* The old journal mode */
65327       const char *zFilename;          /* Name of database file for pPager */
65328     } ch;
65329     struct OP_IncrVacuum_stack_vars {
65330       Btree *pBt;
65331     } ci;
65332     struct OP_VBegin_stack_vars {
65333       VTable *pVTab;
65334     } cj;
65335     struct OP_VOpen_stack_vars {
65336       VdbeCursor *pCur;
65337       sqlcipher3_vtab_cursor *pVtabCursor;
65338       sqlcipher3_vtab *pVtab;
65339       sqlcipher3_module *pModule;
65340     } ck;
65341     struct OP_VFilter_stack_vars {
65342       int nArg;
65343       int iQuery;
65344       const sqlcipher3_module *pModule;
65345       Mem *pQuery;
65346       Mem *pArgc;
65347       sqlcipher3_vtab_cursor *pVtabCursor;
65348       sqlcipher3_vtab *pVtab;
65349       VdbeCursor *pCur;
65350       int res;
65351       int i;
65352       Mem **apArg;
65353     } cl;
65354     struct OP_VColumn_stack_vars {
65355       sqlcipher3_vtab *pVtab;
65356       const sqlcipher3_module *pModule;
65357       Mem *pDest;
65358       sqlcipher3_context sContext;
65359     } cm;
65360     struct OP_VNext_stack_vars {
65361       sqlcipher3_vtab *pVtab;
65362       const sqlcipher3_module *pModule;
65363       int res;
65364       VdbeCursor *pCur;
65365     } cn;
65366     struct OP_VRename_stack_vars {
65367       sqlcipher3_vtab *pVtab;
65368       Mem *pName;
65369     } co;
65370     struct OP_VUpdate_stack_vars {
65371       sqlcipher3_vtab *pVtab;
65372       sqlcipher3_module *pModule;
65373       int nArg;
65374       int i;
65375       sqlcipher_int64 rowid;
65376       Mem **apArg;
65377       Mem *pX;
65378     } cp;
65379     struct OP_Trace_stack_vars {
65380       char *zTrace;
65381       char *z;
65382     } cq;
65383   } u;
65384   /* End automatically generated code
65385   ********************************************************************/
65386
65387   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlcipher3_step() verifies this */
65388   sqlcipher3VdbeEnter(p);
65389   if( p->rc==SQLCIPHER_NOMEM ){
65390     /* This happens if a malloc() inside a call to sqlcipher3_column_text() or
65391     ** sqlcipher3_column_text16() failed.  */
65392     goto no_mem;
65393   }
65394   assert( p->rc==SQLCIPHER_OK || p->rc==SQLCIPHER_BUSY );
65395   p->rc = SQLCIPHER_OK;
65396   assert( p->explain==0 );
65397   p->pResultSet = 0;
65398   db->busyHandler.nBusy = 0;
65399   CHECK_FOR_INTERRUPT;
65400   sqlcipher3VdbeIOTraceSql(p);
65401 #ifndef SQLCIPHER_OMIT_PROGRESS_CALLBACK
65402   checkProgress = db->xProgress!=0;
65403 #endif
65404 #ifdef SQLCIPHER_DEBUG
65405   sqlcipher3BeginBenignMalloc();
65406   if( p->pc==0  && (p->db->flags & SQLCIPHER_VdbeListing)!=0 ){
65407     int i;
65408     printf("VDBE Program Listing:\n");
65409     sqlcipher3VdbePrintSql(p);
65410     for(i=0; i<p->nOp; i++){
65411       sqlcipher3VdbePrintOp(stdout, i, &aOp[i]);
65412     }
65413   }
65414   sqlcipher3EndBenignMalloc();
65415 #endif
65416   for(pc=p->pc; rc==SQLCIPHER_OK; pc++){
65417     assert( pc>=0 && pc<p->nOp );
65418     if( db->mallocFailed ) goto no_mem;
65419 #ifdef VDBE_PROFILE
65420     origPc = pc;
65421     start = sqlcipher3Hwtime();
65422 #endif
65423     pOp = &aOp[pc];
65424
65425     /* Only allow tracing if SQLCIPHER_DEBUG is defined.
65426     */
65427 #ifdef SQLCIPHER_DEBUG
65428     if( p->trace ){
65429       if( pc==0 ){
65430         printf("VDBE Execution Trace:\n");
65431         sqlcipher3VdbePrintSql(p);
65432       }
65433       sqlcipher3VdbePrintOp(p->trace, pc, pOp);
65434     }
65435 #endif
65436       
65437
65438     /* Check to see if we need to simulate an interrupt.  This only happens
65439     ** if we have a special test build.
65440     */
65441 #ifdef SQLCIPHER_TEST
65442     if( sqlcipher3_interrupt_count>0 ){
65443       sqlcipher3_interrupt_count--;
65444       if( sqlcipher3_interrupt_count==0 ){
65445         sqlcipher3_interrupt(db);
65446       }
65447     }
65448 #endif
65449
65450 #ifndef SQLCIPHER_OMIT_PROGRESS_CALLBACK
65451     /* Call the progress callback if it is configured and the required number
65452     ** of VDBE ops have been executed (either since this invocation of
65453     ** sqlcipher3VdbeExec() or since last time the progress callback was called).
65454     ** If the progress callback returns non-zero, exit the virtual machine with
65455     ** a return code SQLCIPHER_ABORT.
65456     */
65457     if( checkProgress ){
65458       if( db->nProgressOps==nProgressOps ){
65459         int prc;
65460         prc = db->xProgress(db->pProgressArg);
65461         if( prc!=0 ){
65462           rc = SQLCIPHER_INTERRUPT;
65463           goto vdbe_error_halt;
65464         }
65465         nProgressOps = 0;
65466       }
65467       nProgressOps++;
65468     }
65469 #endif
65470
65471     /* On any opcode with the "out2-prerelase" tag, free any
65472     ** external allocations out of mem[p2] and set mem[p2] to be
65473     ** an undefined integer.  Opcodes will either fill in the integer
65474     ** value or convert mem[p2] to a different type.
65475     */
65476     assert( pOp->opflags==sqlcipher3OpcodeProperty[pOp->opcode] );
65477     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
65478       assert( pOp->p2>0 );
65479       assert( pOp->p2<=p->nMem );
65480       pOut = &aMem[pOp->p2];
65481       memAboutToChange(p, pOut);
65482       MemReleaseExt(pOut);
65483       pOut->flags = MEM_Int;
65484     }
65485
65486     /* Sanity checking on other operands */
65487 #ifdef SQLCIPHER_DEBUG
65488     if( (pOp->opflags & OPFLG_IN1)!=0 ){
65489       assert( pOp->p1>0 );
65490       assert( pOp->p1<=p->nMem );
65491       assert( memIsValid(&aMem[pOp->p1]) );
65492       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
65493     }
65494     if( (pOp->opflags & OPFLG_IN2)!=0 ){
65495       assert( pOp->p2>0 );
65496       assert( pOp->p2<=p->nMem );
65497       assert( memIsValid(&aMem[pOp->p2]) );
65498       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
65499     }
65500     if( (pOp->opflags & OPFLG_IN3)!=0 ){
65501       assert( pOp->p3>0 );
65502       assert( pOp->p3<=p->nMem );
65503       assert( memIsValid(&aMem[pOp->p3]) );
65504       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
65505     }
65506     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
65507       assert( pOp->p2>0 );
65508       assert( pOp->p2<=p->nMem );
65509       memAboutToChange(p, &aMem[pOp->p2]);
65510     }
65511     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
65512       assert( pOp->p3>0 );
65513       assert( pOp->p3<=p->nMem );
65514       memAboutToChange(p, &aMem[pOp->p3]);
65515     }
65516 #endif
65517   
65518     switch( pOp->opcode ){
65519
65520 /*****************************************************************************
65521 ** What follows is a massive switch statement where each case implements a
65522 ** separate instruction in the virtual machine.  If we follow the usual
65523 ** indentation conventions, each case should be indented by 6 spaces.  But
65524 ** that is a lot of wasted space on the left margin.  So the code within
65525 ** the switch statement will break with convention and be flush-left. Another
65526 ** big comment (similar to this one) will mark the point in the code where
65527 ** we transition back to normal indentation.
65528 **
65529 ** The formatting of each case is important.  The makefile for SQLite
65530 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
65531 ** file looking for lines that begin with "case OP_".  The opcodes.h files
65532 ** will be filled with #defines that give unique integer values to each
65533 ** opcode and the opcodes.c file is filled with an array of strings where
65534 ** each string is the symbolic name for the corresponding opcode.  If the
65535 ** case statement is followed by a comment of the form "/# same as ... #/"
65536 ** that comment is used to determine the particular value of the opcode.
65537 **
65538 ** Other keywords in the comment that follows each case are used to
65539 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
65540 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
65541 ** the mkopcodeh.awk script for additional information.
65542 **
65543 ** Documentation about VDBE opcodes is generated by scanning this file
65544 ** for lines of that contain "Opcode:".  That line and all subsequent
65545 ** comment lines are used in the generation of the opcode.html documentation
65546 ** file.
65547 **
65548 ** SUMMARY:
65549 **
65550 **     Formatting is important to scripts that scan this file.
65551 **     Do not deviate from the formatting style currently in use.
65552 **
65553 *****************************************************************************/
65554
65555 /* Opcode:  Goto * P2 * * *
65556 **
65557 ** An unconditional jump to address P2.
65558 ** The next instruction executed will be 
65559 ** the one at index P2 from the beginning of
65560 ** the program.
65561 */
65562 case OP_Goto: {             /* jump */
65563   CHECK_FOR_INTERRUPT;
65564   pc = pOp->p2 - 1;
65565   break;
65566 }
65567
65568 /* Opcode:  Gosub P1 P2 * * *
65569 **
65570 ** Write the current address onto register P1
65571 ** and then jump to address P2.
65572 */
65573 case OP_Gosub: {            /* jump, in1 */
65574   pIn1 = &aMem[pOp->p1];
65575   assert( (pIn1->flags & MEM_Dyn)==0 );
65576   memAboutToChange(p, pIn1);
65577   pIn1->flags = MEM_Int;
65578   pIn1->u.i = pc;
65579   REGISTER_TRACE(pOp->p1, pIn1);
65580   pc = pOp->p2 - 1;
65581   break;
65582 }
65583
65584 /* Opcode:  Return P1 * * * *
65585 **
65586 ** Jump to the next instruction after the address in register P1.
65587 */
65588 case OP_Return: {           /* in1 */
65589   pIn1 = &aMem[pOp->p1];
65590   assert( pIn1->flags & MEM_Int );
65591   pc = (int)pIn1->u.i;
65592   break;
65593 }
65594
65595 /* Opcode:  Yield P1 * * * *
65596 **
65597 ** Swap the program counter with the value in register P1.
65598 */
65599 case OP_Yield: {            /* in1 */
65600 #if 0  /* local variables moved into u.aa */
65601   int pcDest;
65602 #endif /* local variables moved into u.aa */
65603   pIn1 = &aMem[pOp->p1];
65604   assert( (pIn1->flags & MEM_Dyn)==0 );
65605   pIn1->flags = MEM_Int;
65606   u.aa.pcDest = (int)pIn1->u.i;
65607   pIn1->u.i = pc;
65608   REGISTER_TRACE(pOp->p1, pIn1);
65609   pc = u.aa.pcDest;
65610   break;
65611 }
65612
65613 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
65614 **
65615 ** Check the value in register P3.  If it is NULL then Halt using
65616 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
65617 ** value in register P3 is not NULL, then this routine is a no-op.
65618 */
65619 case OP_HaltIfNull: {      /* in3 */
65620   pIn3 = &aMem[pOp->p3];
65621   if( (pIn3->flags & MEM_Null)==0 ) break;
65622   /* Fall through into OP_Halt */
65623 }
65624
65625 /* Opcode:  Halt P1 P2 * P4 *
65626 **
65627 ** Exit immediately.  All open cursors, etc are closed
65628 ** automatically.
65629 **
65630 ** P1 is the result code returned by sqlcipher3_exec(), sqlcipher3_reset(),
65631 ** or sqlcipher3_finalize().  For a normal halt, this should be SQLCIPHER_OK (0).
65632 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
65633 ** whether or not to rollback the current transaction.  Do not rollback
65634 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
65635 ** then back out all changes that have occurred during this execution of the
65636 ** VDBE, but do not rollback the transaction. 
65637 **
65638 ** If P4 is not null then it is an error message string.
65639 **
65640 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
65641 ** every program.  So a jump past the last instruction of the program
65642 ** is the same as executing Halt.
65643 */
65644 case OP_Halt: {
65645   if( pOp->p1==SQLCIPHER_OK && p->pFrame ){
65646     /* Halt the sub-program. Return control to the parent frame. */
65647     VdbeFrame *pFrame = p->pFrame;
65648     p->pFrame = pFrame->pParent;
65649     p->nFrame--;
65650     sqlcipher3VdbeSetChanges(db, p->nChange);
65651     pc = sqlcipher3VdbeFrameRestore(pFrame);
65652     lastRowid = db->lastRowid;
65653     if( pOp->p2==OE_Ignore ){
65654       /* Instruction pc is the OP_Program that invoked the sub-program 
65655       ** currently being halted. If the p2 instruction of this OP_Halt
65656       ** instruction is set to OE_Ignore, then the sub-program is throwing
65657       ** an IGNORE exception. In this case jump to the address specified
65658       ** as the p2 of the calling OP_Program.  */
65659       pc = p->aOp[pc].p2-1;
65660     }
65661     aOp = p->aOp;
65662     aMem = p->aMem;
65663     break;
65664   }
65665
65666   p->rc = pOp->p1;
65667   p->errorAction = (u8)pOp->p2;
65668   p->pc = pc;
65669   if( pOp->p4.z ){
65670     assert( p->rc!=SQLCIPHER_OK );
65671     sqlcipher3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
65672     testcase( sqlcipher3GlobalConfig.xLog!=0 );
65673     sqlcipher3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
65674   }else if( p->rc ){
65675     testcase( sqlcipher3GlobalConfig.xLog!=0 );
65676     sqlcipher3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
65677   }
65678   rc = sqlcipher3VdbeHalt(p);
65679   assert( rc==SQLCIPHER_BUSY || rc==SQLCIPHER_OK || rc==SQLCIPHER_ERROR );
65680   if( rc==SQLCIPHER_BUSY ){
65681     p->rc = rc = SQLCIPHER_BUSY;
65682   }else{
65683     assert( rc==SQLCIPHER_OK || p->rc==SQLCIPHER_CONSTRAINT );
65684     assert( rc==SQLCIPHER_OK || db->nDeferredCons>0 );
65685     rc = p->rc ? SQLCIPHER_ERROR : SQLCIPHER_DONE;
65686   }
65687   goto vdbe_return;
65688 }
65689
65690 /* Opcode: Integer P1 P2 * * *
65691 **
65692 ** The 32-bit integer value P1 is written into register P2.
65693 */
65694 case OP_Integer: {         /* out2-prerelease */
65695   pOut->u.i = pOp->p1;
65696   break;
65697 }
65698
65699 /* Opcode: Int64 * P2 * P4 *
65700 **
65701 ** P4 is a pointer to a 64-bit integer value.
65702 ** Write that value into register P2.
65703 */
65704 case OP_Int64: {           /* out2-prerelease */
65705   assert( pOp->p4.pI64!=0 );
65706   pOut->u.i = *pOp->p4.pI64;
65707   break;
65708 }
65709
65710 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
65711 /* Opcode: Real * P2 * P4 *
65712 **
65713 ** P4 is a pointer to a 64-bit floating point value.
65714 ** Write that value into register P2.
65715 */
65716 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
65717   pOut->flags = MEM_Real;
65718   assert( !sqlcipher3IsNaN(*pOp->p4.pReal) );
65719   pOut->r = *pOp->p4.pReal;
65720   break;
65721 }
65722 #endif
65723
65724 /* Opcode: String8 * P2 * P4 *
65725 **
65726 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
65727 ** into an OP_String before it is executed for the first time.
65728 */
65729 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
65730   assert( pOp->p4.z!=0 );
65731   pOp->opcode = OP_String;
65732   pOp->p1 = sqlcipher3Strlen30(pOp->p4.z);
65733
65734 #ifndef SQLCIPHER_OMIT_UTF16
65735   if( encoding!=SQLCIPHER_UTF8 ){
65736     rc = sqlcipher3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLCIPHER_UTF8, SQLCIPHER_STATIC);
65737     if( rc==SQLCIPHER_TOOBIG ) goto too_big;
65738     if( SQLCIPHER_OK!=sqlcipher3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
65739     assert( pOut->zMalloc==pOut->z );
65740     assert( pOut->flags & MEM_Dyn );
65741     pOut->zMalloc = 0;
65742     pOut->flags |= MEM_Static;
65743     pOut->flags &= ~MEM_Dyn;
65744     if( pOp->p4type==P4_DYNAMIC ){
65745       sqlcipher3DbFree(db, pOp->p4.z);
65746     }
65747     pOp->p4type = P4_DYNAMIC;
65748     pOp->p4.z = pOut->z;
65749     pOp->p1 = pOut->n;
65750   }
65751 #endif
65752   if( pOp->p1>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
65753     goto too_big;
65754   }
65755   /* Fall through to the next case, OP_String */
65756 }
65757   
65758 /* Opcode: String P1 P2 * P4 *
65759 **
65760 ** The string value P4 of length P1 (bytes) is stored in register P2.
65761 */
65762 case OP_String: {          /* out2-prerelease */
65763   assert( pOp->p4.z!=0 );
65764   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
65765   pOut->z = pOp->p4.z;
65766   pOut->n = pOp->p1;
65767   pOut->enc = encoding;
65768   UPDATE_MAX_BLOBSIZE(pOut);
65769   break;
65770 }
65771
65772 /* Opcode: Null * P2 * * *
65773 **
65774 ** Write a NULL into register P2.
65775 */
65776 case OP_Null: {           /* out2-prerelease */
65777   pOut->flags = MEM_Null;
65778   break;
65779 }
65780
65781
65782 /* Opcode: Blob P1 P2 * P4
65783 **
65784 ** P4 points to a blob of data P1 bytes long.  Store this
65785 ** blob in register P2.
65786 */
65787 case OP_Blob: {                /* out2-prerelease */
65788   assert( pOp->p1 <= SQLCIPHER_MAX_LENGTH );
65789   sqlcipher3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
65790   pOut->enc = encoding;
65791   UPDATE_MAX_BLOBSIZE(pOut);
65792   break;
65793 }
65794
65795 /* Opcode: Variable P1 P2 * P4 *
65796 **
65797 ** Transfer the values of bound parameter P1 into register P2
65798 **
65799 ** If the parameter is named, then its name appears in P4 and P3==1.
65800 ** The P4 value is used by sqlcipher3_bind_parameter_name().
65801 */
65802 case OP_Variable: {            /* out2-prerelease */
65803 #if 0  /* local variables moved into u.ab */
65804   Mem *pVar;       /* Value being transferred */
65805 #endif /* local variables moved into u.ab */
65806
65807   assert( pOp->p1>0 && pOp->p1<=p->nVar );
65808   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
65809   u.ab.pVar = &p->aVar[pOp->p1 - 1];
65810   if( sqlcipher3VdbeMemTooBig(u.ab.pVar) ){
65811     goto too_big;
65812   }
65813   sqlcipher3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
65814   UPDATE_MAX_BLOBSIZE(pOut);
65815   break;
65816 }
65817
65818 /* Opcode: Move P1 P2 P3 * *
65819 **
65820 ** Move the values in register P1..P1+P3-1 over into
65821 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
65822 ** left holding a NULL.  It is an error for register ranges
65823 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
65824 */
65825 case OP_Move: {
65826 #if 0  /* local variables moved into u.ac */
65827   char *zMalloc;   /* Holding variable for allocated memory */
65828   int n;           /* Number of registers left to copy */
65829   int p1;          /* Register to copy from */
65830   int p2;          /* Register to copy to */
65831 #endif /* local variables moved into u.ac */
65832
65833   u.ac.n = pOp->p3;
65834   u.ac.p1 = pOp->p1;
65835   u.ac.p2 = pOp->p2;
65836   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
65837   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
65838
65839   pIn1 = &aMem[u.ac.p1];
65840   pOut = &aMem[u.ac.p2];
65841   while( u.ac.n-- ){
65842     assert( pOut<=&aMem[p->nMem] );
65843     assert( pIn1<=&aMem[p->nMem] );
65844     assert( memIsValid(pIn1) );
65845     memAboutToChange(p, pOut);
65846     u.ac.zMalloc = pOut->zMalloc;
65847     pOut->zMalloc = 0;
65848     sqlcipher3VdbeMemMove(pOut, pIn1);
65849 #ifdef SQLCIPHER_DEBUG
65850     if( pOut->pScopyFrom>=&aMem[u.ac.p1] && pOut->pScopyFrom<&aMem[u.ac.p1+pOp->p3] ){
65851       pOut->pScopyFrom += u.ac.p1 - pOp->p2;
65852     }
65853 #endif
65854     pIn1->zMalloc = u.ac.zMalloc;
65855     REGISTER_TRACE(u.ac.p2++, pOut);
65856     pIn1++;
65857     pOut++;
65858   }
65859   break;
65860 }
65861
65862 /* Opcode: Copy P1 P2 * * *
65863 **
65864 ** Make a copy of register P1 into register P2.
65865 **
65866 ** This instruction makes a deep copy of the value.  A duplicate
65867 ** is made of any string or blob constant.  See also OP_SCopy.
65868 */
65869 case OP_Copy: {             /* in1, out2 */
65870   pIn1 = &aMem[pOp->p1];
65871   pOut = &aMem[pOp->p2];
65872   assert( pOut!=pIn1 );
65873   sqlcipher3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65874   Deephemeralize(pOut);
65875   REGISTER_TRACE(pOp->p2, pOut);
65876   break;
65877 }
65878
65879 /* Opcode: SCopy P1 P2 * * *
65880 **
65881 ** Make a shallow copy of register P1 into register P2.
65882 **
65883 ** This instruction makes a shallow copy of the value.  If the value
65884 ** is a string or blob, then the copy is only a pointer to the
65885 ** original and hence if the original changes so will the copy.
65886 ** Worse, if the original is deallocated, the copy becomes invalid.
65887 ** Thus the program must guarantee that the original will not change
65888 ** during the lifetime of the copy.  Use OP_Copy to make a complete
65889 ** copy.
65890 */
65891 case OP_SCopy: {            /* in1, out2 */
65892   pIn1 = &aMem[pOp->p1];
65893   pOut = &aMem[pOp->p2];
65894   assert( pOut!=pIn1 );
65895   sqlcipher3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65896 #ifdef SQLCIPHER_DEBUG
65897   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
65898 #endif
65899   REGISTER_TRACE(pOp->p2, pOut);
65900   break;
65901 }
65902
65903 /* Opcode: ResultRow P1 P2 * * *
65904 **
65905 ** The registers P1 through P1+P2-1 contain a single row of
65906 ** results. This opcode causes the sqlcipher3_step() call to terminate
65907 ** with an SQLCIPHER_ROW return code and it sets up the sqlcipher3_stmt
65908 ** structure to provide access to the top P1 values as the result
65909 ** row.
65910 */
65911 case OP_ResultRow: {
65912 #if 0  /* local variables moved into u.ad */
65913   Mem *pMem;
65914   int i;
65915 #endif /* local variables moved into u.ad */
65916   assert( p->nResColumn==pOp->p2 );
65917   assert( pOp->p1>0 );
65918   assert( pOp->p1+pOp->p2<=p->nMem+1 );
65919
65920   /* If this statement has violated immediate foreign key constraints, do
65921   ** not return the number of rows modified. And do not RELEASE the statement
65922   ** transaction. It needs to be rolled back.  */
65923   if( SQLCIPHER_OK!=(rc = sqlcipher3VdbeCheckFk(p, 0)) ){
65924     assert( db->flags&SQLCIPHER_CountRows );
65925     assert( p->usesStmtJournal );
65926     break;
65927   }
65928
65929   /* If the SQLCIPHER_CountRows flag is set in sqlcipher3.flags mask, then
65930   ** DML statements invoke this opcode to return the number of rows
65931   ** modified to the user. This is the only way that a VM that
65932   ** opens a statement transaction may invoke this opcode.
65933   **
65934   ** In case this is such a statement, close any statement transaction
65935   ** opened by this VM before returning control to the user. This is to
65936   ** ensure that statement-transactions are always nested, not overlapping.
65937   ** If the open statement-transaction is not closed here, then the user
65938   ** may step another VM that opens its own statement transaction. This
65939   ** may lead to overlapping statement transactions.
65940   **
65941   ** The statement transaction is never a top-level transaction.  Hence
65942   ** the RELEASE call below can never fail.
65943   */
65944   assert( p->iStatement==0 || db->flags&SQLCIPHER_CountRows );
65945   rc = sqlcipher3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
65946   if( NEVER(rc!=SQLCIPHER_OK) ){
65947     break;
65948   }
65949
65950   /* Invalidate all ephemeral cursor row caches */
65951   p->cacheCtr = (p->cacheCtr + 2)|1;
65952
65953   /* Make sure the results of the current row are \000 terminated
65954   ** and have an assigned type.  The results are de-ephemeralized as
65955   ** as side effect.
65956   */
65957   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
65958   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
65959     assert( memIsValid(&u.ad.pMem[u.ad.i]) );
65960     Deephemeralize(&u.ad.pMem[u.ad.i]);
65961     assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
65962             || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
65963     sqlcipher3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
65964     sqlcipher3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
65965     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
65966   }
65967   if( db->mallocFailed ) goto no_mem;
65968
65969   /* Return SQLCIPHER_ROW
65970   */
65971   p->pc = pc + 1;
65972   rc = SQLCIPHER_ROW;
65973   goto vdbe_return;
65974 }
65975
65976 /* Opcode: Concat P1 P2 P3 * *
65977 **
65978 ** Add the text in register P1 onto the end of the text in
65979 ** register P2 and store the result in register P3.
65980 ** If either the P1 or P2 text are NULL then store NULL in P3.
65981 **
65982 **   P3 = P2 || P1
65983 **
65984 ** It is illegal for P1 and P3 to be the same register. Sometimes,
65985 ** if P3 is the same register as P2, the implementation is able
65986 ** to avoid a memcpy().
65987 */
65988 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
65989 #if 0  /* local variables moved into u.ae */
65990   i64 nByte;
65991 #endif /* local variables moved into u.ae */
65992
65993   pIn1 = &aMem[pOp->p1];
65994   pIn2 = &aMem[pOp->p2];
65995   pOut = &aMem[pOp->p3];
65996   assert( pIn1!=pOut );
65997   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
65998     sqlcipher3VdbeMemSetNull(pOut);
65999     break;
66000   }
66001   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
66002   Stringify(pIn1, encoding);
66003   Stringify(pIn2, encoding);
66004   u.ae.nByte = pIn1->n + pIn2->n;
66005   if( u.ae.nByte>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
66006     goto too_big;
66007   }
66008   MemSetTypeFlag(pOut, MEM_Str);
66009   if( sqlcipher3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
66010     goto no_mem;
66011   }
66012   if( pOut!=pIn2 ){
66013     memcpy(pOut->z, pIn2->z, pIn2->n);
66014   }
66015   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
66016   pOut->z[u.ae.nByte] = 0;
66017   pOut->z[u.ae.nByte+1] = 0;
66018   pOut->flags |= MEM_Term;
66019   pOut->n = (int)u.ae.nByte;
66020   pOut->enc = encoding;
66021   UPDATE_MAX_BLOBSIZE(pOut);
66022   break;
66023 }
66024
66025 /* Opcode: Add P1 P2 P3 * *
66026 **
66027 ** Add the value in register P1 to the value in register P2
66028 ** and store the result in register P3.
66029 ** If either input is NULL, the result is NULL.
66030 */
66031 /* Opcode: Multiply P1 P2 P3 * *
66032 **
66033 **
66034 ** Multiply the value in register P1 by the value in register P2
66035 ** and store the result in register P3.
66036 ** If either input is NULL, the result is NULL.
66037 */
66038 /* Opcode: Subtract P1 P2 P3 * *
66039 **
66040 ** Subtract the value in register P1 from the value in register P2
66041 ** and store the result in register P3.
66042 ** If either input is NULL, the result is NULL.
66043 */
66044 /* Opcode: Divide P1 P2 P3 * *
66045 **
66046 ** Divide the value in register P1 by the value in register P2
66047 ** and store the result in register P3 (P3=P2/P1). If the value in 
66048 ** register P1 is zero, then the result is NULL. If either input is 
66049 ** NULL, the result is NULL.
66050 */
66051 /* Opcode: Remainder P1 P2 P3 * *
66052 **
66053 ** Compute the remainder after integer division of the value in
66054 ** register P1 by the value in register P2 and store the result in P3. 
66055 ** If the value in register P2 is zero the result is NULL.
66056 ** If either operand is NULL, the result is NULL.
66057 */
66058 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
66059 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
66060 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
66061 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
66062 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
66063 #if 0  /* local variables moved into u.af */
66064   int flags;      /* Combined MEM_* flags from both inputs */
66065   i64 iA;         /* Integer value of left operand */
66066   i64 iB;         /* Integer value of right operand */
66067   double rA;      /* Real value of left operand */
66068   double rB;      /* Real value of right operand */
66069 #endif /* local variables moved into u.af */
66070
66071   pIn1 = &aMem[pOp->p1];
66072   applyNumericAffinity(pIn1);
66073   pIn2 = &aMem[pOp->p2];
66074   applyNumericAffinity(pIn2);
66075   pOut = &aMem[pOp->p3];
66076   u.af.flags = pIn1->flags | pIn2->flags;
66077   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
66078   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
66079     u.af.iA = pIn1->u.i;
66080     u.af.iB = pIn2->u.i;
66081     switch( pOp->opcode ){
66082       case OP_Add:       if( sqlcipher3AddInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
66083       case OP_Subtract:  if( sqlcipher3SubInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
66084       case OP_Multiply:  if( sqlcipher3MulInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
66085       case OP_Divide: {
66086         if( u.af.iA==0 ) goto arithmetic_result_is_null;
66087         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) goto fp_math;
66088         u.af.iB /= u.af.iA;
66089         break;
66090       }
66091       default: {
66092         if( u.af.iA==0 ) goto arithmetic_result_is_null;
66093         if( u.af.iA==-1 ) u.af.iA = 1;
66094         u.af.iB %= u.af.iA;
66095         break;
66096       }
66097     }
66098     pOut->u.i = u.af.iB;
66099     MemSetTypeFlag(pOut, MEM_Int);
66100   }else{
66101 fp_math:
66102     u.af.rA = sqlcipher3VdbeRealValue(pIn1);
66103     u.af.rB = sqlcipher3VdbeRealValue(pIn2);
66104     switch( pOp->opcode ){
66105       case OP_Add:         u.af.rB += u.af.rA;       break;
66106       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
66107       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
66108       case OP_Divide: {
66109         /* (double)0 In case of SQLCIPHER_OMIT_FLOATING_POINT... */
66110         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
66111         u.af.rB /= u.af.rA;
66112         break;
66113       }
66114       default: {
66115         u.af.iA = (i64)u.af.rA;
66116         u.af.iB = (i64)u.af.rB;
66117         if( u.af.iA==0 ) goto arithmetic_result_is_null;
66118         if( u.af.iA==-1 ) u.af.iA = 1;
66119         u.af.rB = (double)(u.af.iB % u.af.iA);
66120         break;
66121       }
66122     }
66123 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
66124     pOut->u.i = u.af.rB;
66125     MemSetTypeFlag(pOut, MEM_Int);
66126 #else
66127     if( sqlcipher3IsNaN(u.af.rB) ){
66128       goto arithmetic_result_is_null;
66129     }
66130     pOut->r = u.af.rB;
66131     MemSetTypeFlag(pOut, MEM_Real);
66132     if( (u.af.flags & MEM_Real)==0 ){
66133       sqlcipher3VdbeIntegerAffinity(pOut);
66134     }
66135 #endif
66136   }
66137   break;
66138
66139 arithmetic_result_is_null:
66140   sqlcipher3VdbeMemSetNull(pOut);
66141   break;
66142 }
66143
66144 /* Opcode: CollSeq * * P4
66145 **
66146 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
66147 ** or aggregate calls sqlcipher3GetFuncCollSeq(), this collation sequence will
66148 ** be returned. This is used by the built-in min(), max() and nullif()
66149 ** functions.
66150 **
66151 ** The interface used by the implementation of the aforementioned functions
66152 ** to retrieve the collation sequence set by this opcode is not available
66153 ** publicly, only to user functions defined in func.c.
66154 */
66155 case OP_CollSeq: {
66156   assert( pOp->p4type==P4_COLLSEQ );
66157   break;
66158 }
66159
66160 /* Opcode: Function P1 P2 P3 P4 P5
66161 **
66162 ** Invoke a user function (P4 is a pointer to a Function structure that
66163 ** defines the function) with P5 arguments taken from register P2 and
66164 ** successors.  The result of the function is stored in register P3.
66165 ** Register P3 must not be one of the function inputs.
66166 **
66167 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
66168 ** function was determined to be constant at compile time. If the first
66169 ** argument was constant then bit 0 of P1 is set. This is used to determine
66170 ** whether meta data associated with a user function argument using the
66171 ** sqlcipher3_set_auxdata() API may be safely retained until the next
66172 ** invocation of this opcode.
66173 **
66174 ** See also: AggStep and AggFinal
66175 */
66176 case OP_Function: {
66177 #if 0  /* local variables moved into u.ag */
66178   int i;
66179   Mem *pArg;
66180   sqlcipher3_context ctx;
66181   sqlcipher3_value **apVal;
66182   int n;
66183 #endif /* local variables moved into u.ag */
66184
66185   u.ag.n = pOp->p5;
66186   u.ag.apVal = p->apArg;
66187   assert( u.ag.apVal || u.ag.n==0 );
66188   assert( pOp->p3>0 && pOp->p3<=p->nMem );
66189   pOut = &aMem[pOp->p3];
66190   memAboutToChange(p, pOut);
66191
66192   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
66193   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
66194   u.ag.pArg = &aMem[pOp->p2];
66195   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
66196     assert( memIsValid(u.ag.pArg) );
66197     u.ag.apVal[u.ag.i] = u.ag.pArg;
66198     Deephemeralize(u.ag.pArg);
66199     sqlcipher3VdbeMemStoreType(u.ag.pArg);
66200     REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
66201   }
66202
66203   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
66204   if( pOp->p4type==P4_FUNCDEF ){
66205     u.ag.ctx.pFunc = pOp->p4.pFunc;
66206     u.ag.ctx.pVdbeFunc = 0;
66207   }else{
66208     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
66209     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
66210   }
66211
66212   u.ag.ctx.s.flags = MEM_Null;
66213   u.ag.ctx.s.db = db;
66214   u.ag.ctx.s.xDel = 0;
66215   u.ag.ctx.s.zMalloc = 0;
66216
66217   /* The output cell may already have a buffer allocated. Move
66218   ** the pointer to u.ag.ctx.s so in case the user-function can use
66219   ** the already allocated buffer instead of allocating a new one.
66220   */
66221   sqlcipher3VdbeMemMove(&u.ag.ctx.s, pOut);
66222   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
66223
66224   u.ag.ctx.isError = 0;
66225   if( u.ag.ctx.pFunc->flags & SQLCIPHER_FUNC_NEEDCOLL ){
66226     assert( pOp>aOp );
66227     assert( pOp[-1].p4type==P4_COLLSEQ );
66228     assert( pOp[-1].opcode==OP_CollSeq );
66229     u.ag.ctx.pColl = pOp[-1].p4.pColl;
66230   }
66231   db->lastRowid = lastRowid;
66232   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
66233   lastRowid = db->lastRowid;
66234
66235   /* If any auxiliary data functions have been called by this user function,
66236   ** immediately call the destructor for any non-static values.
66237   */
66238   if( u.ag.ctx.pVdbeFunc ){
66239     sqlcipher3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
66240     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
66241     pOp->p4type = P4_VDBEFUNC;
66242   }
66243
66244   if( db->mallocFailed ){
66245     /* Even though a malloc() has failed, the implementation of the
66246     ** user function may have called an sqlcipher3_result_XXX() function
66247     ** to return a value. The following call releases any resources
66248     ** associated with such a value.
66249     */
66250     sqlcipher3VdbeMemRelease(&u.ag.ctx.s);
66251     goto no_mem;
66252   }
66253
66254   /* If the function returned an error, throw an exception */
66255   if( u.ag.ctx.isError ){
66256     sqlcipher3SetString(&p->zErrMsg, db, "%s", sqlcipher3_value_text(&u.ag.ctx.s));
66257     rc = u.ag.ctx.isError;
66258   }
66259
66260   /* Copy the result of the function into register P3 */
66261   sqlcipher3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
66262   sqlcipher3VdbeMemMove(pOut, &u.ag.ctx.s);
66263   if( sqlcipher3VdbeMemTooBig(pOut) ){
66264     goto too_big;
66265   }
66266
66267 #if 0
66268   /* The app-defined function has done something that as caused this
66269   ** statement to expire.  (Perhaps the function called sqlcipher3_exec()
66270   ** with a CREATE TABLE statement.)
66271   */
66272   if( p->expired ) rc = SQLCIPHER_ABORT;
66273 #endif
66274
66275   REGISTER_TRACE(pOp->p3, pOut);
66276   UPDATE_MAX_BLOBSIZE(pOut);
66277   break;
66278 }
66279
66280 /* Opcode: BitAnd P1 P2 P3 * *
66281 **
66282 ** Take the bit-wise AND of the values in register P1 and P2 and
66283 ** store the result in register P3.
66284 ** If either input is NULL, the result is NULL.
66285 */
66286 /* Opcode: BitOr P1 P2 P3 * *
66287 **
66288 ** Take the bit-wise OR of the values in register P1 and P2 and
66289 ** store the result in register P3.
66290 ** If either input is NULL, the result is NULL.
66291 */
66292 /* Opcode: ShiftLeft P1 P2 P3 * *
66293 **
66294 ** Shift the integer value in register P2 to the left by the
66295 ** number of bits specified by the integer in register P1.
66296 ** Store the result in register P3.
66297 ** If either input is NULL, the result is NULL.
66298 */
66299 /* Opcode: ShiftRight P1 P2 P3 * *
66300 **
66301 ** Shift the integer value in register P2 to the right by the
66302 ** number of bits specified by the integer in register P1.
66303 ** Store the result in register P3.
66304 ** If either input is NULL, the result is NULL.
66305 */
66306 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
66307 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
66308 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
66309 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
66310 #if 0  /* local variables moved into u.ah */
66311   i64 iA;
66312   u64 uA;
66313   i64 iB;
66314   u8 op;
66315 #endif /* local variables moved into u.ah */
66316
66317   pIn1 = &aMem[pOp->p1];
66318   pIn2 = &aMem[pOp->p2];
66319   pOut = &aMem[pOp->p3];
66320   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66321     sqlcipher3VdbeMemSetNull(pOut);
66322     break;
66323   }
66324   u.ah.iA = sqlcipher3VdbeIntValue(pIn2);
66325   u.ah.iB = sqlcipher3VdbeIntValue(pIn1);
66326   u.ah.op = pOp->opcode;
66327   if( u.ah.op==OP_BitAnd ){
66328     u.ah.iA &= u.ah.iB;
66329   }else if( u.ah.op==OP_BitOr ){
66330     u.ah.iA |= u.ah.iB;
66331   }else if( u.ah.iB!=0 ){
66332     assert( u.ah.op==OP_ShiftRight || u.ah.op==OP_ShiftLeft );
66333
66334     /* If shifting by a negative amount, shift in the other direction */
66335     if( u.ah.iB<0 ){
66336       assert( OP_ShiftRight==OP_ShiftLeft+1 );
66337       u.ah.op = 2*OP_ShiftLeft + 1 - u.ah.op;
66338       u.ah.iB = u.ah.iB>(-64) ? -u.ah.iB : 64;
66339     }
66340
66341     if( u.ah.iB>=64 ){
66342       u.ah.iA = (u.ah.iA>=0 || u.ah.op==OP_ShiftLeft) ? 0 : -1;
66343     }else{
66344       memcpy(&u.ah.uA, &u.ah.iA, sizeof(u.ah.uA));
66345       if( u.ah.op==OP_ShiftLeft ){
66346         u.ah.uA <<= u.ah.iB;
66347       }else{
66348         u.ah.uA >>= u.ah.iB;
66349         /* Sign-extend on a right shift of a negative number */
66350         if( u.ah.iA<0 ) u.ah.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ah.iB);
66351       }
66352       memcpy(&u.ah.iA, &u.ah.uA, sizeof(u.ah.iA));
66353     }
66354   }
66355   pOut->u.i = u.ah.iA;
66356   MemSetTypeFlag(pOut, MEM_Int);
66357   break;
66358 }
66359
66360 /* Opcode: AddImm  P1 P2 * * *
66361 ** 
66362 ** Add the constant P2 to the value in register P1.
66363 ** The result is always an integer.
66364 **
66365 ** To force any register to be an integer, just add 0.
66366 */
66367 case OP_AddImm: {            /* in1 */
66368   pIn1 = &aMem[pOp->p1];
66369   memAboutToChange(p, pIn1);
66370   sqlcipher3VdbeMemIntegerify(pIn1);
66371   pIn1->u.i += pOp->p2;
66372   break;
66373 }
66374
66375 /* Opcode: MustBeInt P1 P2 * * *
66376 ** 
66377 ** Force the value in register P1 to be an integer.  If the value
66378 ** in P1 is not an integer and cannot be converted into an integer
66379 ** without data loss, then jump immediately to P2, or if P2==0
66380 ** raise an SQLCIPHER_MISMATCH exception.
66381 */
66382 case OP_MustBeInt: {            /* jump, in1 */
66383   pIn1 = &aMem[pOp->p1];
66384   applyAffinity(pIn1, SQLCIPHER_AFF_NUMERIC, encoding);
66385   if( (pIn1->flags & MEM_Int)==0 ){
66386     if( pOp->p2==0 ){
66387       rc = SQLCIPHER_MISMATCH;
66388       goto abort_due_to_error;
66389     }else{
66390       pc = pOp->p2 - 1;
66391     }
66392   }else{
66393     MemSetTypeFlag(pIn1, MEM_Int);
66394   }
66395   break;
66396 }
66397
66398 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
66399 /* Opcode: RealAffinity P1 * * * *
66400 **
66401 ** If register P1 holds an integer convert it to a real value.
66402 **
66403 ** This opcode is used when extracting information from a column that
66404 ** has REAL affinity.  Such column values may still be stored as
66405 ** integers, for space efficiency, but after extraction we want them
66406 ** to have only a real value.
66407 */
66408 case OP_RealAffinity: {                  /* in1 */
66409   pIn1 = &aMem[pOp->p1];
66410   if( pIn1->flags & MEM_Int ){
66411     sqlcipher3VdbeMemRealify(pIn1);
66412   }
66413   break;
66414 }
66415 #endif
66416
66417 #ifndef SQLCIPHER_OMIT_CAST
66418 /* Opcode: ToText P1 * * * *
66419 **
66420 ** Force the value in register P1 to be text.
66421 ** If the value is numeric, convert it to a string using the
66422 ** equivalent of printf().  Blob values are unchanged and
66423 ** are afterwards simply interpreted as text.
66424 **
66425 ** A NULL value is not changed by this routine.  It remains NULL.
66426 */
66427 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
66428   pIn1 = &aMem[pOp->p1];
66429   memAboutToChange(p, pIn1);
66430   if( pIn1->flags & MEM_Null ) break;
66431   assert( MEM_Str==(MEM_Blob>>3) );
66432   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
66433   applyAffinity(pIn1, SQLCIPHER_AFF_TEXT, encoding);
66434   rc = ExpandBlob(pIn1);
66435   assert( pIn1->flags & MEM_Str || db->mallocFailed );
66436   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
66437   UPDATE_MAX_BLOBSIZE(pIn1);
66438   break;
66439 }
66440
66441 /* Opcode: ToBlob P1 * * * *
66442 **
66443 ** Force the value in register P1 to be a BLOB.
66444 ** If the value is numeric, convert it to a string first.
66445 ** Strings are simply reinterpreted as blobs with no change
66446 ** to the underlying data.
66447 **
66448 ** A NULL value is not changed by this routine.  It remains NULL.
66449 */
66450 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
66451   pIn1 = &aMem[pOp->p1];
66452   if( pIn1->flags & MEM_Null ) break;
66453   if( (pIn1->flags & MEM_Blob)==0 ){
66454     applyAffinity(pIn1, SQLCIPHER_AFF_TEXT, encoding);
66455     assert( pIn1->flags & MEM_Str || db->mallocFailed );
66456     MemSetTypeFlag(pIn1, MEM_Blob);
66457   }else{
66458     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
66459   }
66460   UPDATE_MAX_BLOBSIZE(pIn1);
66461   break;
66462 }
66463
66464 /* Opcode: ToNumeric P1 * * * *
66465 **
66466 ** Force the value in register P1 to be numeric (either an
66467 ** integer or a floating-point number.)
66468 ** If the value is text or blob, try to convert it to an using the
66469 ** equivalent of atoi() or atof() and store 0 if no such conversion 
66470 ** is possible.
66471 **
66472 ** A NULL value is not changed by this routine.  It remains NULL.
66473 */
66474 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
66475   pIn1 = &aMem[pOp->p1];
66476   sqlcipher3VdbeMemNumerify(pIn1);
66477   break;
66478 }
66479 #endif /* SQLCIPHER_OMIT_CAST */
66480
66481 /* Opcode: ToInt P1 * * * *
66482 **
66483 ** Force the value in register P1 to be an integer.  If
66484 ** The value is currently a real number, drop its fractional part.
66485 ** If the value is text or blob, try to convert it to an integer using the
66486 ** equivalent of atoi() and store 0 if no such conversion is possible.
66487 **
66488 ** A NULL value is not changed by this routine.  It remains NULL.
66489 */
66490 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
66491   pIn1 = &aMem[pOp->p1];
66492   if( (pIn1->flags & MEM_Null)==0 ){
66493     sqlcipher3VdbeMemIntegerify(pIn1);
66494   }
66495   break;
66496 }
66497
66498 #if !defined(SQLCIPHER_OMIT_CAST) && !defined(SQLCIPHER_OMIT_FLOATING_POINT)
66499 /* Opcode: ToReal P1 * * * *
66500 **
66501 ** Force the value in register P1 to be a floating point number.
66502 ** If The value is currently an integer, convert it.
66503 ** If the value is text or blob, try to convert it to an integer using the
66504 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
66505 **
66506 ** A NULL value is not changed by this routine.  It remains NULL.
66507 */
66508 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
66509   pIn1 = &aMem[pOp->p1];
66510   memAboutToChange(p, pIn1);
66511   if( (pIn1->flags & MEM_Null)==0 ){
66512     sqlcipher3VdbeMemRealify(pIn1);
66513   }
66514   break;
66515 }
66516 #endif /* !defined(SQLCIPHER_OMIT_CAST) && !defined(SQLCIPHER_OMIT_FLOATING_POINT) */
66517
66518 /* Opcode: Lt P1 P2 P3 P4 P5
66519 **
66520 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
66521 ** jump to address P2.  
66522 **
66523 ** If the SQLCIPHER_JUMPIFNULL bit of P5 is set and either reg(P1) or
66524 ** reg(P3) is NULL then take the jump.  If the SQLCIPHER_JUMPIFNULL 
66525 ** bit is clear then fall through if either operand is NULL.
66526 **
66527 ** The SQLCIPHER_AFF_MASK portion of P5 must be an affinity character -
66528 ** SQLCIPHER_AFF_TEXT, SQLCIPHER_AFF_INTEGER, and so forth. An attempt is made 
66529 ** to coerce both inputs according to this affinity before the
66530 ** comparison is made. If the SQLCIPHER_AFF_MASK is 0x00, then numeric
66531 ** affinity is used. Note that the affinity conversions are stored
66532 ** back into the input registers P1 and P3.  So this opcode can cause
66533 ** persistent changes to registers P1 and P3.
66534 **
66535 ** Once any conversions have taken place, and neither value is NULL, 
66536 ** the values are compared. If both values are blobs then memcmp() is
66537 ** used to determine the results of the comparison.  If both values
66538 ** are text, then the appropriate collating function specified in
66539 ** P4 is  used to do the comparison.  If P4 is not specified then
66540 ** memcmp() is used to compare text string.  If both values are
66541 ** numeric, then a numeric comparison is used. If the two values
66542 ** are of different types, then numbers are considered less than
66543 ** strings and strings are considered less than blobs.
66544 **
66545 ** If the SQLCIPHER_STOREP2 bit of P5 is set, then do not jump.  Instead,
66546 ** store a boolean result (either 0, or 1, or NULL) in register P2.
66547 */
66548 /* Opcode: Ne P1 P2 P3 P4 P5
66549 **
66550 ** This works just like the Lt opcode except that the jump is taken if
66551 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
66552 ** additional information.
66553 **
66554 ** If SQLCIPHER_NULLEQ is set in P5 then the result of comparison is always either
66555 ** true or false and is never NULL.  If both operands are NULL then the result
66556 ** of comparison is false.  If either operand is NULL then the result is true.
66557 ** If neither operand is NULL the result is the same as it would be if
66558 ** the SQLCIPHER_NULLEQ flag were omitted from P5.
66559 */
66560 /* Opcode: Eq P1 P2 P3 P4 P5
66561 **
66562 ** This works just like the Lt opcode except that the jump is taken if
66563 ** the operands in registers P1 and P3 are equal.
66564 ** See the Lt opcode for additional information.
66565 **
66566 ** If SQLCIPHER_NULLEQ is set in P5 then the result of comparison is always either
66567 ** true or false and is never NULL.  If both operands are NULL then the result
66568 ** of comparison is true.  If either operand is NULL then the result is false.
66569 ** If neither operand is NULL the result is the same as it would be if
66570 ** the SQLCIPHER_NULLEQ flag were omitted from P5.
66571 */
66572 /* Opcode: Le P1 P2 P3 P4 P5
66573 **
66574 ** This works just like the Lt opcode except that the jump is taken if
66575 ** the content of register P3 is less than or equal to the content of
66576 ** register P1.  See the Lt opcode for additional information.
66577 */
66578 /* Opcode: Gt P1 P2 P3 P4 P5
66579 **
66580 ** This works just like the Lt opcode except that the jump is taken if
66581 ** the content of register P3 is greater than the content of
66582 ** register P1.  See the Lt opcode for additional information.
66583 */
66584 /* Opcode: Ge P1 P2 P3 P4 P5
66585 **
66586 ** This works just like the Lt opcode except that the jump is taken if
66587 ** the content of register P3 is greater than or equal to the content of
66588 ** register P1.  See the Lt opcode for additional information.
66589 */
66590 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
66591 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
66592 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
66593 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
66594 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
66595 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
66596 #if 0  /* local variables moved into u.ai */
66597   int res;            /* Result of the comparison of pIn1 against pIn3 */
66598   char affinity;      /* Affinity to use for comparison */
66599   u16 flags1;         /* Copy of initial value of pIn1->flags */
66600   u16 flags3;         /* Copy of initial value of pIn3->flags */
66601 #endif /* local variables moved into u.ai */
66602
66603   pIn1 = &aMem[pOp->p1];
66604   pIn3 = &aMem[pOp->p3];
66605   u.ai.flags1 = pIn1->flags;
66606   u.ai.flags3 = pIn3->flags;
66607   if( (u.ai.flags1 | u.ai.flags3)&MEM_Null ){
66608     /* One or both operands are NULL */
66609     if( pOp->p5 & SQLCIPHER_NULLEQ ){
66610       /* If SQLCIPHER_NULLEQ is set (which will only happen if the operator is
66611       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
66612       ** or not both operands are null.
66613       */
66614       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
66615       u.ai.res = (u.ai.flags1 & u.ai.flags3 & MEM_Null)==0;
66616     }else{
66617       /* SQLCIPHER_NULLEQ is clear and at least one operand is NULL,
66618       ** then the result is always NULL.
66619       ** The jump is taken if the SQLCIPHER_JUMPIFNULL bit is set.
66620       */
66621       if( pOp->p5 & SQLCIPHER_STOREP2 ){
66622         pOut = &aMem[pOp->p2];
66623         MemSetTypeFlag(pOut, MEM_Null);
66624         REGISTER_TRACE(pOp->p2, pOut);
66625       }else if( pOp->p5 & SQLCIPHER_JUMPIFNULL ){
66626         pc = pOp->p2-1;
66627       }
66628       break;
66629     }
66630   }else{
66631     /* Neither operand is NULL.  Do a comparison. */
66632     u.ai.affinity = pOp->p5 & SQLCIPHER_AFF_MASK;
66633     if( u.ai.affinity ){
66634       applyAffinity(pIn1, u.ai.affinity, encoding);
66635       applyAffinity(pIn3, u.ai.affinity, encoding);
66636       if( db->mallocFailed ) goto no_mem;
66637     }
66638
66639     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
66640     ExpandBlob(pIn1);
66641     ExpandBlob(pIn3);
66642     u.ai.res = sqlcipher3MemCompare(pIn3, pIn1, pOp->p4.pColl);
66643   }
66644   switch( pOp->opcode ){
66645     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
66646     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
66647     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
66648     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
66649     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
66650     default:       u.ai.res = u.ai.res>=0;     break;
66651   }
66652
66653   if( pOp->p5 & SQLCIPHER_STOREP2 ){
66654     pOut = &aMem[pOp->p2];
66655     memAboutToChange(p, pOut);
66656     MemSetTypeFlag(pOut, MEM_Int);
66657     pOut->u.i = u.ai.res;
66658     REGISTER_TRACE(pOp->p2, pOut);
66659   }else if( u.ai.res ){
66660     pc = pOp->p2-1;
66661   }
66662
66663   /* Undo any changes made by applyAffinity() to the input registers. */
66664   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
66665   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
66666   break;
66667 }
66668
66669 /* Opcode: Permutation * * * P4 *
66670 **
66671 ** Set the permutation used by the OP_Compare operator to be the array
66672 ** of integers in P4.
66673 **
66674 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
66675 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
66676 ** immediately prior to the OP_Compare.
66677 */
66678 case OP_Permutation: {
66679   assert( pOp->p4type==P4_INTARRAY );
66680   assert( pOp->p4.ai );
66681   aPermute = pOp->p4.ai;
66682   break;
66683 }
66684
66685 /* Opcode: Compare P1 P2 P3 P4 *
66686 **
66687 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
66688 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
66689 ** the comparison for use by the next OP_Jump instruct.
66690 **
66691 ** P4 is a KeyInfo structure that defines collating sequences and sort
66692 ** orders for the comparison.  The permutation applies to registers
66693 ** only.  The KeyInfo elements are used sequentially.
66694 **
66695 ** The comparison is a sort comparison, so NULLs compare equal,
66696 ** NULLs are less than numbers, numbers are less than strings,
66697 ** and strings are less than blobs.
66698 */
66699 case OP_Compare: {
66700 #if 0  /* local variables moved into u.aj */
66701   int n;
66702   int i;
66703   int p1;
66704   int p2;
66705   const KeyInfo *pKeyInfo;
66706   int idx;
66707   CollSeq *pColl;    /* Collating sequence to use on this term */
66708   int bRev;          /* True for DESCENDING sort order */
66709 #endif /* local variables moved into u.aj */
66710
66711   u.aj.n = pOp->p3;
66712   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
66713   assert( u.aj.n>0 );
66714   assert( u.aj.pKeyInfo!=0 );
66715   u.aj.p1 = pOp->p1;
66716   u.aj.p2 = pOp->p2;
66717 #if SQLCIPHER_DEBUG
66718   if( aPermute ){
66719     int k, mx = 0;
66720     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
66721     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
66722     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
66723   }else{
66724     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
66725     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
66726   }
66727 #endif /* SQLCIPHER_DEBUG */
66728   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
66729     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
66730     assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
66731     assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
66732     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
66733     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
66734     assert( u.aj.i<u.aj.pKeyInfo->nField );
66735     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
66736     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
66737     iCompare = sqlcipher3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
66738     if( iCompare ){
66739       if( u.aj.bRev ) iCompare = -iCompare;
66740       break;
66741     }
66742   }
66743   aPermute = 0;
66744   break;
66745 }
66746
66747 /* Opcode: Jump P1 P2 P3 * *
66748 **
66749 ** Jump to the instruction at address P1, P2, or P3 depending on whether
66750 ** in the most recent OP_Compare instruction the P1 vector was less than
66751 ** equal to, or greater than the P2 vector, respectively.
66752 */
66753 case OP_Jump: {             /* jump */
66754   if( iCompare<0 ){
66755     pc = pOp->p1 - 1;
66756   }else if( iCompare==0 ){
66757     pc = pOp->p2 - 1;
66758   }else{
66759     pc = pOp->p3 - 1;
66760   }
66761   break;
66762 }
66763
66764 /* Opcode: And P1 P2 P3 * *
66765 **
66766 ** Take the logical AND of the values in registers P1 and P2 and
66767 ** write the result into register P3.
66768 **
66769 ** If either P1 or P2 is 0 (false) then the result is 0 even if
66770 ** the other input is NULL.  A NULL and true or two NULLs give
66771 ** a NULL output.
66772 */
66773 /* Opcode: Or P1 P2 P3 * *
66774 **
66775 ** Take the logical OR of the values in register P1 and P2 and
66776 ** store the answer in register P3.
66777 **
66778 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
66779 ** even if the other input is NULL.  A NULL and false or two NULLs
66780 ** give a NULL output.
66781 */
66782 case OP_And:              /* same as TK_AND, in1, in2, out3 */
66783 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
66784 #if 0  /* local variables moved into u.ak */
66785   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
66786   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
66787 #endif /* local variables moved into u.ak */
66788
66789   pIn1 = &aMem[pOp->p1];
66790   if( pIn1->flags & MEM_Null ){
66791     u.ak.v1 = 2;
66792   }else{
66793     u.ak.v1 = sqlcipher3VdbeIntValue(pIn1)!=0;
66794   }
66795   pIn2 = &aMem[pOp->p2];
66796   if( pIn2->flags & MEM_Null ){
66797     u.ak.v2 = 2;
66798   }else{
66799     u.ak.v2 = sqlcipher3VdbeIntValue(pIn2)!=0;
66800   }
66801   if( pOp->opcode==OP_And ){
66802     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
66803     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
66804   }else{
66805     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
66806     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
66807   }
66808   pOut = &aMem[pOp->p3];
66809   if( u.ak.v1==2 ){
66810     MemSetTypeFlag(pOut, MEM_Null);
66811   }else{
66812     pOut->u.i = u.ak.v1;
66813     MemSetTypeFlag(pOut, MEM_Int);
66814   }
66815   break;
66816 }
66817
66818 /* Opcode: Not P1 P2 * * *
66819 **
66820 ** Interpret the value in register P1 as a boolean value.  Store the
66821 ** boolean complement in register P2.  If the value in register P1 is 
66822 ** NULL, then a NULL is stored in P2.
66823 */
66824 case OP_Not: {                /* same as TK_NOT, in1, out2 */
66825   pIn1 = &aMem[pOp->p1];
66826   pOut = &aMem[pOp->p2];
66827   if( pIn1->flags & MEM_Null ){
66828     sqlcipher3VdbeMemSetNull(pOut);
66829   }else{
66830     sqlcipher3VdbeMemSetInt64(pOut, !sqlcipher3VdbeIntValue(pIn1));
66831   }
66832   break;
66833 }
66834
66835 /* Opcode: BitNot P1 P2 * * *
66836 **
66837 ** Interpret the content of register P1 as an integer.  Store the
66838 ** ones-complement of the P1 value into register P2.  If P1 holds
66839 ** a NULL then store a NULL in P2.
66840 */
66841 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
66842   pIn1 = &aMem[pOp->p1];
66843   pOut = &aMem[pOp->p2];
66844   if( pIn1->flags & MEM_Null ){
66845     sqlcipher3VdbeMemSetNull(pOut);
66846   }else{
66847     sqlcipher3VdbeMemSetInt64(pOut, ~sqlcipher3VdbeIntValue(pIn1));
66848   }
66849   break;
66850 }
66851
66852 /* Opcode: Once P1 P2 * * *
66853 **
66854 ** Jump to P2 if the value in register P1 is a not null or zero.  If
66855 ** the value is NULL or zero, fall through and change the P1 register
66856 ** to an integer 1.
66857 **
66858 ** When P1 is not used otherwise in a program, this opcode falls through
66859 ** once and jumps on all subsequent invocations.  It is the equivalent
66860 ** of "OP_If P1 P2", followed by "OP_Integer 1 P1".
66861 */
66862 /* Opcode: If P1 P2 P3 * *
66863 **
66864 ** Jump to P2 if the value in register P1 is true.  The value
66865 ** is considered true if it is numeric and non-zero.  If the value
66866 ** in P1 is NULL then take the jump if P3 is true.
66867 */
66868 /* Opcode: IfNot P1 P2 P3 * *
66869 **
66870 ** Jump to P2 if the value in register P1 is False.  The value
66871 ** is considered true if it has a numeric value of zero.  If the value
66872 ** in P1 is NULL then take the jump if P3 is true.
66873 */
66874 case OP_Once:               /* jump, in1 */
66875 case OP_If:                 /* jump, in1 */
66876 case OP_IfNot: {            /* jump, in1 */
66877 #if 0  /* local variables moved into u.al */
66878   int c;
66879 #endif /* local variables moved into u.al */
66880   pIn1 = &aMem[pOp->p1];
66881   if( pIn1->flags & MEM_Null ){
66882     u.al.c = pOp->p3;
66883   }else{
66884 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
66885     u.al.c = sqlcipher3VdbeIntValue(pIn1)!=0;
66886 #else
66887     u.al.c = sqlcipher3VdbeRealValue(pIn1)!=0.0;
66888 #endif
66889     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
66890   }
66891   if( u.al.c ){
66892     pc = pOp->p2-1;
66893   }else if( pOp->opcode==OP_Once ){
66894     assert( (pIn1->flags & (MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))==0 );
66895     memAboutToChange(p, pIn1);
66896     pIn1->flags = MEM_Int;
66897     pIn1->u.i = 1;
66898     REGISTER_TRACE(pOp->p1, pIn1);
66899   }
66900   break;
66901 }
66902
66903 /* Opcode: IsNull P1 P2 * * *
66904 **
66905 ** Jump to P2 if the value in register P1 is NULL.
66906 */
66907 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
66908   pIn1 = &aMem[pOp->p1];
66909   if( (pIn1->flags & MEM_Null)!=0 ){
66910     pc = pOp->p2 - 1;
66911   }
66912   break;
66913 }
66914
66915 /* Opcode: NotNull P1 P2 * * *
66916 **
66917 ** Jump to P2 if the value in register P1 is not NULL.  
66918 */
66919 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
66920   pIn1 = &aMem[pOp->p1];
66921   if( (pIn1->flags & MEM_Null)==0 ){
66922     pc = pOp->p2 - 1;
66923   }
66924   break;
66925 }
66926
66927 /* Opcode: Column P1 P2 P3 P4 P5
66928 **
66929 ** Interpret the data that cursor P1 points to as a structure built using
66930 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
66931 ** information about the format of the data.)  Extract the P2-th column
66932 ** from this record.  If there are less that (P2+1) 
66933 ** values in the record, extract a NULL.
66934 **
66935 ** The value extracted is stored in register P3.
66936 **
66937 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
66938 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
66939 ** the result.
66940 **
66941 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
66942 ** then the cache of the cursor is reset prior to extracting the column.
66943 ** The first OP_Column against a pseudo-table after the value of the content
66944 ** register has changed should have this bit set.
66945 */
66946 case OP_Column: {
66947 #if 0  /* local variables moved into u.am */
66948   u32 payloadSize;   /* Number of bytes in the record */
66949   i64 payloadSize64; /* Number of bytes in the record */
66950   int p1;            /* P1 value of the opcode */
66951   int p2;            /* column number to retrieve */
66952   VdbeCursor *pC;    /* The VDBE cursor */
66953   char *zRec;        /* Pointer to complete record-data */
66954   BtCursor *pCrsr;   /* The BTree cursor */
66955   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
66956   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
66957   int nField;        /* number of fields in the record */
66958   int len;           /* The length of the serialized data for the column */
66959   int i;             /* Loop counter */
66960   char *zData;       /* Part of the record being decoded */
66961   Mem *pDest;        /* Where to write the extracted value */
66962   Mem sMem;          /* For storing the record being decoded */
66963   u8 *zIdx;          /* Index into header */
66964   u8 *zEndHdr;       /* Pointer to first byte after the header */
66965   u32 offset;        /* Offset into the data */
66966   u32 szField;       /* Number of bytes in the content of a field */
66967   int szHdr;         /* Size of the header size field at start of record */
66968   int avail;         /* Number of bytes of available data */
66969   u32 t;             /* A type code from the record header */
66970   Mem *pReg;         /* PseudoTable input register */
66971 #endif /* local variables moved into u.am */
66972
66973
66974   u.am.p1 = pOp->p1;
66975   u.am.p2 = pOp->p2;
66976   u.am.pC = 0;
66977   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
66978   assert( u.am.p1<p->nCursor );
66979   assert( pOp->p3>0 && pOp->p3<=p->nMem );
66980   u.am.pDest = &aMem[pOp->p3];
66981   memAboutToChange(p, u.am.pDest);
66982   u.am.zRec = 0;
66983
66984   /* This block sets the variable u.am.payloadSize to be the total number of
66985   ** bytes in the record.
66986   **
66987   ** u.am.zRec is set to be the complete text of the record if it is available.
66988   ** The complete record text is always available for pseudo-tables
66989   ** If the record is stored in a cursor, the complete record text
66990   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
66991   ** If the data is unavailable,  u.am.zRec is set to NULL.
66992   **
66993   ** We also compute the number of columns in the record.  For cursors,
66994   ** the number of columns is stored in the VdbeCursor.nField element.
66995   */
66996   u.am.pC = p->apCsr[u.am.p1];
66997   assert( u.am.pC!=0 );
66998 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
66999   assert( u.am.pC->pVtabCursor==0 );
67000 #endif
67001   u.am.pCrsr = u.am.pC->pCursor;
67002   if( u.am.pCrsr!=0 ){
67003     /* The record is stored in a B-Tree */
67004     rc = sqlcipher3VdbeCursorMoveto(u.am.pC);
67005     if( rc ) goto abort_due_to_error;
67006     if( u.am.pC->nullRow ){
67007       u.am.payloadSize = 0;
67008     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
67009       u.am.payloadSize = u.am.pC->payloadSize;
67010       u.am.zRec = (char*)u.am.pC->aRow;
67011     }else if( u.am.pC->isIndex ){
67012       assert( sqlcipher3BtreeCursorIsValid(u.am.pCrsr) );
67013       VVA_ONLY(rc =) sqlcipher3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
67014       assert( rc==SQLCIPHER_OK );   /* True because of CursorMoveto() call above */
67015       /* sqlcipher3BtreeParseCellPtr() uses getVarint32() to extract the
67016       ** payload size, so it is impossible for u.am.payloadSize64 to be
67017       ** larger than 32 bits. */
67018       assert( (u.am.payloadSize64 & SQLCIPHER_MAX_U32)==(u64)u.am.payloadSize64 );
67019       u.am.payloadSize = (u32)u.am.payloadSize64;
67020     }else{
67021       assert( sqlcipher3BtreeCursorIsValid(u.am.pCrsr) );
67022       VVA_ONLY(rc =) sqlcipher3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
67023       assert( rc==SQLCIPHER_OK );   /* DataSize() cannot fail */
67024     }
67025   }else if( ALWAYS(u.am.pC->pseudoTableReg>0) ){
67026     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
67027     assert( u.am.pReg->flags & MEM_Blob );
67028     assert( memIsValid(u.am.pReg) );
67029     u.am.payloadSize = u.am.pReg->n;
67030     u.am.zRec = u.am.pReg->z;
67031     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
67032     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
67033   }else{
67034     /* Consider the row to be NULL */
67035     u.am.payloadSize = 0;
67036   }
67037
67038   /* If u.am.payloadSize is 0, then just store a NULL.  This can happen because of
67039   ** nullRow or because of a corrupt database. */
67040   if( u.am.payloadSize==0 ){
67041     MemSetTypeFlag(u.am.pDest, MEM_Null);
67042     goto op_column_out;
67043   }
67044   assert( db->aLimit[SQLCIPHER_LIMIT_LENGTH]>=0 );
67045   if( u.am.payloadSize > (u32)db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
67046     goto too_big;
67047   }
67048
67049   u.am.nField = u.am.pC->nField;
67050   assert( u.am.p2<u.am.nField );
67051
67052   /* Read and parse the table header.  Store the results of the parse
67053   ** into the record header cache fields of the cursor.
67054   */
67055   u.am.aType = u.am.pC->aType;
67056   if( u.am.pC->cacheStatus==p->cacheCtr ){
67057     u.am.aOffset = u.am.pC->aOffset;
67058   }else{
67059     assert(u.am.aType);
67060     u.am.avail = 0;
67061     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
67062     u.am.pC->payloadSize = u.am.payloadSize;
67063     u.am.pC->cacheStatus = p->cacheCtr;
67064
67065     /* Figure out how many bytes are in the header */
67066     if( u.am.zRec ){
67067       u.am.zData = u.am.zRec;
67068     }else{
67069       if( u.am.pC->isIndex ){
67070         u.am.zData = (char*)sqlcipher3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
67071       }else{
67072         u.am.zData = (char*)sqlcipher3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
67073       }
67074       /* If KeyFetch()/DataFetch() managed to get the entire payload,
67075       ** save the payload in the u.am.pC->aRow cache.  That will save us from
67076       ** having to make additional calls to fetch the content portion of
67077       ** the record.
67078       */
67079       assert( u.am.avail>=0 );
67080       if( u.am.payloadSize <= (u32)u.am.avail ){
67081         u.am.zRec = u.am.zData;
67082         u.am.pC->aRow = (u8*)u.am.zData;
67083       }else{
67084         u.am.pC->aRow = 0;
67085       }
67086     }
67087     /* The following assert is true in all cases accept when
67088     ** the database file has been corrupted externally.
67089     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
67090     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
67091
67092     /* Make sure a corrupt database has not given us an oversize header.
67093     ** Do this now to avoid an oversize memory allocation.
67094     **
67095     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
67096     ** types use so much data space that there can only be 4096 and 32 of
67097     ** them, respectively.  So the maximum header length results from a
67098     ** 3-byte type for each of the maximum of 32768 columns plus three
67099     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
67100     */
67101     if( u.am.offset > 98307 ){
67102       rc = SQLCIPHER_CORRUPT_BKPT;
67103       goto op_column_out;
67104     }
67105
67106     /* Compute in u.am.len the number of bytes of data we need to read in order
67107     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
67108     ** u.am.nField might be significantly less than the true number of columns
67109     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
67110     ** We want to minimize u.am.len in order to limit the size of the memory
67111     ** allocation, especially if a corrupt database file has caused u.am.offset
67112     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
67113     ** still exceed Robson memory allocation limits on some configurations.
67114     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
67115     ** will likely be much smaller since u.am.nField will likely be less than
67116     ** 20 or so.  This insures that Robson memory allocation limits are
67117     ** not exceeded even for corrupt database files.
67118     */
67119     u.am.len = u.am.nField*5 + 3;
67120     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
67121
67122     /* The KeyFetch() or DataFetch() above are fast and will get the entire
67123     ** record header in most cases.  But they will fail to get the complete
67124     ** record header if the record header does not fit on a single page
67125     ** in the B-Tree.  When that happens, use sqlcipher3VdbeMemFromBtree() to
67126     ** acquire the complete header text.
67127     */
67128     if( !u.am.zRec && u.am.avail<u.am.len ){
67129       u.am.sMem.flags = 0;
67130       u.am.sMem.db = 0;
67131       rc = sqlcipher3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
67132       if( rc!=SQLCIPHER_OK ){
67133         goto op_column_out;
67134       }
67135       u.am.zData = u.am.sMem.z;
67136     }
67137     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
67138     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
67139
67140     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
67141     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
67142     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
67143     ** of the record to the start of the data for the u.am.i-th column
67144     */
67145     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
67146       if( u.am.zIdx<u.am.zEndHdr ){
67147         u.am.aOffset[u.am.i] = u.am.offset;
67148         if( u.am.zIdx[0]<0x80 ){
67149           u.am.t = u.am.zIdx[0];
67150           u.am.zIdx++;
67151         }else{
67152           u.am.zIdx += sqlcipher3GetVarint32(u.am.zIdx, &u.am.t);
67153         }
67154         u.am.aType[u.am.i] = u.am.t;
67155         u.am.szField = sqlcipher3VdbeSerialTypeLen(u.am.t);
67156         u.am.offset += u.am.szField;
67157         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
67158           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLCIPHER_CORRUPT return below */
67159           break;
67160         }
67161       }else{
67162         /* If u.am.i is less that u.am.nField, then there are less fields in this
67163         ** record than SetNumColumns indicated there are columns in the
67164         ** table. Set the u.am.offset for any extra columns not present in
67165         ** the record to 0. This tells code below to store a NULL
67166         ** instead of deserializing a value from the record.
67167         */
67168         u.am.aOffset[u.am.i] = 0;
67169       }
67170     }
67171     sqlcipher3VdbeMemRelease(&u.am.sMem);
67172     u.am.sMem.flags = MEM_Null;
67173
67174     /* If we have read more header data than was contained in the header,
67175     ** or if the end of the last field appears to be past the end of the
67176     ** record, or if the end of the last field appears to be before the end
67177     ** of the record (when all fields present), then we must be dealing
67178     ** with a corrupt database.
67179     */
67180     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
67181          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
67182       rc = SQLCIPHER_CORRUPT_BKPT;
67183       goto op_column_out;
67184     }
67185   }
67186
67187   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
67188   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
67189   ** then there are not enough fields in the record to satisfy the
67190   ** request.  In this case, set the value NULL or to P4 if P4 is
67191   ** a pointer to a Mem object.
67192   */
67193   if( u.am.aOffset[u.am.p2] ){
67194     assert( rc==SQLCIPHER_OK );
67195     if( u.am.zRec ){
67196       MemReleaseExt(u.am.pDest);
67197       sqlcipher3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
67198     }else{
67199       u.am.len = sqlcipher3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
67200       sqlcipher3VdbeMemMove(&u.am.sMem, u.am.pDest);
67201       rc = sqlcipher3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
67202       if( rc!=SQLCIPHER_OK ){
67203         goto op_column_out;
67204       }
67205       u.am.zData = u.am.sMem.z;
67206       sqlcipher3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
67207     }
67208     u.am.pDest->enc = encoding;
67209   }else{
67210     if( pOp->p4type==P4_MEM ){
67211       sqlcipher3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
67212     }else{
67213       MemSetTypeFlag(u.am.pDest, MEM_Null);
67214     }
67215   }
67216
67217   /* If we dynamically allocated space to hold the data (in the
67218   ** sqlcipher3VdbeMemFromBtree() call above) then transfer control of that
67219   ** dynamically allocated space over to the u.am.pDest structure.
67220   ** This prevents a memory copy.
67221   */
67222   if( u.am.sMem.zMalloc ){
67223     assert( u.am.sMem.z==u.am.sMem.zMalloc );
67224     assert( !(u.am.pDest->flags & MEM_Dyn) );
67225     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
67226     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
67227     u.am.pDest->flags |= MEM_Term;
67228     u.am.pDest->z = u.am.sMem.z;
67229     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
67230   }
67231
67232   rc = sqlcipher3VdbeMemMakeWriteable(u.am.pDest);
67233
67234 op_column_out:
67235   UPDATE_MAX_BLOBSIZE(u.am.pDest);
67236   REGISTER_TRACE(pOp->p3, u.am.pDest);
67237   break;
67238 }
67239
67240 /* Opcode: Affinity P1 P2 * P4 *
67241 **
67242 ** Apply affinities to a range of P2 registers starting with P1.
67243 **
67244 ** P4 is a string that is P2 characters long. The nth character of the
67245 ** string indicates the column affinity that should be used for the nth
67246 ** memory cell in the range.
67247 */
67248 case OP_Affinity: {
67249 #if 0  /* local variables moved into u.an */
67250   const char *zAffinity;   /* The affinity to be applied */
67251   char cAff;               /* A single character of affinity */
67252 #endif /* local variables moved into u.an */
67253
67254   u.an.zAffinity = pOp->p4.z;
67255   assert( u.an.zAffinity!=0 );
67256   assert( u.an.zAffinity[pOp->p2]==0 );
67257   pIn1 = &aMem[pOp->p1];
67258   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
67259     assert( pIn1 <= &p->aMem[p->nMem] );
67260     assert( memIsValid(pIn1) );
67261     ExpandBlob(pIn1);
67262     applyAffinity(pIn1, u.an.cAff, encoding);
67263     pIn1++;
67264   }
67265   break;
67266 }
67267
67268 /* Opcode: MakeRecord P1 P2 P3 P4 *
67269 **
67270 ** Convert P2 registers beginning with P1 into the [record format]
67271 ** use as a data record in a database table or as a key
67272 ** in an index.  The OP_Column opcode can decode the record later.
67273 **
67274 ** P4 may be a string that is P2 characters long.  The nth character of the
67275 ** string indicates the column affinity that should be used for the nth
67276 ** field of the index key.
67277 **
67278 ** The mapping from character to affinity is given by the SQLCIPHER_AFF_
67279 ** macros defined in sqlcipherInt.h.
67280 **
67281 ** If P4 is NULL then all index fields have the affinity NONE.
67282 */
67283 case OP_MakeRecord: {
67284 #if 0  /* local variables moved into u.ao */
67285   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
67286   Mem *pRec;             /* The new record */
67287   u64 nData;             /* Number of bytes of data space */
67288   int nHdr;              /* Number of bytes of header space */
67289   i64 nByte;             /* Data space required for this record */
67290   int nZero;             /* Number of zero bytes at the end of the record */
67291   int nVarint;           /* Number of bytes in a varint */
67292   u32 serial_type;       /* Type field */
67293   Mem *pData0;           /* First field to be combined into the record */
67294   Mem *pLast;            /* Last field of the record */
67295   int nField;            /* Number of fields in the record */
67296   char *zAffinity;       /* The affinity string for the record */
67297   int file_format;       /* File format to use for encoding */
67298   int i;                 /* Space used in zNewRecord[] */
67299   int len;               /* Length of a field */
67300 #endif /* local variables moved into u.ao */
67301
67302   /* Assuming the record contains N fields, the record format looks
67303   ** like this:
67304   **
67305   ** ------------------------------------------------------------------------
67306   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
67307   ** ------------------------------------------------------------------------
67308   **
67309   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
67310   ** and so froth.
67311   **
67312   ** Each type field is a varint representing the serial type of the
67313   ** corresponding data element (see sqlcipher3VdbeSerialType()). The
67314   ** hdr-size field is also a varint which is the offset from the beginning
67315   ** of the record to data0.
67316   */
67317   u.ao.nData = 0;         /* Number of bytes of data space */
67318   u.ao.nHdr = 0;          /* Number of bytes of header space */
67319   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
67320   u.ao.nField = pOp->p1;
67321   u.ao.zAffinity = pOp->p4.z;
67322   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
67323   u.ao.pData0 = &aMem[u.ao.nField];
67324   u.ao.nField = pOp->p2;
67325   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
67326   u.ao.file_format = p->minWriteFileFormat;
67327
67328   /* Identify the output register */
67329   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
67330   pOut = &aMem[pOp->p3];
67331   memAboutToChange(p, pOut);
67332
67333   /* Loop through the elements that will make up the record to figure
67334   ** out how much space is required for the new record.
67335   */
67336   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
67337     assert( memIsValid(u.ao.pRec) );
67338     if( u.ao.zAffinity ){
67339       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
67340     }
67341     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
67342       sqlcipher3VdbeMemExpandBlob(u.ao.pRec);
67343     }
67344     u.ao.serial_type = sqlcipher3VdbeSerialType(u.ao.pRec, u.ao.file_format);
67345     u.ao.len = sqlcipher3VdbeSerialTypeLen(u.ao.serial_type);
67346     u.ao.nData += u.ao.len;
67347     u.ao.nHdr += sqlcipher3VarintLen(u.ao.serial_type);
67348     if( u.ao.pRec->flags & MEM_Zero ){
67349       /* Only pure zero-filled BLOBs can be input to this Opcode.
67350       ** We do not allow blobs with a prefix and a zero-filled tail. */
67351       u.ao.nZero += u.ao.pRec->u.nZero;
67352     }else if( u.ao.len ){
67353       u.ao.nZero = 0;
67354     }
67355   }
67356
67357   /* Add the initial header varint and total the size */
67358   u.ao.nHdr += u.ao.nVarint = sqlcipher3VarintLen(u.ao.nHdr);
67359   if( u.ao.nVarint<sqlcipher3VarintLen(u.ao.nHdr) ){
67360     u.ao.nHdr++;
67361   }
67362   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
67363   if( u.ao.nByte>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
67364     goto too_big;
67365   }
67366
67367   /* Make sure the output register has a buffer large enough to store
67368   ** the new record. The output register (pOp->p3) is not allowed to
67369   ** be one of the input registers (because the following call to
67370   ** sqlcipher3VdbeMemGrow() could clobber the value before it is used).
67371   */
67372   if( sqlcipher3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
67373     goto no_mem;
67374   }
67375   u.ao.zNewRecord = (u8 *)pOut->z;
67376
67377   /* Write the record */
67378   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
67379   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
67380     u.ao.serial_type = sqlcipher3VdbeSerialType(u.ao.pRec, u.ao.file_format);
67381     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
67382   }
67383   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
67384     u.ao.i += sqlcipher3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
67385   }
67386   assert( u.ao.i==u.ao.nByte );
67387
67388   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67389   pOut->n = (int)u.ao.nByte;
67390   pOut->flags = MEM_Blob | MEM_Dyn;
67391   pOut->xDel = 0;
67392   if( u.ao.nZero ){
67393     pOut->u.nZero = u.ao.nZero;
67394     pOut->flags |= MEM_Zero;
67395   }
67396   pOut->enc = SQLCIPHER_UTF8;  /* In case the blob is ever converted to text */
67397   REGISTER_TRACE(pOp->p3, pOut);
67398   UPDATE_MAX_BLOBSIZE(pOut);
67399   break;
67400 }
67401
67402 /* Opcode: Count P1 P2 * * *
67403 **
67404 ** Store the number of entries (an integer value) in the table or index 
67405 ** opened by cursor P1 in register P2
67406 */
67407 #ifndef SQLCIPHER_OMIT_BTREECOUNT
67408 case OP_Count: {         /* out2-prerelease */
67409 #if 0  /* local variables moved into u.ap */
67410   i64 nEntry;
67411   BtCursor *pCrsr;
67412 #endif /* local variables moved into u.ap */
67413
67414   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
67415   if( ALWAYS(u.ap.pCrsr) ){
67416     rc = sqlcipher3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
67417   }else{
67418     u.ap.nEntry = 0;
67419   }
67420   pOut->u.i = u.ap.nEntry;
67421   break;
67422 }
67423 #endif
67424
67425 /* Opcode: Savepoint P1 * * P4 *
67426 **
67427 ** Open, release or rollback the savepoint named by parameter P4, depending
67428 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
67429 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
67430 */
67431 case OP_Savepoint: {
67432 #if 0  /* local variables moved into u.aq */
67433   int p1;                         /* Value of P1 operand */
67434   char *zName;                    /* Name of savepoint */
67435   int nName;
67436   Savepoint *pNew;
67437   Savepoint *pSavepoint;
67438   Savepoint *pTmp;
67439   int iSavepoint;
67440   int ii;
67441 #endif /* local variables moved into u.aq */
67442
67443   u.aq.p1 = pOp->p1;
67444   u.aq.zName = pOp->p4.z;
67445
67446   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
67447   ** transaction, then there cannot be any savepoints.
67448   */
67449   assert( db->pSavepoint==0 || db->autoCommit==0 );
67450   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
67451   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
67452   assert( checkSavepointCount(db) );
67453
67454   if( u.aq.p1==SAVEPOINT_BEGIN ){
67455     if( db->writeVdbeCnt>0 ){
67456       /* A new savepoint cannot be created if there are active write
67457       ** statements (i.e. open read/write incremental blob handles).
67458       */
67459       sqlcipher3SetString(&p->zErrMsg, db, "cannot open savepoint - "
67460         "SQL statements in progress");
67461       rc = SQLCIPHER_BUSY;
67462     }else{
67463       u.aq.nName = sqlcipher3Strlen30(u.aq.zName);
67464
67465 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
67466       /* This call is Ok even if this savepoint is actually a transaction
67467       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
67468       ** If this is a transaction savepoint being opened, it is guaranteed
67469       ** that the db->aVTrans[] array is empty.  */
67470       assert( db->autoCommit==0 || db->nVTrans==0 );
67471       rc = sqlcipher3VtabSavepoint(db, SAVEPOINT_BEGIN,
67472                                 db->nStatement+db->nSavepoint);
67473       if( rc!=SQLCIPHER_OK ) goto abort_due_to_error;
67474 #endif
67475
67476       /* Create a new savepoint structure. */
67477       u.aq.pNew = sqlcipher3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
67478       if( u.aq.pNew ){
67479         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
67480         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
67481
67482         /* If there is no open transaction, then mark this as a special
67483         ** "transaction savepoint". */
67484         if( db->autoCommit ){
67485           db->autoCommit = 0;
67486           db->isTransactionSavepoint = 1;
67487         }else{
67488           db->nSavepoint++;
67489         }
67490
67491         /* Link the new savepoint into the database handle's list. */
67492         u.aq.pNew->pNext = db->pSavepoint;
67493         db->pSavepoint = u.aq.pNew;
67494         u.aq.pNew->nDeferredCons = db->nDeferredCons;
67495       }
67496     }
67497   }else{
67498     u.aq.iSavepoint = 0;
67499
67500     /* Find the named savepoint. If there is no such savepoint, then an
67501     ** an error is returned to the user.  */
67502     for(
67503       u.aq.pSavepoint = db->pSavepoint;
67504       u.aq.pSavepoint && sqlcipher3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
67505       u.aq.pSavepoint = u.aq.pSavepoint->pNext
67506     ){
67507       u.aq.iSavepoint++;
67508     }
67509     if( !u.aq.pSavepoint ){
67510       sqlcipher3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
67511       rc = SQLCIPHER_ERROR;
67512     }else if(
67513         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
67514     ){
67515       /* It is not possible to release (commit) a savepoint if there are
67516       ** active write statements. It is not possible to rollback a savepoint
67517       ** if there are any active statements at all.
67518       */
67519       sqlcipher3SetString(&p->zErrMsg, db,
67520         "cannot %s savepoint - SQL statements in progress",
67521         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
67522       );
67523       rc = SQLCIPHER_BUSY;
67524     }else{
67525
67526       /* Determine whether or not this is a transaction savepoint. If so,
67527       ** and this is a RELEASE command, then the current transaction
67528       ** is committed.
67529       */
67530       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
67531       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
67532         if( (rc = sqlcipher3VdbeCheckFk(p, 1))!=SQLCIPHER_OK ){
67533           goto vdbe_return;
67534         }
67535         db->autoCommit = 1;
67536         if( sqlcipher3VdbeHalt(p)==SQLCIPHER_BUSY ){
67537           p->pc = pc;
67538           db->autoCommit = 0;
67539           p->rc = rc = SQLCIPHER_BUSY;
67540           goto vdbe_return;
67541         }
67542         db->isTransactionSavepoint = 0;
67543         rc = p->rc;
67544       }else{
67545         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
67546         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
67547           rc = sqlcipher3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
67548           if( rc!=SQLCIPHER_OK ){
67549             goto abort_due_to_error;
67550           }
67551         }
67552         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLCIPHER_InternChanges)!=0 ){
67553           sqlcipher3ExpirePreparedStatements(db);
67554           sqlcipher3ResetInternalSchema(db, -1);
67555           db->flags = (db->flags | SQLCIPHER_InternChanges);
67556         }
67557       }
67558
67559       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
67560       ** savepoints nested inside of the savepoint being operated on. */
67561       while( db->pSavepoint!=u.aq.pSavepoint ){
67562         u.aq.pTmp = db->pSavepoint;
67563         db->pSavepoint = u.aq.pTmp->pNext;
67564         sqlcipher3DbFree(db, u.aq.pTmp);
67565         db->nSavepoint--;
67566       }
67567
67568       /* If it is a RELEASE, then destroy the savepoint being operated on
67569       ** too. If it is a ROLLBACK TO, then set the number of deferred
67570       ** constraint violations present in the database to the value stored
67571       ** when the savepoint was created.  */
67572       if( u.aq.p1==SAVEPOINT_RELEASE ){
67573         assert( u.aq.pSavepoint==db->pSavepoint );
67574         db->pSavepoint = u.aq.pSavepoint->pNext;
67575         sqlcipher3DbFree(db, u.aq.pSavepoint);
67576         if( !isTransaction ){
67577           db->nSavepoint--;
67578         }
67579       }else{
67580         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
67581       }
67582
67583       if( !isTransaction ){
67584         rc = sqlcipher3VtabSavepoint(db, u.aq.p1, u.aq.iSavepoint);
67585         if( rc!=SQLCIPHER_OK ) goto abort_due_to_error;
67586       }
67587     }
67588   }
67589
67590   break;
67591 }
67592
67593 /* Opcode: AutoCommit P1 P2 * * *
67594 **
67595 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
67596 ** back any currently active btree transactions. If there are any active
67597 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
67598 ** there are active writing VMs or active VMs that use shared cache.
67599 **
67600 ** This instruction causes the VM to halt.
67601 */
67602 case OP_AutoCommit: {
67603 #if 0  /* local variables moved into u.ar */
67604   int desiredAutoCommit;
67605   int iRollback;
67606   int turnOnAC;
67607 #endif /* local variables moved into u.ar */
67608
67609   u.ar.desiredAutoCommit = pOp->p1;
67610   u.ar.iRollback = pOp->p2;
67611   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
67612   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
67613   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
67614   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
67615
67616   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
67617     /* If this instruction implements a ROLLBACK and other VMs are
67618     ** still running, and a transaction is active, return an error indicating
67619     ** that the other VMs must complete first.
67620     */
67621     sqlcipher3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
67622         "SQL statements in progress");
67623     rc = SQLCIPHER_BUSY;
67624   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
67625     /* If this instruction implements a COMMIT and other VMs are writing
67626     ** return an error indicating that the other VMs must complete first.
67627     */
67628     sqlcipher3SetString(&p->zErrMsg, db, "cannot commit transaction - "
67629         "SQL statements in progress");
67630     rc = SQLCIPHER_BUSY;
67631   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
67632     if( u.ar.iRollback ){
67633       assert( u.ar.desiredAutoCommit==1 );
67634       sqlcipher3RollbackAll(db);
67635       db->autoCommit = 1;
67636     }else if( (rc = sqlcipher3VdbeCheckFk(p, 1))!=SQLCIPHER_OK ){
67637       goto vdbe_return;
67638     }else{
67639       db->autoCommit = (u8)u.ar.desiredAutoCommit;
67640       if( sqlcipher3VdbeHalt(p)==SQLCIPHER_BUSY ){
67641         p->pc = pc;
67642         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
67643         p->rc = rc = SQLCIPHER_BUSY;
67644         goto vdbe_return;
67645       }
67646     }
67647     assert( db->nStatement==0 );
67648     sqlcipher3CloseSavepoints(db);
67649     if( p->rc==SQLCIPHER_OK ){
67650       rc = SQLCIPHER_DONE;
67651     }else{
67652       rc = SQLCIPHER_ERROR;
67653     }
67654     goto vdbe_return;
67655   }else{
67656     sqlcipher3SetString(&p->zErrMsg, db,
67657         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
67658         (u.ar.iRollback)?"cannot rollback - no transaction is active":
67659                    "cannot commit - no transaction is active"));
67660
67661     rc = SQLCIPHER_ERROR;
67662   }
67663   break;
67664 }
67665
67666 /* Opcode: Transaction P1 P2 * * *
67667 **
67668 ** Begin a transaction.  The transaction ends when a Commit or Rollback
67669 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
67670 ** transaction might also be rolled back if an error is encountered.
67671 **
67672 ** P1 is the index of the database file on which the transaction is
67673 ** started.  Index 0 is the main database file and index 1 is the
67674 ** file used for temporary tables.  Indices of 2 or more are used for
67675 ** attached databases.
67676 **
67677 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
67678 ** obtained on the database file when a write-transaction is started.  No
67679 ** other process can start another write transaction while this transaction is
67680 ** underway.  Starting a write transaction also creates a rollback journal. A
67681 ** write transaction must be started before any changes can be made to the
67682 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
67683 ** on the file.
67684 **
67685 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
67686 ** true (this flag is set if the Vdbe may modify more than one row and may
67687 ** throw an ABORT exception), a statement transaction may also be opened.
67688 ** More specifically, a statement transaction is opened iff the database
67689 ** connection is currently not in autocommit mode, or if there are other
67690 ** active statements. A statement transaction allows the affects of this
67691 ** VDBE to be rolled back after an error without having to roll back the
67692 ** entire transaction. If no error is encountered, the statement transaction
67693 ** will automatically commit when the VDBE halts.
67694 **
67695 ** If P2 is zero, then a read-lock is obtained on the database file.
67696 */
67697 case OP_Transaction: {
67698 #if 0  /* local variables moved into u.as */
67699   Btree *pBt;
67700 #endif /* local variables moved into u.as */
67701
67702   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67703   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67704   u.as.pBt = db->aDb[pOp->p1].pBt;
67705
67706   if( u.as.pBt ){
67707     rc = sqlcipher3BtreeBeginTrans(u.as.pBt, pOp->p2);
67708     if( rc==SQLCIPHER_BUSY ){
67709       p->pc = pc;
67710       p->rc = rc = SQLCIPHER_BUSY;
67711       goto vdbe_return;
67712     }
67713     if( rc!=SQLCIPHER_OK ){
67714       goto abort_due_to_error;
67715     }
67716
67717     if( pOp->p2 && p->usesStmtJournal
67718      && (db->autoCommit==0 || db->activeVdbeCnt>1)
67719     ){
67720       assert( sqlcipher3BtreeIsInTrans(u.as.pBt) );
67721       if( p->iStatement==0 ){
67722         assert( db->nStatement>=0 && db->nSavepoint>=0 );
67723         db->nStatement++;
67724         p->iStatement = db->nSavepoint + db->nStatement;
67725       }
67726
67727       rc = sqlcipher3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
67728       if( rc==SQLCIPHER_OK ){
67729         rc = sqlcipher3BtreeBeginStmt(u.as.pBt, p->iStatement);
67730       }
67731
67732       /* Store the current value of the database handles deferred constraint
67733       ** counter. If the statement transaction needs to be rolled back,
67734       ** the value of this counter needs to be restored too.  */
67735       p->nStmtDefCons = db->nDeferredCons;
67736     }
67737   }
67738   break;
67739 }
67740
67741 /* Opcode: ReadCookie P1 P2 P3 * *
67742 **
67743 ** Read cookie number P3 from database P1 and write it into register P2.
67744 ** P3==1 is the schema version.  P3==2 is the database format.
67745 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
67746 ** the main database file and P1==1 is the database file used to store
67747 ** temporary tables.
67748 **
67749 ** There must be a read-lock on the database (either a transaction
67750 ** must be started or there must be an open cursor) before
67751 ** executing this instruction.
67752 */
67753 case OP_ReadCookie: {               /* out2-prerelease */
67754 #if 0  /* local variables moved into u.at */
67755   int iMeta;
67756   int iDb;
67757   int iCookie;
67758 #endif /* local variables moved into u.at */
67759
67760   u.at.iDb = pOp->p1;
67761   u.at.iCookie = pOp->p3;
67762   assert( pOp->p3<SQLCIPHER_N_BTREE_META );
67763   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
67764   assert( db->aDb[u.at.iDb].pBt!=0 );
67765   assert( (p->btreeMask & (((yDbMask)1)<<u.at.iDb))!=0 );
67766
67767   sqlcipher3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
67768   pOut->u.i = u.at.iMeta;
67769   break;
67770 }
67771
67772 /* Opcode: SetCookie P1 P2 P3 * *
67773 **
67774 ** Write the content of register P3 (interpreted as an integer)
67775 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
67776 ** P2==2 is the database format. P2==3 is the recommended pager cache 
67777 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
67778 ** database file used to store temporary tables.
67779 **
67780 ** A transaction must be started before executing this opcode.
67781 */
67782 case OP_SetCookie: {       /* in3 */
67783 #if 0  /* local variables moved into u.au */
67784   Db *pDb;
67785 #endif /* local variables moved into u.au */
67786   assert( pOp->p2<SQLCIPHER_N_BTREE_META );
67787   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67788   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67789   u.au.pDb = &db->aDb[pOp->p1];
67790   assert( u.au.pDb->pBt!=0 );
67791   assert( sqlcipher3SchemaMutexHeld(db, pOp->p1, 0) );
67792   pIn3 = &aMem[pOp->p3];
67793   sqlcipher3VdbeMemIntegerify(pIn3);
67794   /* See note about index shifting on OP_ReadCookie */
67795   rc = sqlcipher3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
67796   if( pOp->p2==BTREE_SCHEMA_VERSION ){
67797     /* When the schema cookie changes, record the new cookie internally */
67798     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
67799     db->flags |= SQLCIPHER_InternChanges;
67800   }else if( pOp->p2==BTREE_FILE_FORMAT ){
67801     /* Record changes in the file format */
67802     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
67803   }
67804   if( pOp->p1==1 ){
67805     /* Invalidate all prepared statements whenever the TEMP database
67806     ** schema is changed.  Ticket #1644 */
67807     sqlcipher3ExpirePreparedStatements(db);
67808     p->expired = 0;
67809   }
67810   break;
67811 }
67812
67813 /* Opcode: VerifyCookie P1 P2 P3 * *
67814 **
67815 ** Check the value of global database parameter number 0 (the
67816 ** schema version) and make sure it is equal to P2 and that the
67817 ** generation counter on the local schema parse equals P3.
67818 **
67819 ** P1 is the database number which is 0 for the main database file
67820 ** and 1 for the file holding temporary tables and some higher number
67821 ** for auxiliary databases.
67822 **
67823 ** The cookie changes its value whenever the database schema changes.
67824 ** This operation is used to detect when that the cookie has changed
67825 ** and that the current process needs to reread the schema.
67826 **
67827 ** Either a transaction needs to have been started or an OP_Open needs
67828 ** to be executed (to establish a read lock) before this opcode is
67829 ** invoked.
67830 */
67831 case OP_VerifyCookie: {
67832 #if 0  /* local variables moved into u.av */
67833   int iMeta;
67834   int iGen;
67835   Btree *pBt;
67836 #endif /* local variables moved into u.av */
67837
67838   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67839   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67840   assert( sqlcipher3SchemaMutexHeld(db, pOp->p1, 0) );
67841   u.av.pBt = db->aDb[pOp->p1].pBt;
67842   if( u.av.pBt ){
67843     sqlcipher3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
67844     u.av.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
67845   }else{
67846     u.av.iGen = u.av.iMeta = 0;
67847   }
67848   if( u.av.iMeta!=pOp->p2 || u.av.iGen!=pOp->p3 ){
67849     sqlcipher3DbFree(db, p->zErrMsg);
67850     p->zErrMsg = sqlcipher3DbStrDup(db, "database schema has changed");
67851     /* If the schema-cookie from the database file matches the cookie
67852     ** stored with the in-memory representation of the schema, do
67853     ** not reload the schema from the database file.
67854     **
67855     ** If virtual-tables are in use, this is not just an optimization.
67856     ** Often, v-tables store their data in other SQLite tables, which
67857     ** are queried from within xNext() and other v-table methods using
67858     ** prepared queries. If such a query is out-of-date, we do not want to
67859     ** discard the database schema, as the user code implementing the
67860     ** v-table would have to be ready for the sqlcipher3_vtab structure itself
67861     ** to be invalidated whenever sqlcipher3_step() is called from within
67862     ** a v-table method.
67863     */
67864     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
67865       sqlcipher3ResetInternalSchema(db, pOp->p1);
67866     }
67867
67868     p->expired = 1;
67869     rc = SQLCIPHER_SCHEMA;
67870   }
67871   break;
67872 }
67873
67874 /* Opcode: OpenRead P1 P2 P3 P4 P5
67875 **
67876 ** Open a read-only cursor for the database table whose root page is
67877 ** P2 in a database file.  The database file is determined by P3. 
67878 ** P3==0 means the main database, P3==1 means the database used for 
67879 ** temporary tables, and P3>1 means used the corresponding attached
67880 ** database.  Give the new cursor an identifier of P1.  The P1
67881 ** values need not be contiguous but all P1 values should be small integers.
67882 ** It is an error for P1 to be negative.
67883 **
67884 ** If P5!=0 then use the content of register P2 as the root page, not
67885 ** the value of P2 itself.
67886 **
67887 ** There will be a read lock on the database whenever there is an
67888 ** open cursor.  If the database was unlocked prior to this instruction
67889 ** then a read lock is acquired as part of this instruction.  A read
67890 ** lock allows other processes to read the database but prohibits
67891 ** any other process from modifying the database.  The read lock is
67892 ** released when all cursors are closed.  If this instruction attempts
67893 ** to get a read lock but fails, the script terminates with an
67894 ** SQLCIPHER_BUSY error code.
67895 **
67896 ** The P4 value may be either an integer (P4_INT32) or a pointer to
67897 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
67898 ** structure, then said structure defines the content and collating 
67899 ** sequence of the index being opened. Otherwise, if P4 is an integer 
67900 ** value, it is set to the number of columns in the table.
67901 **
67902 ** See also OpenWrite.
67903 */
67904 /* Opcode: OpenWrite P1 P2 P3 P4 P5
67905 **
67906 ** Open a read/write cursor named P1 on the table or index whose root
67907 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
67908 ** root page.
67909 **
67910 ** The P4 value may be either an integer (P4_INT32) or a pointer to
67911 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
67912 ** structure, then said structure defines the content and collating 
67913 ** sequence of the index being opened. Otherwise, if P4 is an integer 
67914 ** value, it is set to the number of columns in the table, or to the
67915 ** largest index of any column of the table that is actually used.
67916 **
67917 ** This instruction works just like OpenRead except that it opens the cursor
67918 ** in read/write mode.  For a given table, there can be one or more read-only
67919 ** cursors or a single read/write cursor but not both.
67920 **
67921 ** See also OpenRead.
67922 */
67923 case OP_OpenRead:
67924 case OP_OpenWrite: {
67925 #if 0  /* local variables moved into u.aw */
67926   int nField;
67927   KeyInfo *pKeyInfo;
67928   int p2;
67929   int iDb;
67930   int wrFlag;
67931   Btree *pX;
67932   VdbeCursor *pCur;
67933   Db *pDb;
67934 #endif /* local variables moved into u.aw */
67935
67936   if( p->expired ){
67937     rc = SQLCIPHER_ABORT;
67938     break;
67939   }
67940
67941   u.aw.nField = 0;
67942   u.aw.pKeyInfo = 0;
67943   u.aw.p2 = pOp->p2;
67944   u.aw.iDb = pOp->p3;
67945   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
67946   assert( (p->btreeMask & (((yDbMask)1)<<u.aw.iDb))!=0 );
67947   u.aw.pDb = &db->aDb[u.aw.iDb];
67948   u.aw.pX = u.aw.pDb->pBt;
67949   assert( u.aw.pX!=0 );
67950   if( pOp->opcode==OP_OpenWrite ){
67951     u.aw.wrFlag = 1;
67952     assert( sqlcipher3SchemaMutexHeld(db, u.aw.iDb, 0) );
67953     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
67954       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
67955     }
67956   }else{
67957     u.aw.wrFlag = 0;
67958   }
67959   if( pOp->p5 ){
67960     assert( u.aw.p2>0 );
67961     assert( u.aw.p2<=p->nMem );
67962     pIn2 = &aMem[u.aw.p2];
67963     assert( memIsValid(pIn2) );
67964     assert( (pIn2->flags & MEM_Int)!=0 );
67965     sqlcipher3VdbeMemIntegerify(pIn2);
67966     u.aw.p2 = (int)pIn2->u.i;
67967     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
67968     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
67969     ** If there were a failure, the prepared statement would have halted
67970     ** before reaching this instruction. */
67971     if( NEVER(u.aw.p2<2) ) {
67972       rc = SQLCIPHER_CORRUPT_BKPT;
67973       goto abort_due_to_error;
67974     }
67975   }
67976   if( pOp->p4type==P4_KEYINFO ){
67977     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
67978     u.aw.pKeyInfo->enc = ENC(p->db);
67979     u.aw.nField = u.aw.pKeyInfo->nField+1;
67980   }else if( pOp->p4type==P4_INT32 ){
67981     u.aw.nField = pOp->p4.i;
67982   }
67983   assert( pOp->p1>=0 );
67984   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
67985   if( u.aw.pCur==0 ) goto no_mem;
67986   u.aw.pCur->nullRow = 1;
67987   u.aw.pCur->isOrdered = 1;
67988   rc = sqlcipher3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
67989   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
67990
67991   /* Since it performs no memory allocation or IO, the only value that
67992   ** sqlcipher3BtreeCursor() may return is SQLCIPHER_OK. */
67993   assert( rc==SQLCIPHER_OK );
67994
67995   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
67996   ** SQLite used to check if the root-page flags were sane at this point
67997   ** and report database corruption if they were not, but this check has
67998   ** since moved into the btree layer.  */
67999   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
68000   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
68001   break;
68002 }
68003
68004 /* Opcode: OpenEphemeral P1 P2 * P4 P5
68005 **
68006 ** Open a new cursor P1 to a transient table.
68007 ** The cursor is always opened read/write even if 
68008 ** the main database is read-only.  The ephemeral
68009 ** table is deleted automatically when the cursor is closed.
68010 **
68011 ** P2 is the number of columns in the ephemeral table.
68012 ** The cursor points to a BTree table if P4==0 and to a BTree index
68013 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
68014 ** that defines the format of keys in the index.
68015 **
68016 ** This opcode was once called OpenTemp.  But that created
68017 ** confusion because the term "temp table", might refer either
68018 ** to a TEMP table at the SQL level, or to a table opened by
68019 ** this opcode.  Then this opcode was call OpenVirtual.  But
68020 ** that created confusion with the whole virtual-table idea.
68021 **
68022 ** The P5 parameter can be a mask of the BTREE_* flags defined
68023 ** in btree.h.  These flags control aspects of the operation of
68024 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
68025 ** added automatically.
68026 */
68027 /* Opcode: OpenAutoindex P1 P2 * P4 *
68028 **
68029 ** This opcode works the same as OP_OpenEphemeral.  It has a
68030 ** different name to distinguish its use.  Tables created using
68031 ** by this opcode will be used for automatically created transient
68032 ** indices in joins.
68033 */
68034 case OP_OpenAutoindex: 
68035 case OP_OpenEphemeral: {
68036 #if 0  /* local variables moved into u.ax */
68037   VdbeCursor *pCx;
68038 #endif /* local variables moved into u.ax */
68039   static const int vfsFlags =
68040       SQLCIPHER_OPEN_READWRITE |
68041       SQLCIPHER_OPEN_CREATE |
68042       SQLCIPHER_OPEN_EXCLUSIVE |
68043       SQLCIPHER_OPEN_DELETEONCLOSE |
68044       SQLCIPHER_OPEN_TRANSIENT_DB;
68045
68046   assert( pOp->p1>=0 );
68047   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68048   if( u.ax.pCx==0 ) goto no_mem;
68049   u.ax.pCx->nullRow = 1;
68050   rc = sqlcipher3BtreeOpen(db->pVfs, 0, db, &u.ax.pCx->pBt,
68051                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
68052   if( rc==SQLCIPHER_OK ){
68053     rc = sqlcipher3BtreeBeginTrans(u.ax.pCx->pBt, 1);
68054   }
68055   if( rc==SQLCIPHER_OK ){
68056     /* If a transient index is required, create it by calling
68057     ** sqlcipher3BtreeCreateTable() with the BTREE_BLOBKEY flag before
68058     ** opening it. If a transient table is required, just use the
68059     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
68060     */
68061     if( pOp->p4.pKeyInfo ){
68062       int pgno;
68063       assert( pOp->p4type==P4_KEYINFO );
68064       rc = sqlcipher3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
68065       if( rc==SQLCIPHER_OK ){
68066         assert( pgno==MASTER_ROOT+1 );
68067         rc = sqlcipher3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
68068                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
68069         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68070         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
68071       }
68072       u.ax.pCx->isTable = 0;
68073     }else{
68074       rc = sqlcipher3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
68075       u.ax.pCx->isTable = 1;
68076     }
68077   }
68078   u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
68079   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
68080   break;
68081 }
68082
68083 /* Opcode: OpenSorter P1 P2 * P4 *
68084 **
68085 ** This opcode works like OP_OpenEphemeral except that it opens
68086 ** a transient index that is specifically designed to sort large
68087 ** tables using an external merge-sort algorithm.
68088 */
68089 case OP_SorterOpen: {
68090 #if 0  /* local variables moved into u.ay */
68091   VdbeCursor *pCx;
68092 #endif /* local variables moved into u.ay */
68093 #ifndef SQLCIPHER_OMIT_MERGE_SORT
68094   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68095   if( u.ay.pCx==0 ) goto no_mem;
68096   u.ay.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68097   u.ay.pCx->pKeyInfo->enc = ENC(p->db);
68098   u.ay.pCx->isSorter = 1;
68099   rc = sqlcipher3VdbeSorterInit(db, u.ay.pCx);
68100 #else
68101   pOp->opcode = OP_OpenEphemeral;
68102   pc--;
68103 #endif
68104   break;
68105 }
68106
68107 /* Opcode: OpenPseudo P1 P2 P3 * *
68108 **
68109 ** Open a new cursor that points to a fake table that contains a single
68110 ** row of data.  The content of that one row in the content of memory
68111 ** register P2.  In other words, cursor P1 becomes an alias for the 
68112 ** MEM_Blob content contained in register P2.
68113 **
68114 ** A pseudo-table created by this opcode is used to hold a single
68115 ** row output from the sorter so that the row can be decomposed into
68116 ** individual columns using the OP_Column opcode.  The OP_Column opcode
68117 ** is the only cursor opcode that works with a pseudo-table.
68118 **
68119 ** P3 is the number of fields in the records that will be stored by
68120 ** the pseudo-table.
68121 */
68122 case OP_OpenPseudo: {
68123 #if 0  /* local variables moved into u.az */
68124   VdbeCursor *pCx;
68125 #endif /* local variables moved into u.az */
68126
68127   assert( pOp->p1>=0 );
68128   u.az.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
68129   if( u.az.pCx==0 ) goto no_mem;
68130   u.az.pCx->nullRow = 1;
68131   u.az.pCx->pseudoTableReg = pOp->p2;
68132   u.az.pCx->isTable = 1;
68133   u.az.pCx->isIndex = 0;
68134   break;
68135 }
68136
68137 /* Opcode: Close P1 * * * *
68138 **
68139 ** Close a cursor previously opened as P1.  If P1 is not
68140 ** currently open, this instruction is a no-op.
68141 */
68142 case OP_Close: {
68143   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68144   sqlcipher3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
68145   p->apCsr[pOp->p1] = 0;
68146   break;
68147 }
68148
68149 /* Opcode: SeekGe P1 P2 P3 P4 *
68150 **
68151 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
68152 ** use the value in register P3 as the key.  If cursor P1 refers 
68153 ** to an SQL index, then P3 is the first in an array of P4 registers 
68154 ** that are used as an unpacked index key. 
68155 **
68156 ** Reposition cursor P1 so that  it points to the smallest entry that 
68157 ** is greater than or equal to the key value. If there are no records 
68158 ** greater than or equal to the key and P2 is not zero, then jump to P2.
68159 **
68160 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
68161 */
68162 /* Opcode: SeekGt P1 P2 P3 P4 *
68163 **
68164 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
68165 ** use the value in register P3 as a key. If cursor P1 refers 
68166 ** to an SQL index, then P3 is the first in an array of P4 registers 
68167 ** that are used as an unpacked index key. 
68168 **
68169 ** Reposition cursor P1 so that  it points to the smallest entry that 
68170 ** is greater than the key value. If there are no records greater than 
68171 ** the key and P2 is not zero, then jump to P2.
68172 **
68173 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
68174 */
68175 /* Opcode: SeekLt P1 P2 P3 P4 * 
68176 **
68177 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
68178 ** use the value in register P3 as a key. If cursor P1 refers 
68179 ** to an SQL index, then P3 is the first in an array of P4 registers 
68180 ** that are used as an unpacked index key. 
68181 **
68182 ** Reposition cursor P1 so that  it points to the largest entry that 
68183 ** is less than the key value. If there are no records less than 
68184 ** the key and P2 is not zero, then jump to P2.
68185 **
68186 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
68187 */
68188 /* Opcode: SeekLe P1 P2 P3 P4 *
68189 **
68190 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
68191 ** use the value in register P3 as a key. If cursor P1 refers 
68192 ** to an SQL index, then P3 is the first in an array of P4 registers 
68193 ** that are used as an unpacked index key. 
68194 **
68195 ** Reposition cursor P1 so that it points to the largest entry that 
68196 ** is less than or equal to the key value. If there are no records 
68197 ** less than or equal to the key and P2 is not zero, then jump to P2.
68198 **
68199 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
68200 */
68201 case OP_SeekLt:         /* jump, in3 */
68202 case OP_SeekLe:         /* jump, in3 */
68203 case OP_SeekGe:         /* jump, in3 */
68204 case OP_SeekGt: {       /* jump, in3 */
68205 #if 0  /* local variables moved into u.ba */
68206   int res;
68207   int oc;
68208   VdbeCursor *pC;
68209   UnpackedRecord r;
68210   int nField;
68211   i64 iKey;      /* The rowid we are to seek to */
68212 #endif /* local variables moved into u.ba */
68213
68214   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68215   assert( pOp->p2!=0 );
68216   u.ba.pC = p->apCsr[pOp->p1];
68217   assert( u.ba.pC!=0 );
68218   assert( u.ba.pC->pseudoTableReg==0 );
68219   assert( OP_SeekLe == OP_SeekLt+1 );
68220   assert( OP_SeekGe == OP_SeekLt+2 );
68221   assert( OP_SeekGt == OP_SeekLt+3 );
68222   assert( u.ba.pC->isOrdered );
68223   if( ALWAYS(u.ba.pC->pCursor!=0) ){
68224     u.ba.oc = pOp->opcode;
68225     u.ba.pC->nullRow = 0;
68226     if( u.ba.pC->isTable ){
68227       /* The input value in P3 might be of any type: integer, real, string,
68228       ** blob, or NULL.  But it needs to be an integer before we can do
68229       ** the seek, so covert it. */
68230       pIn3 = &aMem[pOp->p3];
68231       applyNumericAffinity(pIn3);
68232       u.ba.iKey = sqlcipher3VdbeIntValue(pIn3);
68233       u.ba.pC->rowidIsValid = 0;
68234
68235       /* If the P3 value could not be converted into an integer without
68236       ** loss of information, then special processing is required... */
68237       if( (pIn3->flags & MEM_Int)==0 ){
68238         if( (pIn3->flags & MEM_Real)==0 ){
68239           /* If the P3 value cannot be converted into any kind of a number,
68240           ** then the seek is not possible, so jump to P2 */
68241           pc = pOp->p2 - 1;
68242           break;
68243         }
68244         /* If we reach this point, then the P3 value must be a floating
68245         ** point number. */
68246         assert( (pIn3->flags & MEM_Real)!=0 );
68247
68248         if( u.ba.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.ba.iKey || pIn3->r>0) ){
68249           /* The P3 value is too large in magnitude to be expressed as an
68250           ** integer. */
68251           u.ba.res = 1;
68252           if( pIn3->r<0 ){
68253             if( u.ba.oc>=OP_SeekGe ){  assert( u.ba.oc==OP_SeekGe || u.ba.oc==OP_SeekGt );
68254               rc = sqlcipher3BtreeFirst(u.ba.pC->pCursor, &u.ba.res);
68255               if( rc!=SQLCIPHER_OK ) goto abort_due_to_error;
68256             }
68257           }else{
68258             if( u.ba.oc<=OP_SeekLe ){  assert( u.ba.oc==OP_SeekLt || u.ba.oc==OP_SeekLe );
68259               rc = sqlcipher3BtreeLast(u.ba.pC->pCursor, &u.ba.res);
68260               if( rc!=SQLCIPHER_OK ) goto abort_due_to_error;
68261             }
68262           }
68263           if( u.ba.res ){
68264             pc = pOp->p2 - 1;
68265           }
68266           break;
68267         }else if( u.ba.oc==OP_SeekLt || u.ba.oc==OP_SeekGe ){
68268           /* Use the ceiling() function to convert real->int */
68269           if( pIn3->r > (double)u.ba.iKey ) u.ba.iKey++;
68270         }else{
68271           /* Use the floor() function to convert real->int */
68272           assert( u.ba.oc==OP_SeekLe || u.ba.oc==OP_SeekGt );
68273           if( pIn3->r < (double)u.ba.iKey ) u.ba.iKey--;
68274         }
68275       }
68276       rc = sqlcipher3BtreeMovetoUnpacked(u.ba.pC->pCursor, 0, (u64)u.ba.iKey, 0, &u.ba.res);
68277       if( rc!=SQLCIPHER_OK ){
68278         goto abort_due_to_error;
68279       }
68280       if( u.ba.res==0 ){
68281         u.ba.pC->rowidIsValid = 1;
68282         u.ba.pC->lastRowid = u.ba.iKey;
68283       }
68284     }else{
68285       u.ba.nField = pOp->p4.i;
68286       assert( pOp->p4type==P4_INT32 );
68287       assert( u.ba.nField>0 );
68288       u.ba.r.pKeyInfo = u.ba.pC->pKeyInfo;
68289       u.ba.r.nField = (u16)u.ba.nField;
68290
68291       /* The next line of code computes as follows, only faster:
68292       **   if( u.ba.oc==OP_SeekGt || u.ba.oc==OP_SeekLe ){
68293       **     u.ba.r.flags = UNPACKED_INCRKEY;
68294       **   }else{
68295       **     u.ba.r.flags = 0;
68296       **   }
68297       */
68298       u.ba.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.ba.oc - OP_SeekLt)));
68299       assert( u.ba.oc!=OP_SeekGt || u.ba.r.flags==UNPACKED_INCRKEY );
68300       assert( u.ba.oc!=OP_SeekLe || u.ba.r.flags==UNPACKED_INCRKEY );
68301       assert( u.ba.oc!=OP_SeekGe || u.ba.r.flags==0 );
68302       assert( u.ba.oc!=OP_SeekLt || u.ba.r.flags==0 );
68303
68304       u.ba.r.aMem = &aMem[pOp->p3];
68305 #ifdef SQLCIPHER_DEBUG
68306       { int i; for(i=0; i<u.ba.r.nField; i++) assert( memIsValid(&u.ba.r.aMem[i]) ); }
68307 #endif
68308       ExpandBlob(u.ba.r.aMem);
68309       rc = sqlcipher3BtreeMovetoUnpacked(u.ba.pC->pCursor, &u.ba.r, 0, 0, &u.ba.res);
68310       if( rc!=SQLCIPHER_OK ){
68311         goto abort_due_to_error;
68312       }
68313       u.ba.pC->rowidIsValid = 0;
68314     }
68315     u.ba.pC->deferredMoveto = 0;
68316     u.ba.pC->cacheStatus = CACHE_STALE;
68317 #ifdef SQLCIPHER_TEST
68318     sqlcipher3_search_count++;
68319 #endif
68320     if( u.ba.oc>=OP_SeekGe ){  assert( u.ba.oc==OP_SeekGe || u.ba.oc==OP_SeekGt );
68321       if( u.ba.res<0 || (u.ba.res==0 && u.ba.oc==OP_SeekGt) ){
68322         rc = sqlcipher3BtreeNext(u.ba.pC->pCursor, &u.ba.res);
68323         if( rc!=SQLCIPHER_OK ) goto abort_due_to_error;
68324         u.ba.pC->rowidIsValid = 0;
68325       }else{
68326         u.ba.res = 0;
68327       }
68328     }else{
68329       assert( u.ba.oc==OP_SeekLt || u.ba.oc==OP_SeekLe );
68330       if( u.ba.res>0 || (u.ba.res==0 && u.ba.oc==OP_SeekLt) ){
68331         rc = sqlcipher3BtreePrevious(u.ba.pC->pCursor, &u.ba.res);
68332         if( rc!=SQLCIPHER_OK ) goto abort_due_to_error;
68333         u.ba.pC->rowidIsValid = 0;
68334       }else{
68335         /* u.ba.res might be negative because the table is empty.  Check to
68336         ** see if this is the case.
68337         */
68338         u.ba.res = sqlcipher3BtreeEof(u.ba.pC->pCursor);
68339       }
68340     }
68341     assert( pOp->p2>0 );
68342     if( u.ba.res ){
68343       pc = pOp->p2 - 1;
68344     }
68345   }else{
68346     /* This happens when attempting to open the sqlcipher3_master table
68347     ** for read access returns SQLCIPHER_EMPTY. In this case always
68348     ** take the jump (since there are no records in the table).
68349     */
68350     pc = pOp->p2 - 1;
68351   }
68352   break;
68353 }
68354
68355 /* Opcode: Seek P1 P2 * * *
68356 **
68357 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
68358 ** for P1 to move so that it points to the rowid given by P2.
68359 **
68360 ** This is actually a deferred seek.  Nothing actually happens until
68361 ** the cursor is used to read a record.  That way, if no reads
68362 ** occur, no unnecessary I/O happens.
68363 */
68364 case OP_Seek: {    /* in2 */
68365 #if 0  /* local variables moved into u.bb */
68366   VdbeCursor *pC;
68367 #endif /* local variables moved into u.bb */
68368
68369   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68370   u.bb.pC = p->apCsr[pOp->p1];
68371   assert( u.bb.pC!=0 );
68372   if( ALWAYS(u.bb.pC->pCursor!=0) ){
68373     assert( u.bb.pC->isTable );
68374     u.bb.pC->nullRow = 0;
68375     pIn2 = &aMem[pOp->p2];
68376     u.bb.pC->movetoTarget = sqlcipher3VdbeIntValue(pIn2);
68377     u.bb.pC->rowidIsValid = 0;
68378     u.bb.pC->deferredMoveto = 1;
68379   }
68380   break;
68381 }
68382   
68383
68384 /* Opcode: Found P1 P2 P3 P4 *
68385 **
68386 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
68387 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
68388 ** record.
68389 **
68390 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
68391 ** is a prefix of any entry in P1 then a jump is made to P2 and
68392 ** P1 is left pointing at the matching entry.
68393 */
68394 /* Opcode: NotFound P1 P2 P3 P4 *
68395 **
68396 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
68397 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
68398 ** record.
68399 ** 
68400 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
68401 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
68402 ** does contain an entry whose prefix matches the P3/P4 record then control
68403 ** falls through to the next instruction and P1 is left pointing at the
68404 ** matching entry.
68405 **
68406 ** See also: Found, NotExists, IsUnique
68407 */
68408 case OP_NotFound:       /* jump, in3 */
68409 case OP_Found: {        /* jump, in3 */
68410 #if 0  /* local variables moved into u.bc */
68411   int alreadyExists;
68412   VdbeCursor *pC;
68413   int res;
68414   char *pFree;
68415   UnpackedRecord *pIdxKey;
68416   UnpackedRecord r;
68417   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
68418 #endif /* local variables moved into u.bc */
68419
68420 #ifdef SQLCIPHER_TEST
68421   sqlcipher3_found_count++;
68422 #endif
68423
68424   u.bc.alreadyExists = 0;
68425   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68426   assert( pOp->p4type==P4_INT32 );
68427   u.bc.pC = p->apCsr[pOp->p1];
68428   assert( u.bc.pC!=0 );
68429   pIn3 = &aMem[pOp->p3];
68430   if( ALWAYS(u.bc.pC->pCursor!=0) ){
68431
68432     assert( u.bc.pC->isTable==0 );
68433     if( pOp->p4.i>0 ){
68434       u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
68435       u.bc.r.nField = (u16)pOp->p4.i;
68436       u.bc.r.aMem = pIn3;
68437 #ifdef SQLCIPHER_DEBUG
68438       { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
68439 #endif
68440       u.bc.r.flags = UNPACKED_PREFIX_MATCH;
68441       u.bc.pIdxKey = &u.bc.r;
68442     }else{
68443       u.bc.pIdxKey = sqlcipher3VdbeAllocUnpackedRecord(
68444           u.bc.pC->pKeyInfo, u.bc.aTempRec, sizeof(u.bc.aTempRec), &u.bc.pFree
68445       );
68446       if( u.bc.pIdxKey==0 ) goto no_mem;
68447       assert( pIn3->flags & MEM_Blob );
68448       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
68449       sqlcipher3VdbeRecordUnpack(u.bc.pC->pKeyInfo, pIn3->n, pIn3->z, u.bc.pIdxKey);
68450       u.bc.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
68451     }
68452     rc = sqlcipher3BtreeMovetoUnpacked(u.bc.pC->pCursor, u.bc.pIdxKey, 0, 0, &u.bc.res);
68453     if( pOp->p4.i==0 ){
68454       sqlcipher3DbFree(db, u.bc.pFree);
68455     }
68456     if( rc!=SQLCIPHER_OK ){
68457       break;
68458     }
68459     u.bc.alreadyExists = (u.bc.res==0);
68460     u.bc.pC->deferredMoveto = 0;
68461     u.bc.pC->cacheStatus = CACHE_STALE;
68462   }
68463   if( pOp->opcode==OP_Found ){
68464     if( u.bc.alreadyExists ) pc = pOp->p2 - 1;
68465   }else{
68466     if( !u.bc.alreadyExists ) pc = pOp->p2 - 1;
68467   }
68468   break;
68469 }
68470
68471 /* Opcode: IsUnique P1 P2 P3 P4 *
68472 **
68473 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
68474 ** no data and where the key are records generated by OP_MakeRecord with
68475 ** the list field being the integer ROWID of the entry that the index
68476 ** entry refers to.
68477 **
68478 ** The P3 register contains an integer record number. Call this record 
68479 ** number R. Register P4 is the first in a set of N contiguous registers
68480 ** that make up an unpacked index key that can be used with cursor P1.
68481 ** The value of N can be inferred from the cursor. N includes the rowid
68482 ** value appended to the end of the index record. This rowid value may
68483 ** or may not be the same as R.
68484 **
68485 ** If any of the N registers beginning with register P4 contains a NULL
68486 ** value, jump immediately to P2.
68487 **
68488 ** Otherwise, this instruction checks if cursor P1 contains an entry
68489 ** where the first (N-1) fields match but the rowid value at the end
68490 ** of the index entry is not R. If there is no such entry, control jumps
68491 ** to instruction P2. Otherwise, the rowid of the conflicting index
68492 ** entry is copied to register P3 and control falls through to the next
68493 ** instruction.
68494 **
68495 ** See also: NotFound, NotExists, Found
68496 */
68497 case OP_IsUnique: {        /* jump, in3 */
68498 #if 0  /* local variables moved into u.bd */
68499   u16 ii;
68500   VdbeCursor *pCx;
68501   BtCursor *pCrsr;
68502   u16 nField;
68503   Mem *aMx;
68504   UnpackedRecord r;                  /* B-Tree index search key */
68505   i64 R;                             /* Rowid stored in register P3 */
68506 #endif /* local variables moved into u.bd */
68507
68508   pIn3 = &aMem[pOp->p3];
68509   u.bd.aMx = &aMem[pOp->p4.i];
68510   /* Assert that the values of parameters P1 and P4 are in range. */
68511   assert( pOp->p4type==P4_INT32 );
68512   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
68513   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68514
68515   /* Find the index cursor. */
68516   u.bd.pCx = p->apCsr[pOp->p1];
68517   assert( u.bd.pCx->deferredMoveto==0 );
68518   u.bd.pCx->seekResult = 0;
68519   u.bd.pCx->cacheStatus = CACHE_STALE;
68520   u.bd.pCrsr = u.bd.pCx->pCursor;
68521
68522   /* If any of the values are NULL, take the jump. */
68523   u.bd.nField = u.bd.pCx->pKeyInfo->nField;
68524   for(u.bd.ii=0; u.bd.ii<u.bd.nField; u.bd.ii++){
68525     if( u.bd.aMx[u.bd.ii].flags & MEM_Null ){
68526       pc = pOp->p2 - 1;
68527       u.bd.pCrsr = 0;
68528       break;
68529     }
68530   }
68531   assert( (u.bd.aMx[u.bd.nField].flags & MEM_Null)==0 );
68532
68533   if( u.bd.pCrsr!=0 ){
68534     /* Populate the index search key. */
68535     u.bd.r.pKeyInfo = u.bd.pCx->pKeyInfo;
68536     u.bd.r.nField = u.bd.nField + 1;
68537     u.bd.r.flags = UNPACKED_PREFIX_SEARCH;
68538     u.bd.r.aMem = u.bd.aMx;
68539 #ifdef SQLCIPHER_DEBUG
68540     { int i; for(i=0; i<u.bd.r.nField; i++) assert( memIsValid(&u.bd.r.aMem[i]) ); }
68541 #endif
68542
68543     /* Extract the value of u.bd.R from register P3. */
68544     sqlcipher3VdbeMemIntegerify(pIn3);
68545     u.bd.R = pIn3->u.i;
68546
68547     /* Search the B-Tree index. If no conflicting record is found, jump
68548     ** to P2. Otherwise, copy the rowid of the conflicting record to
68549     ** register P3 and fall through to the next instruction.  */
68550     rc = sqlcipher3BtreeMovetoUnpacked(u.bd.pCrsr, &u.bd.r, 0, 0, &u.bd.pCx->seekResult);
68551     if( (u.bd.r.flags & UNPACKED_PREFIX_SEARCH) || u.bd.r.rowid==u.bd.R ){
68552       pc = pOp->p2 - 1;
68553     }else{
68554       pIn3->u.i = u.bd.r.rowid;
68555     }
68556   }
68557   break;
68558 }
68559
68560 /* Opcode: NotExists P1 P2 P3 * *
68561 **
68562 ** Use the content of register P3 as an integer key.  If a record 
68563 ** with that key does not exist in table of P1, then jump to P2. 
68564 ** If the record does exist, then fall through.  The cursor is left 
68565 ** pointing to the record if it exists.
68566 **
68567 ** The difference between this operation and NotFound is that this
68568 ** operation assumes the key is an integer and that P1 is a table whereas
68569 ** NotFound assumes key is a blob constructed from MakeRecord and
68570 ** P1 is an index.
68571 **
68572 ** See also: Found, NotFound, IsUnique
68573 */
68574 case OP_NotExists: {        /* jump, in3 */
68575 #if 0  /* local variables moved into u.be */
68576   VdbeCursor *pC;
68577   BtCursor *pCrsr;
68578   int res;
68579   u64 iKey;
68580 #endif /* local variables moved into u.be */
68581
68582   pIn3 = &aMem[pOp->p3];
68583   assert( pIn3->flags & MEM_Int );
68584   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68585   u.be.pC = p->apCsr[pOp->p1];
68586   assert( u.be.pC!=0 );
68587   assert( u.be.pC->isTable );
68588   assert( u.be.pC->pseudoTableReg==0 );
68589   u.be.pCrsr = u.be.pC->pCursor;
68590   if( ALWAYS(u.be.pCrsr!=0) ){
68591     u.be.res = 0;
68592     u.be.iKey = pIn3->u.i;
68593     rc = sqlcipher3BtreeMovetoUnpacked(u.be.pCrsr, 0, u.be.iKey, 0, &u.be.res);
68594     u.be.pC->lastRowid = pIn3->u.i;
68595     u.be.pC->rowidIsValid = u.be.res==0 ?1:0;
68596     u.be.pC->nullRow = 0;
68597     u.be.pC->cacheStatus = CACHE_STALE;
68598     u.be.pC->deferredMoveto = 0;
68599     if( u.be.res!=0 ){
68600       pc = pOp->p2 - 1;
68601       assert( u.be.pC->rowidIsValid==0 );
68602     }
68603     u.be.pC->seekResult = u.be.res;
68604   }else{
68605     /* This happens when an attempt to open a read cursor on the
68606     ** sqlcipher_master table returns SQLCIPHER_EMPTY.
68607     */
68608     pc = pOp->p2 - 1;
68609     assert( u.be.pC->rowidIsValid==0 );
68610     u.be.pC->seekResult = 0;
68611   }
68612   break;
68613 }
68614
68615 /* Opcode: Sequence P1 P2 * * *
68616 **
68617 ** Find the next available sequence number for cursor P1.
68618 ** Write the sequence number into register P2.
68619 ** The sequence number on the cursor is incremented after this
68620 ** instruction.  
68621 */
68622 case OP_Sequence: {           /* out2-prerelease */
68623   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68624   assert( p->apCsr[pOp->p1]!=0 );
68625   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
68626   break;
68627 }
68628
68629
68630 /* Opcode: NewRowid P1 P2 P3 * *
68631 **
68632 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
68633 ** The record number is not previously used as a key in the database
68634 ** table that cursor P1 points to.  The new record number is written
68635 ** written to register P2.
68636 **
68637 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
68638 ** the largest previously generated record number. No new record numbers are
68639 ** allowed to be less than this value. When this value reaches its maximum, 
68640 ** an SQLCIPHER_FULL error is generated. The P3 register is updated with the '
68641 ** generated record number. This P3 mechanism is used to help implement the
68642 ** AUTOINCREMENT feature.
68643 */
68644 case OP_NewRowid: {           /* out2-prerelease */
68645 #if 0  /* local variables moved into u.bf */
68646   i64 v;                 /* The new rowid */
68647   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
68648   int res;               /* Result of an sqlcipher3BtreeLast() */
68649   int cnt;               /* Counter to limit the number of searches */
68650   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
68651   VdbeFrame *pFrame;     /* Root frame of VDBE */
68652 #endif /* local variables moved into u.bf */
68653
68654   u.bf.v = 0;
68655   u.bf.res = 0;
68656   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68657   u.bf.pC = p->apCsr[pOp->p1];
68658   assert( u.bf.pC!=0 );
68659   if( NEVER(u.bf.pC->pCursor==0) ){
68660     /* The zero initialization above is all that is needed */
68661   }else{
68662     /* The next rowid or record number (different terms for the same
68663     ** thing) is obtained in a two-step algorithm.
68664     **
68665     ** First we attempt to find the largest existing rowid and add one
68666     ** to that.  But if the largest existing rowid is already the maximum
68667     ** positive integer, we have to fall through to the second
68668     ** probabilistic algorithm
68669     **
68670     ** The second algorithm is to select a rowid at random and see if
68671     ** it already exists in the table.  If it does not exist, we have
68672     ** succeeded.  If the random rowid does exist, we select a new one
68673     ** and try again, up to 100 times.
68674     */
68675     assert( u.bf.pC->isTable );
68676
68677 #ifdef SQLCIPHER_32BIT_ROWID
68678 #   define MAX_ROWID 0x7fffffff
68679 #else
68680     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
68681     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
68682     ** to provide the constant while making all compilers happy.
68683     */
68684 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
68685 #endif
68686
68687     if( !u.bf.pC->useRandomRowid ){
68688       u.bf.v = sqlcipher3BtreeGetCachedRowid(u.bf.pC->pCursor);
68689       if( u.bf.v==0 ){
68690         rc = sqlcipher3BtreeLast(u.bf.pC->pCursor, &u.bf.res);
68691         if( rc!=SQLCIPHER_OK ){
68692           goto abort_due_to_error;
68693         }
68694         if( u.bf.res ){
68695           u.bf.v = 1;   /* IMP: R-61914-48074 */
68696         }else{
68697           assert( sqlcipher3BtreeCursorIsValid(u.bf.pC->pCursor) );
68698           rc = sqlcipher3BtreeKeySize(u.bf.pC->pCursor, &u.bf.v);
68699           assert( rc==SQLCIPHER_OK );   /* Cannot fail following BtreeLast() */
68700           if( u.bf.v==MAX_ROWID ){
68701             u.bf.pC->useRandomRowid = 1;
68702           }else{
68703             u.bf.v++;   /* IMP: R-29538-34987 */
68704           }
68705         }
68706       }
68707
68708 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
68709       if( pOp->p3 ){
68710         /* Assert that P3 is a valid memory cell. */
68711         assert( pOp->p3>0 );
68712         if( p->pFrame ){
68713           for(u.bf.pFrame=p->pFrame; u.bf.pFrame->pParent; u.bf.pFrame=u.bf.pFrame->pParent);
68714           /* Assert that P3 is a valid memory cell. */
68715           assert( pOp->p3<=u.bf.pFrame->nMem );
68716           u.bf.pMem = &u.bf.pFrame->aMem[pOp->p3];
68717         }else{
68718           /* Assert that P3 is a valid memory cell. */
68719           assert( pOp->p3<=p->nMem );
68720           u.bf.pMem = &aMem[pOp->p3];
68721           memAboutToChange(p, u.bf.pMem);
68722         }
68723         assert( memIsValid(u.bf.pMem) );
68724
68725         REGISTER_TRACE(pOp->p3, u.bf.pMem);
68726         sqlcipher3VdbeMemIntegerify(u.bf.pMem);
68727         assert( (u.bf.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
68728         if( u.bf.pMem->u.i==MAX_ROWID || u.bf.pC->useRandomRowid ){
68729           rc = SQLCIPHER_FULL;   /* IMP: R-12275-61338 */
68730           goto abort_due_to_error;
68731         }
68732         if( u.bf.v<u.bf.pMem->u.i+1 ){
68733           u.bf.v = u.bf.pMem->u.i + 1;
68734         }
68735         u.bf.pMem->u.i = u.bf.v;
68736       }
68737 #endif
68738
68739       sqlcipher3BtreeSetCachedRowid(u.bf.pC->pCursor, u.bf.v<MAX_ROWID ? u.bf.v+1 : 0);
68740     }
68741     if( u.bf.pC->useRandomRowid ){
68742       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
68743       ** largest possible integer (9223372036854775807) then the database
68744       ** engine starts picking positive candidate ROWIDs at random until
68745       ** it finds one that is not previously used. */
68746       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
68747                              ** an AUTOINCREMENT table. */
68748       /* on the first attempt, simply do one more than previous */
68749       u.bf.v = lastRowid;
68750       u.bf.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
68751       u.bf.v++; /* ensure non-zero */
68752       u.bf.cnt = 0;
68753       while(   ((rc = sqlcipher3BtreeMovetoUnpacked(u.bf.pC->pCursor, 0, (u64)u.bf.v,
68754                                                  0, &u.bf.res))==SQLCIPHER_OK)
68755             && (u.bf.res==0)
68756             && (++u.bf.cnt<100)){
68757         /* collision - try another random rowid */
68758         sqlcipher3_randomness(sizeof(u.bf.v), &u.bf.v);
68759         if( u.bf.cnt<5 ){
68760           /* try "small" random rowids for the initial attempts */
68761           u.bf.v &= 0xffffff;
68762         }else{
68763           u.bf.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
68764         }
68765         u.bf.v++; /* ensure non-zero */
68766       }
68767       if( rc==SQLCIPHER_OK && u.bf.res==0 ){
68768         rc = SQLCIPHER_FULL;   /* IMP: R-38219-53002 */
68769         goto abort_due_to_error;
68770       }
68771       assert( u.bf.v>0 );  /* EV: R-40812-03570 */
68772     }
68773     u.bf.pC->rowidIsValid = 0;
68774     u.bf.pC->deferredMoveto = 0;
68775     u.bf.pC->cacheStatus = CACHE_STALE;
68776   }
68777   pOut->u.i = u.bf.v;
68778   break;
68779 }
68780
68781 /* Opcode: Insert P1 P2 P3 P4 P5
68782 **
68783 ** Write an entry into the table of cursor P1.  A new entry is
68784 ** created if it doesn't already exist or the data for an existing
68785 ** entry is overwritten.  The data is the value MEM_Blob stored in register
68786 ** number P2. The key is stored in register P3. The key must
68787 ** be a MEM_Int.
68788 **
68789 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
68790 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
68791 ** then rowid is stored for subsequent return by the
68792 ** sqlcipher3_last_insert_rowid() function (otherwise it is unmodified).
68793 **
68794 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
68795 ** the last seek operation (OP_NotExists) was a success, then this
68796 ** operation will not attempt to find the appropriate row before doing
68797 ** the insert but will instead overwrite the row that the cursor is
68798 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
68799 ** has already positioned the cursor correctly.  This is an optimization
68800 ** that boosts performance by avoiding redundant seeks.
68801 **
68802 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
68803 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
68804 ** is part of an INSERT operation.  The difference is only important to
68805 ** the update hook.
68806 **
68807 ** Parameter P4 may point to a string containing the table-name, or
68808 ** may be NULL. If it is not NULL, then the update-hook 
68809 ** (sqlcipher3.xUpdateCallback) is invoked following a successful insert.
68810 **
68811 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
68812 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
68813 ** and register P2 becomes ephemeral.  If the cursor is changed, the
68814 ** value of register P2 will then change.  Make sure this does not
68815 ** cause any problems.)
68816 **
68817 ** This instruction only works on tables.  The equivalent instruction
68818 ** for indices is OP_IdxInsert.
68819 */
68820 /* Opcode: InsertInt P1 P2 P3 P4 P5
68821 **
68822 ** This works exactly like OP_Insert except that the key is the
68823 ** integer value P3, not the value of the integer stored in register P3.
68824 */
68825 case OP_Insert: 
68826 case OP_InsertInt: {
68827 #if 0  /* local variables moved into u.bg */
68828   Mem *pData;       /* MEM cell holding data for the record to be inserted */
68829   Mem *pKey;        /* MEM cell holding key  for the record */
68830   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
68831   VdbeCursor *pC;   /* Cursor to table into which insert is written */
68832   int nZero;        /* Number of zero-bytes to append */
68833   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
68834   const char *zDb;  /* database name - used by the update hook */
68835   const char *zTbl; /* Table name - used by the opdate hook */
68836   int op;           /* Opcode for update hook: SQLCIPHER_UPDATE or SQLCIPHER_INSERT */
68837 #endif /* local variables moved into u.bg */
68838
68839   u.bg.pData = &aMem[pOp->p2];
68840   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68841   assert( memIsValid(u.bg.pData) );
68842   u.bg.pC = p->apCsr[pOp->p1];
68843   assert( u.bg.pC!=0 );
68844   assert( u.bg.pC->pCursor!=0 );
68845   assert( u.bg.pC->pseudoTableReg==0 );
68846   assert( u.bg.pC->isTable );
68847   REGISTER_TRACE(pOp->p2, u.bg.pData);
68848
68849   if( pOp->opcode==OP_Insert ){
68850     u.bg.pKey = &aMem[pOp->p3];
68851     assert( u.bg.pKey->flags & MEM_Int );
68852     assert( memIsValid(u.bg.pKey) );
68853     REGISTER_TRACE(pOp->p3, u.bg.pKey);
68854     u.bg.iKey = u.bg.pKey->u.i;
68855   }else{
68856     assert( pOp->opcode==OP_InsertInt );
68857     u.bg.iKey = pOp->p3;
68858   }
68859
68860   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
68861   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bg.iKey;
68862   if( u.bg.pData->flags & MEM_Null ){
68863     u.bg.pData->z = 0;
68864     u.bg.pData->n = 0;
68865   }else{
68866     assert( u.bg.pData->flags & (MEM_Blob|MEM_Str) );
68867   }
68868   u.bg.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bg.pC->seekResult : 0);
68869   if( u.bg.pData->flags & MEM_Zero ){
68870     u.bg.nZero = u.bg.pData->u.nZero;
68871   }else{
68872     u.bg.nZero = 0;
68873   }
68874   sqlcipher3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
68875   rc = sqlcipher3BtreeInsert(u.bg.pC->pCursor, 0, u.bg.iKey,
68876                           u.bg.pData->z, u.bg.pData->n, u.bg.nZero,
68877                           pOp->p5 & OPFLAG_APPEND, u.bg.seekResult
68878   );
68879   u.bg.pC->rowidIsValid = 0;
68880   u.bg.pC->deferredMoveto = 0;
68881   u.bg.pC->cacheStatus = CACHE_STALE;
68882
68883   /* Invoke the update-hook if required. */
68884   if( rc==SQLCIPHER_OK && db->xUpdateCallback && pOp->p4.z ){
68885     u.bg.zDb = db->aDb[u.bg.pC->iDb].zName;
68886     u.bg.zTbl = pOp->p4.z;
68887     u.bg.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLCIPHER_UPDATE : SQLCIPHER_INSERT);
68888     assert( u.bg.pC->isTable );
68889     db->xUpdateCallback(db->pUpdateArg, u.bg.op, u.bg.zDb, u.bg.zTbl, u.bg.iKey);
68890     assert( u.bg.pC->iDb>=0 );
68891   }
68892   break;
68893 }
68894
68895 /* Opcode: Delete P1 P2 * P4 *
68896 **
68897 ** Delete the record at which the P1 cursor is currently pointing.
68898 **
68899 ** The cursor will be left pointing at either the next or the previous
68900 ** record in the table. If it is left pointing at the next record, then
68901 ** the next Next instruction will be a no-op.  Hence it is OK to delete
68902 ** a record from within an Next loop.
68903 **
68904 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
68905 ** incremented (otherwise not).
68906 **
68907 ** P1 must not be pseudo-table.  It has to be a real table with
68908 ** multiple rows.
68909 **
68910 ** If P4 is not NULL, then it is the name of the table that P1 is
68911 ** pointing to.  The update hook will be invoked, if it exists.
68912 ** If P4 is not NULL then the P1 cursor must have been positioned
68913 ** using OP_NotFound prior to invoking this opcode.
68914 */
68915 case OP_Delete: {
68916 #if 0  /* local variables moved into u.bh */
68917   i64 iKey;
68918   VdbeCursor *pC;
68919 #endif /* local variables moved into u.bh */
68920
68921   u.bh.iKey = 0;
68922   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68923   u.bh.pC = p->apCsr[pOp->p1];
68924   assert( u.bh.pC!=0 );
68925   assert( u.bh.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
68926
68927   /* If the update-hook will be invoked, set u.bh.iKey to the rowid of the
68928   ** row being deleted.
68929   */
68930   if( db->xUpdateCallback && pOp->p4.z ){
68931     assert( u.bh.pC->isTable );
68932     assert( u.bh.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
68933     u.bh.iKey = u.bh.pC->lastRowid;
68934   }
68935
68936   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
68937   ** OP_Column on the same table without any intervening operations that
68938   ** might move or invalidate the cursor.  Hence cursor u.bh.pC is always pointing
68939   ** to the row to be deleted and the sqlcipher3VdbeCursorMoveto() operation
68940   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
68941   ** to guard against future changes to the code generator.
68942   **/
68943   assert( u.bh.pC->deferredMoveto==0 );
68944   rc = sqlcipher3VdbeCursorMoveto(u.bh.pC);
68945   if( NEVER(rc!=SQLCIPHER_OK) ) goto abort_due_to_error;
68946
68947   sqlcipher3BtreeSetCachedRowid(u.bh.pC->pCursor, 0);
68948   rc = sqlcipher3BtreeDelete(u.bh.pC->pCursor);
68949   u.bh.pC->cacheStatus = CACHE_STALE;
68950
68951   /* Invoke the update-hook if required. */
68952   if( rc==SQLCIPHER_OK && db->xUpdateCallback && pOp->p4.z ){
68953     const char *zDb = db->aDb[u.bh.pC->iDb].zName;
68954     const char *zTbl = pOp->p4.z;
68955     db->xUpdateCallback(db->pUpdateArg, SQLCIPHER_DELETE, zDb, zTbl, u.bh.iKey);
68956     assert( u.bh.pC->iDb>=0 );
68957   }
68958   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
68959   break;
68960 }
68961 /* Opcode: ResetCount * * * * *
68962 **
68963 ** The value of the change counter is copied to the database handle
68964 ** change counter (returned by subsequent calls to sqlcipher3_changes()).
68965 ** Then the VMs internal change counter resets to 0.
68966 ** This is used by trigger programs.
68967 */
68968 case OP_ResetCount: {
68969   sqlcipher3VdbeSetChanges(db, p->nChange);
68970   p->nChange = 0;
68971   break;
68972 }
68973
68974 /* Opcode: SorterCompare P1 P2 P3
68975 **
68976 ** P1 is a sorter cursor. This instruction compares the record blob in 
68977 ** register P3 with the entry that the sorter cursor currently points to.
68978 ** If, excluding the rowid fields at the end, the two records are a match,
68979 ** fall through to the next instruction. Otherwise, jump to instruction P2.
68980 */
68981 case OP_SorterCompare: {
68982 #if 0  /* local variables moved into u.bi */
68983   VdbeCursor *pC;
68984   int res;
68985 #endif /* local variables moved into u.bi */
68986
68987   u.bi.pC = p->apCsr[pOp->p1];
68988   assert( isSorter(u.bi.pC) );
68989   pIn3 = &aMem[pOp->p3];
68990   rc = sqlcipher3VdbeSorterCompare(u.bi.pC, pIn3, &u.bi.res);
68991   if( u.bi.res ){
68992     pc = pOp->p2-1;
68993   }
68994   break;
68995 };
68996
68997 /* Opcode: SorterData P1 P2 * * *
68998 **
68999 ** Write into register P2 the current sorter data for sorter cursor P1.
69000 */
69001 case OP_SorterData: {
69002 #if 0  /* local variables moved into u.bj */
69003   VdbeCursor *pC;
69004 #endif /* local variables moved into u.bj */
69005 #ifndef SQLCIPHER_OMIT_MERGE_SORT
69006   pOut = &aMem[pOp->p2];
69007   u.bj.pC = p->apCsr[pOp->p1];
69008   assert( u.bj.pC->isSorter );
69009   rc = sqlcipher3VdbeSorterRowkey(u.bj.pC, pOut);
69010 #else
69011   pOp->opcode = OP_RowKey;
69012   pc--;
69013 #endif
69014   break;
69015 }
69016
69017 /* Opcode: RowData P1 P2 * * *
69018 **
69019 ** Write into register P2 the complete row data for cursor P1.
69020 ** There is no interpretation of the data.  
69021 ** It is just copied onto the P2 register exactly as 
69022 ** it is found in the database file.
69023 **
69024 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
69025 ** of a real table, not a pseudo-table.
69026 */
69027 /* Opcode: RowKey P1 P2 * * *
69028 **
69029 ** Write into register P2 the complete row key for cursor P1.
69030 ** There is no interpretation of the data.  
69031 ** The key is copied onto the P3 register exactly as 
69032 ** it is found in the database file.
69033 **
69034 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
69035 ** of a real table, not a pseudo-table.
69036 */
69037 case OP_RowKey:
69038 case OP_RowData: {
69039 #if 0  /* local variables moved into u.bk */
69040   VdbeCursor *pC;
69041   BtCursor *pCrsr;
69042   u32 n;
69043   i64 n64;
69044 #endif /* local variables moved into u.bk */
69045
69046   pOut = &aMem[pOp->p2];
69047   memAboutToChange(p, pOut);
69048
69049   /* Note that RowKey and RowData are really exactly the same instruction */
69050   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69051   u.bk.pC = p->apCsr[pOp->p1];
69052   assert( u.bk.pC->isSorter==0 );
69053   assert( u.bk.pC->isTable || pOp->opcode!=OP_RowData );
69054   assert( u.bk.pC->isIndex || pOp->opcode==OP_RowData );
69055   assert( u.bk.pC!=0 );
69056   assert( u.bk.pC->nullRow==0 );
69057   assert( u.bk.pC->pseudoTableReg==0 );
69058   assert( !u.bk.pC->isSorter );
69059   assert( u.bk.pC->pCursor!=0 );
69060   u.bk.pCrsr = u.bk.pC->pCursor;
69061   assert( sqlcipher3BtreeCursorIsValid(u.bk.pCrsr) );
69062
69063   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
69064   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
69065   ** the cursor.  Hence the following sqlcipher3VdbeCursorMoveto() call is always
69066   ** a no-op and can never fail.  But we leave it in place as a safety.
69067   */
69068   assert( u.bk.pC->deferredMoveto==0 );
69069   rc = sqlcipher3VdbeCursorMoveto(u.bk.pC);
69070   if( NEVER(rc!=SQLCIPHER_OK) ) goto abort_due_to_error;
69071
69072   if( u.bk.pC->isIndex ){
69073     assert( !u.bk.pC->isTable );
69074     VVA_ONLY(rc =) sqlcipher3BtreeKeySize(u.bk.pCrsr, &u.bk.n64);
69075     assert( rc==SQLCIPHER_OK );    /* True because of CursorMoveto() call above */
69076     if( u.bk.n64>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
69077       goto too_big;
69078     }
69079     u.bk.n = (u32)u.bk.n64;
69080   }else{
69081     VVA_ONLY(rc =) sqlcipher3BtreeDataSize(u.bk.pCrsr, &u.bk.n);
69082     assert( rc==SQLCIPHER_OK );    /* DataSize() cannot fail */
69083     if( u.bk.n>(u32)db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
69084       goto too_big;
69085     }
69086   }
69087   if( sqlcipher3VdbeMemGrow(pOut, u.bk.n, 0) ){
69088     goto no_mem;
69089   }
69090   pOut->n = u.bk.n;
69091   MemSetTypeFlag(pOut, MEM_Blob);
69092   if( u.bk.pC->isIndex ){
69093     rc = sqlcipher3BtreeKey(u.bk.pCrsr, 0, u.bk.n, pOut->z);
69094   }else{
69095     rc = sqlcipher3BtreeData(u.bk.pCrsr, 0, u.bk.n, pOut->z);
69096   }
69097   pOut->enc = SQLCIPHER_UTF8;  /* In case the blob is ever cast to text */
69098   UPDATE_MAX_BLOBSIZE(pOut);
69099   break;
69100 }
69101
69102 /* Opcode: Rowid P1 P2 * * *
69103 **
69104 ** Store in register P2 an integer which is the key of the table entry that
69105 ** P1 is currently point to.
69106 **
69107 ** P1 can be either an ordinary table or a virtual table.  There used to
69108 ** be a separate OP_VRowid opcode for use with virtual tables, but this
69109 ** one opcode now works for both table types.
69110 */
69111 case OP_Rowid: {                 /* out2-prerelease */
69112 #if 0  /* local variables moved into u.bl */
69113   VdbeCursor *pC;
69114   i64 v;
69115   sqlcipher3_vtab *pVtab;
69116   const sqlcipher3_module *pModule;
69117 #endif /* local variables moved into u.bl */
69118
69119   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69120   u.bl.pC = p->apCsr[pOp->p1];
69121   assert( u.bl.pC!=0 );
69122   assert( u.bl.pC->pseudoTableReg==0 );
69123   if( u.bl.pC->nullRow ){
69124     pOut->flags = MEM_Null;
69125     break;
69126   }else if( u.bl.pC->deferredMoveto ){
69127     u.bl.v = u.bl.pC->movetoTarget;
69128 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
69129   }else if( u.bl.pC->pVtabCursor ){
69130     u.bl.pVtab = u.bl.pC->pVtabCursor->pVtab;
69131     u.bl.pModule = u.bl.pVtab->pModule;
69132     assert( u.bl.pModule->xRowid );
69133     rc = u.bl.pModule->xRowid(u.bl.pC->pVtabCursor, &u.bl.v);
69134     importVtabErrMsg(p, u.bl.pVtab);
69135 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
69136   }else{
69137     assert( u.bl.pC->pCursor!=0 );
69138     rc = sqlcipher3VdbeCursorMoveto(u.bl.pC);
69139     if( rc ) goto abort_due_to_error;
69140     if( u.bl.pC->rowidIsValid ){
69141       u.bl.v = u.bl.pC->lastRowid;
69142     }else{
69143       rc = sqlcipher3BtreeKeySize(u.bl.pC->pCursor, &u.bl.v);
69144       assert( rc==SQLCIPHER_OK );  /* Always so because of CursorMoveto() above */
69145     }
69146   }
69147   pOut->u.i = u.bl.v;
69148   break;
69149 }
69150
69151 /* Opcode: NullRow P1 * * * *
69152 **
69153 ** Move the cursor P1 to a null row.  Any OP_Column operations
69154 ** that occur while the cursor is on the null row will always
69155 ** write a NULL.
69156 */
69157 case OP_NullRow: {
69158 #if 0  /* local variables moved into u.bm */
69159   VdbeCursor *pC;
69160 #endif /* local variables moved into u.bm */
69161
69162   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69163   u.bm.pC = p->apCsr[pOp->p1];
69164   assert( u.bm.pC!=0 );
69165   u.bm.pC->nullRow = 1;
69166   u.bm.pC->rowidIsValid = 0;
69167   assert( u.bm.pC->pCursor || u.bm.pC->pVtabCursor );
69168   if( u.bm.pC->pCursor ){
69169     sqlcipher3BtreeClearCursor(u.bm.pC->pCursor);
69170   }
69171   break;
69172 }
69173
69174 /* Opcode: Last P1 P2 * * *
69175 **
69176 ** The next use of the Rowid or Column or Next instruction for P1 
69177 ** will refer to the last entry in the database table or index.
69178 ** If the table or index is empty and P2>0, then jump immediately to P2.
69179 ** If P2 is 0 or if the table or index is not empty, fall through
69180 ** to the following instruction.
69181 */
69182 case OP_Last: {        /* jump */
69183 #if 0  /* local variables moved into u.bn */
69184   VdbeCursor *pC;
69185   BtCursor *pCrsr;
69186   int res;
69187 #endif /* local variables moved into u.bn */
69188
69189   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69190   u.bn.pC = p->apCsr[pOp->p1];
69191   assert( u.bn.pC!=0 );
69192   u.bn.pCrsr = u.bn.pC->pCursor;
69193   u.bn.res = 0;
69194   if( ALWAYS(u.bn.pCrsr!=0) ){
69195     rc = sqlcipher3BtreeLast(u.bn.pCrsr, &u.bn.res);
69196   }
69197   u.bn.pC->nullRow = (u8)u.bn.res;
69198   u.bn.pC->deferredMoveto = 0;
69199   u.bn.pC->rowidIsValid = 0;
69200   u.bn.pC->cacheStatus = CACHE_STALE;
69201   if( pOp->p2>0 && u.bn.res ){
69202     pc = pOp->p2 - 1;
69203   }
69204   break;
69205 }
69206
69207
69208 /* Opcode: Sort P1 P2 * * *
69209 **
69210 ** This opcode does exactly the same thing as OP_Rewind except that
69211 ** it increments an undocumented global variable used for testing.
69212 **
69213 ** Sorting is accomplished by writing records into a sorting index,
69214 ** then rewinding that index and playing it back from beginning to
69215 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
69216 ** rewinding so that the global variable will be incremented and
69217 ** regression tests can determine whether or not the optimizer is
69218 ** correctly optimizing out sorts.
69219 */
69220 case OP_SorterSort:    /* jump */
69221 #ifdef SQLCIPHER_OMIT_MERGE_SORT
69222   pOp->opcode = OP_Sort;
69223 #endif
69224 case OP_Sort: {        /* jump */
69225 #ifdef SQLCIPHER_TEST
69226   sqlcipher3_sort_count++;
69227   sqlcipher3_search_count--;
69228 #endif
69229   p->aCounter[SQLCIPHER_STMTSTATUS_SORT-1]++;
69230   /* Fall through into OP_Rewind */
69231 }
69232 /* Opcode: Rewind P1 P2 * * *
69233 **
69234 ** The next use of the Rowid or Column or Next instruction for P1 
69235 ** will refer to the first entry in the database table or index.
69236 ** If the table or index is empty and P2>0, then jump immediately to P2.
69237 ** If P2 is 0 or if the table or index is not empty, fall through
69238 ** to the following instruction.
69239 */
69240 case OP_Rewind: {        /* jump */
69241 #if 0  /* local variables moved into u.bo */
69242   VdbeCursor *pC;
69243   BtCursor *pCrsr;
69244   int res;
69245 #endif /* local variables moved into u.bo */
69246
69247   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69248   u.bo.pC = p->apCsr[pOp->p1];
69249   assert( u.bo.pC!=0 );
69250   assert( u.bo.pC->isSorter==(pOp->opcode==OP_SorterSort) );
69251   u.bo.res = 1;
69252   if( isSorter(u.bo.pC) ){
69253     rc = sqlcipher3VdbeSorterRewind(db, u.bo.pC, &u.bo.res);
69254   }else{
69255     u.bo.pCrsr = u.bo.pC->pCursor;
69256     assert( u.bo.pCrsr );
69257     rc = sqlcipher3BtreeFirst(u.bo.pCrsr, &u.bo.res);
69258     u.bo.pC->atFirst = u.bo.res==0 ?1:0;
69259     u.bo.pC->deferredMoveto = 0;
69260     u.bo.pC->cacheStatus = CACHE_STALE;
69261     u.bo.pC->rowidIsValid = 0;
69262   }
69263   u.bo.pC->nullRow = (u8)u.bo.res;
69264   assert( pOp->p2>0 && pOp->p2<p->nOp );
69265   if( u.bo.res ){
69266     pc = pOp->p2 - 1;
69267   }
69268   break;
69269 }
69270
69271 /* Opcode: Next P1 P2 * P4 P5
69272 **
69273 ** Advance cursor P1 so that it points to the next key/data pair in its
69274 ** table or index.  If there are no more key/value pairs then fall through
69275 ** to the following instruction.  But if the cursor advance was successful,
69276 ** jump immediately to P2.
69277 **
69278 ** The P1 cursor must be for a real table, not a pseudo-table.
69279 **
69280 ** P4 is always of type P4_ADVANCE. The function pointer points to
69281 ** sqlcipher3BtreeNext().
69282 **
69283 ** If P5 is positive and the jump is taken, then event counter
69284 ** number P5-1 in the prepared statement is incremented.
69285 **
69286 ** See also: Prev
69287 */
69288 /* Opcode: Prev P1 P2 * * P5
69289 **
69290 ** Back up cursor P1 so that it points to the previous key/data pair in its
69291 ** table or index.  If there is no previous key/value pairs then fall through
69292 ** to the following instruction.  But if the cursor backup was successful,
69293 ** jump immediately to P2.
69294 **
69295 ** The P1 cursor must be for a real table, not a pseudo-table.
69296 **
69297 ** P4 is always of type P4_ADVANCE. The function pointer points to
69298 ** sqlcipher3BtreePrevious().
69299 **
69300 ** If P5 is positive and the jump is taken, then event counter
69301 ** number P5-1 in the prepared statement is incremented.
69302 */
69303 case OP_SorterNext:    /* jump */
69304 #ifdef SQLCIPHER_OMIT_MERGE_SORT
69305   pOp->opcode = OP_Next;
69306 #endif
69307 case OP_Prev:          /* jump */
69308 case OP_Next: {        /* jump */
69309 #if 0  /* local variables moved into u.bp */
69310   VdbeCursor *pC;
69311   int res;
69312 #endif /* local variables moved into u.bp */
69313
69314   CHECK_FOR_INTERRUPT;
69315   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69316   assert( pOp->p5<=ArraySize(p->aCounter) );
69317   u.bp.pC = p->apCsr[pOp->p1];
69318   if( u.bp.pC==0 ){
69319     break;  /* See ticket #2273 */
69320   }
69321   assert( u.bp.pC->isSorter==(pOp->opcode==OP_SorterNext) );
69322   if( isSorter(u.bp.pC) ){
69323     assert( pOp->opcode==OP_SorterNext );
69324     rc = sqlcipher3VdbeSorterNext(db, u.bp.pC, &u.bp.res);
69325   }else{
69326     u.bp.res = 1;
69327     assert( u.bp.pC->deferredMoveto==0 );
69328     assert( u.bp.pC->pCursor );
69329     assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlcipher3BtreeNext );
69330     assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlcipher3BtreePrevious );
69331     rc = pOp->p4.xAdvance(u.bp.pC->pCursor, &u.bp.res);
69332   }
69333   u.bp.pC->nullRow = (u8)u.bp.res;
69334   u.bp.pC->cacheStatus = CACHE_STALE;
69335   if( u.bp.res==0 ){
69336     pc = pOp->p2 - 1;
69337     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
69338 #ifdef SQLCIPHER_TEST
69339     sqlcipher3_search_count++;
69340 #endif
69341   }
69342   u.bp.pC->rowidIsValid = 0;
69343   break;
69344 }
69345
69346 /* Opcode: IdxInsert P1 P2 P3 * P5
69347 **
69348 ** Register P2 holds an SQL index key made using the
69349 ** MakeRecord instructions.  This opcode writes that key
69350 ** into the index P1.  Data for the entry is nil.
69351 **
69352 ** P3 is a flag that provides a hint to the b-tree layer that this
69353 ** insert is likely to be an append.
69354 **
69355 ** This instruction only works for indices.  The equivalent instruction
69356 ** for tables is OP_Insert.
69357 */
69358 case OP_SorterInsert:       /* in2 */
69359 #ifdef SQLCIPHER_OMIT_MERGE_SORT
69360   pOp->opcode = OP_IdxInsert;
69361 #endif
69362 case OP_IdxInsert: {        /* in2 */
69363 #if 0  /* local variables moved into u.bq */
69364   VdbeCursor *pC;
69365   BtCursor *pCrsr;
69366   int nKey;
69367   const char *zKey;
69368 #endif /* local variables moved into u.bq */
69369
69370   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69371   u.bq.pC = p->apCsr[pOp->p1];
69372   assert( u.bq.pC!=0 );
69373   assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
69374   pIn2 = &aMem[pOp->p2];
69375   assert( pIn2->flags & MEM_Blob );
69376   u.bq.pCrsr = u.bq.pC->pCursor;
69377   if( ALWAYS(u.bq.pCrsr!=0) ){
69378     assert( u.bq.pC->isTable==0 );
69379     rc = ExpandBlob(pIn2);
69380     if( rc==SQLCIPHER_OK ){
69381       if( isSorter(u.bq.pC) ){
69382         rc = sqlcipher3VdbeSorterWrite(db, u.bq.pC, pIn2);
69383       }else{
69384         u.bq.nKey = pIn2->n;
69385         u.bq.zKey = pIn2->z;
69386         rc = sqlcipher3BtreeInsert(u.bq.pCrsr, u.bq.zKey, u.bq.nKey, "", 0, 0, pOp->p3,
69387             ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bq.pC->seekResult : 0)
69388             );
69389         assert( u.bq.pC->deferredMoveto==0 );
69390         u.bq.pC->cacheStatus = CACHE_STALE;
69391       }
69392     }
69393   }
69394   break;
69395 }
69396
69397 /* Opcode: IdxDelete P1 P2 P3 * *
69398 **
69399 ** The content of P3 registers starting at register P2 form
69400 ** an unpacked index key. This opcode removes that entry from the 
69401 ** index opened by cursor P1.
69402 */
69403 case OP_IdxDelete: {
69404 #if 0  /* local variables moved into u.br */
69405   VdbeCursor *pC;
69406   BtCursor *pCrsr;
69407   int res;
69408   UnpackedRecord r;
69409 #endif /* local variables moved into u.br */
69410
69411   assert( pOp->p3>0 );
69412   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
69413   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69414   u.br.pC = p->apCsr[pOp->p1];
69415   assert( u.br.pC!=0 );
69416   u.br.pCrsr = u.br.pC->pCursor;
69417   if( ALWAYS(u.br.pCrsr!=0) ){
69418     u.br.r.pKeyInfo = u.br.pC->pKeyInfo;
69419     u.br.r.nField = (u16)pOp->p3;
69420     u.br.r.flags = 0;
69421     u.br.r.aMem = &aMem[pOp->p2];
69422 #ifdef SQLCIPHER_DEBUG
69423     { int i; for(i=0; i<u.br.r.nField; i++) assert( memIsValid(&u.br.r.aMem[i]) ); }
69424 #endif
69425     rc = sqlcipher3BtreeMovetoUnpacked(u.br.pCrsr, &u.br.r, 0, 0, &u.br.res);
69426     if( rc==SQLCIPHER_OK && u.br.res==0 ){
69427       rc = sqlcipher3BtreeDelete(u.br.pCrsr);
69428     }
69429     assert( u.br.pC->deferredMoveto==0 );
69430     u.br.pC->cacheStatus = CACHE_STALE;
69431   }
69432   break;
69433 }
69434
69435 /* Opcode: IdxRowid P1 P2 * * *
69436 **
69437 ** Write into register P2 an integer which is the last entry in the record at
69438 ** the end of the index key pointed to by cursor P1.  This integer should be
69439 ** the rowid of the table entry to which this index entry points.
69440 **
69441 ** See also: Rowid, MakeRecord.
69442 */
69443 case OP_IdxRowid: {              /* out2-prerelease */
69444 #if 0  /* local variables moved into u.bs */
69445   BtCursor *pCrsr;
69446   VdbeCursor *pC;
69447   i64 rowid;
69448 #endif /* local variables moved into u.bs */
69449
69450   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69451   u.bs.pC = p->apCsr[pOp->p1];
69452   assert( u.bs.pC!=0 );
69453   u.bs.pCrsr = u.bs.pC->pCursor;
69454   pOut->flags = MEM_Null;
69455   if( ALWAYS(u.bs.pCrsr!=0) ){
69456     rc = sqlcipher3VdbeCursorMoveto(u.bs.pC);
69457     if( NEVER(rc) ) goto abort_due_to_error;
69458     assert( u.bs.pC->deferredMoveto==0 );
69459     assert( u.bs.pC->isTable==0 );
69460     if( !u.bs.pC->nullRow ){
69461       rc = sqlcipher3VdbeIdxRowid(db, u.bs.pCrsr, &u.bs.rowid);
69462       if( rc!=SQLCIPHER_OK ){
69463         goto abort_due_to_error;
69464       }
69465       pOut->u.i = u.bs.rowid;
69466       pOut->flags = MEM_Int;
69467     }
69468   }
69469   break;
69470 }
69471
69472 /* Opcode: IdxGE P1 P2 P3 P4 P5
69473 **
69474 ** The P4 register values beginning with P3 form an unpacked index 
69475 ** key that omits the ROWID.  Compare this key value against the index 
69476 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
69477 **
69478 ** If the P1 index entry is greater than or equal to the key value
69479 ** then jump to P2.  Otherwise fall through to the next instruction.
69480 **
69481 ** If P5 is non-zero then the key value is increased by an epsilon 
69482 ** prior to the comparison.  This make the opcode work like IdxGT except
69483 ** that if the key from register P3 is a prefix of the key in the cursor,
69484 ** the result is false whereas it would be true with IdxGT.
69485 */
69486 /* Opcode: IdxLT P1 P2 P3 P4 P5
69487 **
69488 ** The P4 register values beginning with P3 form an unpacked index 
69489 ** key that omits the ROWID.  Compare this key value against the index 
69490 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
69491 **
69492 ** If the P1 index entry is less than the key value then jump to P2.
69493 ** Otherwise fall through to the next instruction.
69494 **
69495 ** If P5 is non-zero then the key value is increased by an epsilon prior 
69496 ** to the comparison.  This makes the opcode work like IdxLE.
69497 */
69498 case OP_IdxLT:          /* jump */
69499 case OP_IdxGE: {        /* jump */
69500 #if 0  /* local variables moved into u.bt */
69501   VdbeCursor *pC;
69502   int res;
69503   UnpackedRecord r;
69504 #endif /* local variables moved into u.bt */
69505
69506   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69507   u.bt.pC = p->apCsr[pOp->p1];
69508   assert( u.bt.pC!=0 );
69509   assert( u.bt.pC->isOrdered );
69510   if( ALWAYS(u.bt.pC->pCursor!=0) ){
69511     assert( u.bt.pC->deferredMoveto==0 );
69512     assert( pOp->p5==0 || pOp->p5==1 );
69513     assert( pOp->p4type==P4_INT32 );
69514     u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
69515     u.bt.r.nField = (u16)pOp->p4.i;
69516     if( pOp->p5 ){
69517       u.bt.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
69518     }else{
69519       u.bt.r.flags = UNPACKED_IGNORE_ROWID;
69520     }
69521     u.bt.r.aMem = &aMem[pOp->p3];
69522 #ifdef SQLCIPHER_DEBUG
69523     { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
69524 #endif
69525     rc = sqlcipher3VdbeIdxKeyCompare(u.bt.pC, &u.bt.r, &u.bt.res);
69526     if( pOp->opcode==OP_IdxLT ){
69527       u.bt.res = -u.bt.res;
69528     }else{
69529       assert( pOp->opcode==OP_IdxGE );
69530       u.bt.res++;
69531     }
69532     if( u.bt.res>0 ){
69533       pc = pOp->p2 - 1 ;
69534     }
69535   }
69536   break;
69537 }
69538
69539 /* Opcode: Destroy P1 P2 P3 * *
69540 **
69541 ** Delete an entire database table or index whose root page in the database
69542 ** file is given by P1.
69543 **
69544 ** The table being destroyed is in the main database file if P3==0.  If
69545 ** P3==1 then the table to be clear is in the auxiliary database file
69546 ** that is used to store tables create using CREATE TEMPORARY TABLE.
69547 **
69548 ** If AUTOVACUUM is enabled then it is possible that another root page
69549 ** might be moved into the newly deleted root page in order to keep all
69550 ** root pages contiguous at the beginning of the database.  The former
69551 ** value of the root page that moved - its value before the move occurred -
69552 ** is stored in register P2.  If no page 
69553 ** movement was required (because the table being dropped was already 
69554 ** the last one in the database) then a zero is stored in register P2.
69555 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
69556 **
69557 ** See also: Clear
69558 */
69559 case OP_Destroy: {     /* out2-prerelease */
69560 #if 0  /* local variables moved into u.bu */
69561   int iMoved;
69562   int iCnt;
69563   Vdbe *pVdbe;
69564   int iDb;
69565 #endif /* local variables moved into u.bu */
69566 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
69567   u.bu.iCnt = 0;
69568   for(u.bu.pVdbe=db->pVdbe; u.bu.pVdbe; u.bu.pVdbe = u.bu.pVdbe->pNext){
69569     if( u.bu.pVdbe->magic==VDBE_MAGIC_RUN && u.bu.pVdbe->inVtabMethod<2 && u.bu.pVdbe->pc>=0 ){
69570       u.bu.iCnt++;
69571     }
69572   }
69573 #else
69574   u.bu.iCnt = db->activeVdbeCnt;
69575 #endif
69576   pOut->flags = MEM_Null;
69577   if( u.bu.iCnt>1 ){
69578     rc = SQLCIPHER_LOCKED;
69579     p->errorAction = OE_Abort;
69580   }else{
69581     u.bu.iDb = pOp->p3;
69582     assert( u.bu.iCnt==1 );
69583     assert( (p->btreeMask & (((yDbMask)1)<<u.bu.iDb))!=0 );
69584     rc = sqlcipher3BtreeDropTable(db->aDb[u.bu.iDb].pBt, pOp->p1, &u.bu.iMoved);
69585     pOut->flags = MEM_Int;
69586     pOut->u.i = u.bu.iMoved;
69587 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
69588     if( rc==SQLCIPHER_OK && u.bu.iMoved!=0 ){
69589       sqlcipher3RootPageMoved(db, u.bu.iDb, u.bu.iMoved, pOp->p1);
69590       /* All OP_Destroy operations occur on the same btree */
69591       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bu.iDb+1 );
69592       resetSchemaOnFault = u.bu.iDb+1;
69593     }
69594 #endif
69595   }
69596   break;
69597 }
69598
69599 /* Opcode: Clear P1 P2 P3
69600 **
69601 ** Delete all contents of the database table or index whose root page
69602 ** in the database file is given by P1.  But, unlike Destroy, do not
69603 ** remove the table or index from the database file.
69604 **
69605 ** The table being clear is in the main database file if P2==0.  If
69606 ** P2==1 then the table to be clear is in the auxiliary database file
69607 ** that is used to store tables create using CREATE TEMPORARY TABLE.
69608 **
69609 ** If the P3 value is non-zero, then the table referred to must be an
69610 ** intkey table (an SQL table, not an index). In this case the row change 
69611 ** count is incremented by the number of rows in the table being cleared. 
69612 ** If P3 is greater than zero, then the value stored in register P3 is
69613 ** also incremented by the number of rows in the table being cleared.
69614 **
69615 ** See also: Destroy
69616 */
69617 case OP_Clear: {
69618 #if 0  /* local variables moved into u.bv */
69619   int nChange;
69620 #endif /* local variables moved into u.bv */
69621
69622   u.bv.nChange = 0;
69623   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
69624   rc = sqlcipher3BtreeClearTable(
69625       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bv.nChange : 0)
69626   );
69627   if( pOp->p3 ){
69628     p->nChange += u.bv.nChange;
69629     if( pOp->p3>0 ){
69630       assert( memIsValid(&aMem[pOp->p3]) );
69631       memAboutToChange(p, &aMem[pOp->p3]);
69632       aMem[pOp->p3].u.i += u.bv.nChange;
69633     }
69634   }
69635   break;
69636 }
69637
69638 /* Opcode: CreateTable P1 P2 * * *
69639 **
69640 ** Allocate a new table in the main database file if P1==0 or in the
69641 ** auxiliary database file if P1==1 or in an attached database if
69642 ** P1>1.  Write the root page number of the new table into
69643 ** register P2
69644 **
69645 ** The difference between a table and an index is this:  A table must
69646 ** have a 4-byte integer key and can have arbitrary data.  An index
69647 ** has an arbitrary key but no data.
69648 **
69649 ** See also: CreateIndex
69650 */
69651 /* Opcode: CreateIndex P1 P2 * * *
69652 **
69653 ** Allocate a new index in the main database file if P1==0 or in the
69654 ** auxiliary database file if P1==1 or in an attached database if
69655 ** P1>1.  Write the root page number of the new table into
69656 ** register P2.
69657 **
69658 ** See documentation on OP_CreateTable for additional information.
69659 */
69660 case OP_CreateIndex:            /* out2-prerelease */
69661 case OP_CreateTable: {          /* out2-prerelease */
69662 #if 0  /* local variables moved into u.bw */
69663   int pgno;
69664   int flags;
69665   Db *pDb;
69666 #endif /* local variables moved into u.bw */
69667
69668   u.bw.pgno = 0;
69669   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69670   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69671   u.bw.pDb = &db->aDb[pOp->p1];
69672   assert( u.bw.pDb->pBt!=0 );
69673   if( pOp->opcode==OP_CreateTable ){
69674     /* u.bw.flags = BTREE_INTKEY; */
69675     u.bw.flags = BTREE_INTKEY;
69676   }else{
69677     u.bw.flags = BTREE_BLOBKEY;
69678   }
69679   rc = sqlcipher3BtreeCreateTable(u.bw.pDb->pBt, &u.bw.pgno, u.bw.flags);
69680   pOut->u.i = u.bw.pgno;
69681   break;
69682 }
69683
69684 /* Opcode: ParseSchema P1 * * P4 *
69685 **
69686 ** Read and parse all entries from the SQLCIPHER_MASTER table of database P1
69687 ** that match the WHERE clause P4. 
69688 **
69689 ** This opcode invokes the parser to create a new virtual machine,
69690 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
69691 */
69692 case OP_ParseSchema: {
69693 #if 0  /* local variables moved into u.bx */
69694   int iDb;
69695   const char *zMaster;
69696   char *zSql;
69697   InitData initData;
69698 #endif /* local variables moved into u.bx */
69699
69700   /* Any prepared statement that invokes this opcode will hold mutexes
69701   ** on every btree.  This is a prerequisite for invoking
69702   ** sqlcipher3InitCallback().
69703   */
69704 #ifdef SQLCIPHER_DEBUG
69705   for(u.bx.iDb=0; u.bx.iDb<db->nDb; u.bx.iDb++){
69706     assert( u.bx.iDb==1 || sqlcipher3BtreeHoldsMutex(db->aDb[u.bx.iDb].pBt) );
69707   }
69708 #endif
69709
69710   u.bx.iDb = pOp->p1;
69711   assert( u.bx.iDb>=0 && u.bx.iDb<db->nDb );
69712   assert( DbHasProperty(db, u.bx.iDb, DB_SchemaLoaded) );
69713   /* Used to be a conditional */ {
69714     u.bx.zMaster = SCHEMA_TABLE(u.bx.iDb);
69715     u.bx.initData.db = db;
69716     u.bx.initData.iDb = pOp->p1;
69717     u.bx.initData.pzErrMsg = &p->zErrMsg;
69718     u.bx.zSql = sqlcipher3MPrintf(db,
69719        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
69720        db->aDb[u.bx.iDb].zName, u.bx.zMaster, pOp->p4.z);
69721     if( u.bx.zSql==0 ){
69722       rc = SQLCIPHER_NOMEM;
69723     }else{
69724       assert( db->init.busy==0 );
69725       db->init.busy = 1;
69726       u.bx.initData.rc = SQLCIPHER_OK;
69727       assert( !db->mallocFailed );
69728       rc = sqlcipher3_exec(db, u.bx.zSql, sqlcipher3InitCallback, &u.bx.initData, 0);
69729       if( rc==SQLCIPHER_OK ) rc = u.bx.initData.rc;
69730       sqlcipher3DbFree(db, u.bx.zSql);
69731       db->init.busy = 0;
69732     }
69733   }
69734   if( rc==SQLCIPHER_NOMEM ){
69735     goto no_mem;
69736   }
69737   break;
69738 }
69739
69740 #if !defined(SQLCIPHER_OMIT_ANALYZE)
69741 /* Opcode: LoadAnalysis P1 * * * *
69742 **
69743 ** Read the sqlcipher_stat1 table for database P1 and load the content
69744 ** of that table into the internal index hash table.  This will cause
69745 ** the analysis to be used when preparing all subsequent queries.
69746 */
69747 case OP_LoadAnalysis: {
69748   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69749   rc = sqlcipher3AnalysisLoad(db, pOp->p1);
69750   break;  
69751 }
69752 #endif /* !defined(SQLCIPHER_OMIT_ANALYZE) */
69753
69754 /* Opcode: DropTable P1 * * P4 *
69755 **
69756 ** Remove the internal (in-memory) data structures that describe
69757 ** the table named P4 in database P1.  This is called after a table
69758 ** is dropped in order to keep the internal representation of the
69759 ** schema consistent with what is on disk.
69760 */
69761 case OP_DropTable: {
69762   sqlcipher3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
69763   break;
69764 }
69765
69766 /* Opcode: DropIndex P1 * * P4 *
69767 **
69768 ** Remove the internal (in-memory) data structures that describe
69769 ** the index named P4 in database P1.  This is called after an index
69770 ** is dropped in order to keep the internal representation of the
69771 ** schema consistent with what is on disk.
69772 */
69773 case OP_DropIndex: {
69774   sqlcipher3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
69775   break;
69776 }
69777
69778 /* Opcode: DropTrigger P1 * * P4 *
69779 **
69780 ** Remove the internal (in-memory) data structures that describe
69781 ** the trigger named P4 in database P1.  This is called after a trigger
69782 ** is dropped in order to keep the internal representation of the
69783 ** schema consistent with what is on disk.
69784 */
69785 case OP_DropTrigger: {
69786   sqlcipher3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
69787   break;
69788 }
69789
69790
69791 #ifndef SQLCIPHER_OMIT_INTEGRITY_CHECK
69792 /* Opcode: IntegrityCk P1 P2 P3 * P5
69793 **
69794 ** Do an analysis of the currently open database.  Store in
69795 ** register P1 the text of an error message describing any problems.
69796 ** If no problems are found, store a NULL in register P1.
69797 **
69798 ** The register P3 contains the maximum number of allowed errors.
69799 ** At most reg(P3) errors will be reported.
69800 ** In other words, the analysis stops as soon as reg(P1) errors are 
69801 ** seen.  Reg(P1) is updated with the number of errors remaining.
69802 **
69803 ** The root page numbers of all tables in the database are integer
69804 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
69805 ** total.
69806 **
69807 ** If P5 is not zero, the check is done on the auxiliary database
69808 ** file, not the main database file.
69809 **
69810 ** This opcode is used to implement the integrity_check pragma.
69811 */
69812 case OP_IntegrityCk: {
69813 #if 0  /* local variables moved into u.by */
69814   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
69815   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
69816   int j;          /* Loop counter */
69817   int nErr;       /* Number of errors reported */
69818   char *z;        /* Text of the error report */
69819   Mem *pnErr;     /* Register keeping track of errors remaining */
69820 #endif /* local variables moved into u.by */
69821
69822   u.by.nRoot = pOp->p2;
69823   assert( u.by.nRoot>0 );
69824   u.by.aRoot = sqlcipher3DbMallocRaw(db, sizeof(int)*(u.by.nRoot+1) );
69825   if( u.by.aRoot==0 ) goto no_mem;
69826   assert( pOp->p3>0 && pOp->p3<=p->nMem );
69827   u.by.pnErr = &aMem[pOp->p3];
69828   assert( (u.by.pnErr->flags & MEM_Int)!=0 );
69829   assert( (u.by.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
69830   pIn1 = &aMem[pOp->p1];
69831   for(u.by.j=0; u.by.j<u.by.nRoot; u.by.j++){
69832     u.by.aRoot[u.by.j] = (int)sqlcipher3VdbeIntValue(&pIn1[u.by.j]);
69833   }
69834   u.by.aRoot[u.by.j] = 0;
69835   assert( pOp->p5<db->nDb );
69836   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
69837   u.by.z = sqlcipher3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.by.aRoot, u.by.nRoot,
69838                                  (int)u.by.pnErr->u.i, &u.by.nErr);
69839   sqlcipher3DbFree(db, u.by.aRoot);
69840   u.by.pnErr->u.i -= u.by.nErr;
69841   sqlcipher3VdbeMemSetNull(pIn1);
69842   if( u.by.nErr==0 ){
69843     assert( u.by.z==0 );
69844   }else if( u.by.z==0 ){
69845     goto no_mem;
69846   }else{
69847     sqlcipher3VdbeMemSetStr(pIn1, u.by.z, -1, SQLCIPHER_UTF8, sqlcipher3_free);
69848   }
69849   UPDATE_MAX_BLOBSIZE(pIn1);
69850   sqlcipher3VdbeChangeEncoding(pIn1, encoding);
69851   break;
69852 }
69853 #endif /* SQLCIPHER_OMIT_INTEGRITY_CHECK */
69854
69855 /* Opcode: RowSetAdd P1 P2 * * *
69856 **
69857 ** Insert the integer value held by register P2 into a boolean index
69858 ** held in register P1.
69859 **
69860 ** An assertion fails if P2 is not an integer.
69861 */
69862 case OP_RowSetAdd: {       /* in1, in2 */
69863   pIn1 = &aMem[pOp->p1];
69864   pIn2 = &aMem[pOp->p2];
69865   assert( (pIn2->flags & MEM_Int)!=0 );
69866   if( (pIn1->flags & MEM_RowSet)==0 ){
69867     sqlcipher3VdbeMemSetRowSet(pIn1);
69868     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
69869   }
69870   sqlcipher3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
69871   break;
69872 }
69873
69874 /* Opcode: RowSetRead P1 P2 P3 * *
69875 **
69876 ** Extract the smallest value from boolean index P1 and put that value into
69877 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
69878 ** unchanged and jump to instruction P2.
69879 */
69880 case OP_RowSetRead: {       /* jump, in1, out3 */
69881 #if 0  /* local variables moved into u.bz */
69882   i64 val;
69883 #endif /* local variables moved into u.bz */
69884   CHECK_FOR_INTERRUPT;
69885   pIn1 = &aMem[pOp->p1];
69886   if( (pIn1->flags & MEM_RowSet)==0
69887    || sqlcipher3RowSetNext(pIn1->u.pRowSet, &u.bz.val)==0
69888   ){
69889     /* The boolean index is empty */
69890     sqlcipher3VdbeMemSetNull(pIn1);
69891     pc = pOp->p2 - 1;
69892   }else{
69893     /* A value was pulled from the index */
69894     sqlcipher3VdbeMemSetInt64(&aMem[pOp->p3], u.bz.val);
69895   }
69896   break;
69897 }
69898
69899 /* Opcode: RowSetTest P1 P2 P3 P4
69900 **
69901 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
69902 ** contains a RowSet object and that RowSet object contains
69903 ** the value held in P3, jump to register P2. Otherwise, insert the
69904 ** integer in P3 into the RowSet and continue on to the
69905 ** next opcode.
69906 **
69907 ** The RowSet object is optimized for the case where successive sets
69908 ** of integers, where each set contains no duplicates. Each set
69909 ** of values is identified by a unique P4 value. The first set
69910 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
69911 ** non-negative.  For non-negative values of P4 only the lower 4
69912 ** bits are significant.
69913 **
69914 ** This allows optimizations: (a) when P4==0 there is no need to test
69915 ** the rowset object for P3, as it is guaranteed not to contain it,
69916 ** (b) when P4==-1 there is no need to insert the value, as it will
69917 ** never be tested for, and (c) when a value that is part of set X is
69918 ** inserted, there is no need to search to see if the same value was
69919 ** previously inserted as part of set X (only if it was previously
69920 ** inserted as part of some other set).
69921 */
69922 case OP_RowSetTest: {                     /* jump, in1, in3 */
69923 #if 0  /* local variables moved into u.ca */
69924   int iSet;
69925   int exists;
69926 #endif /* local variables moved into u.ca */
69927
69928   pIn1 = &aMem[pOp->p1];
69929   pIn3 = &aMem[pOp->p3];
69930   u.ca.iSet = pOp->p4.i;
69931   assert( pIn3->flags&MEM_Int );
69932
69933   /* If there is anything other than a rowset object in memory cell P1,
69934   ** delete it now and initialize P1 with an empty rowset
69935   */
69936   if( (pIn1->flags & MEM_RowSet)==0 ){
69937     sqlcipher3VdbeMemSetRowSet(pIn1);
69938     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
69939   }
69940
69941   assert( pOp->p4type==P4_INT32 );
69942   assert( u.ca.iSet==-1 || u.ca.iSet>=0 );
69943   if( u.ca.iSet ){
69944     u.ca.exists = sqlcipher3RowSetTest(pIn1->u.pRowSet,
69945                                (u8)(u.ca.iSet>=0 ? u.ca.iSet & 0xf : 0xff),
69946                                pIn3->u.i);
69947     if( u.ca.exists ){
69948       pc = pOp->p2 - 1;
69949       break;
69950     }
69951   }
69952   if( u.ca.iSet>=0 ){
69953     sqlcipher3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
69954   }
69955   break;
69956 }
69957
69958
69959 #ifndef SQLCIPHER_OMIT_TRIGGER
69960
69961 /* Opcode: Program P1 P2 P3 P4 *
69962 **
69963 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
69964 **
69965 ** P1 contains the address of the memory cell that contains the first memory 
69966 ** cell in an array of values used as arguments to the sub-program. P2 
69967 ** contains the address to jump to if the sub-program throws an IGNORE 
69968 ** exception using the RAISE() function. Register P3 contains the address 
69969 ** of a memory cell in this (the parent) VM that is used to allocate the 
69970 ** memory required by the sub-vdbe at runtime.
69971 **
69972 ** P4 is a pointer to the VM containing the trigger program.
69973 */
69974 case OP_Program: {        /* jump */
69975 #if 0  /* local variables moved into u.cb */
69976   int nMem;               /* Number of memory registers for sub-program */
69977   int nByte;              /* Bytes of runtime space required for sub-program */
69978   Mem *pRt;               /* Register to allocate runtime space */
69979   Mem *pMem;              /* Used to iterate through memory cells */
69980   Mem *pEnd;              /* Last memory cell in new array */
69981   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
69982   SubProgram *pProgram;   /* Sub-program to execute */
69983   void *t;                /* Token identifying trigger */
69984 #endif /* local variables moved into u.cb */
69985
69986   u.cb.pProgram = pOp->p4.pProgram;
69987   u.cb.pRt = &aMem[pOp->p3];
69988   assert( memIsValid(u.cb.pRt) );
69989   assert( u.cb.pProgram->nOp>0 );
69990
69991   /* If the p5 flag is clear, then recursive invocation of triggers is
69992   ** disabled for backwards compatibility (p5 is set if this sub-program
69993   ** is really a trigger, not a foreign key action, and the flag set
69994   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
69995   **
69996   ** It is recursive invocation of triggers, at the SQL level, that is
69997   ** disabled. In some cases a single trigger may generate more than one
69998   ** SubProgram (if the trigger may be executed with more than one different
69999   ** ON CONFLICT algorithm). SubProgram structures associated with a
70000   ** single trigger all have the same value for the SubProgram.token
70001   ** variable.  */
70002   if( pOp->p5 ){
70003     u.cb.t = u.cb.pProgram->token;
70004     for(u.cb.pFrame=p->pFrame; u.cb.pFrame && u.cb.pFrame->token!=u.cb.t; u.cb.pFrame=u.cb.pFrame->pParent);
70005     if( u.cb.pFrame ) break;
70006   }
70007
70008   if( p->nFrame>=db->aLimit[SQLCIPHER_LIMIT_TRIGGER_DEPTH] ){
70009     rc = SQLCIPHER_ERROR;
70010     sqlcipher3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
70011     break;
70012   }
70013
70014   /* Register u.cb.pRt is used to store the memory required to save the state
70015   ** of the current program, and the memory required at runtime to execute
70016   ** the trigger program. If this trigger has been fired before, then u.cb.pRt
70017   ** is already allocated. Otherwise, it must be initialized.  */
70018   if( (u.cb.pRt->flags&MEM_Frame)==0 ){
70019     /* SubProgram.nMem is set to the number of memory cells used by the
70020     ** program stored in SubProgram.aOp. As well as these, one memory
70021     ** cell is required for each cursor used by the program. Set local
70022     ** variable u.cb.nMem (and later, VdbeFrame.nChildMem) to this value.
70023     */
70024     u.cb.nMem = u.cb.pProgram->nMem + u.cb.pProgram->nCsr;
70025     u.cb.nByte = ROUND8(sizeof(VdbeFrame))
70026               + u.cb.nMem * sizeof(Mem)
70027               + u.cb.pProgram->nCsr * sizeof(VdbeCursor *);
70028     u.cb.pFrame = sqlcipher3DbMallocZero(db, u.cb.nByte);
70029     if( !u.cb.pFrame ){
70030       goto no_mem;
70031     }
70032     sqlcipher3VdbeMemRelease(u.cb.pRt);
70033     u.cb.pRt->flags = MEM_Frame;
70034     u.cb.pRt->u.pFrame = u.cb.pFrame;
70035
70036     u.cb.pFrame->v = p;
70037     u.cb.pFrame->nChildMem = u.cb.nMem;
70038     u.cb.pFrame->nChildCsr = u.cb.pProgram->nCsr;
70039     u.cb.pFrame->pc = pc;
70040     u.cb.pFrame->aMem = p->aMem;
70041     u.cb.pFrame->nMem = p->nMem;
70042     u.cb.pFrame->apCsr = p->apCsr;
70043     u.cb.pFrame->nCursor = p->nCursor;
70044     u.cb.pFrame->aOp = p->aOp;
70045     u.cb.pFrame->nOp = p->nOp;
70046     u.cb.pFrame->token = u.cb.pProgram->token;
70047
70048     u.cb.pEnd = &VdbeFrameMem(u.cb.pFrame)[u.cb.pFrame->nChildMem];
70049     for(u.cb.pMem=VdbeFrameMem(u.cb.pFrame); u.cb.pMem!=u.cb.pEnd; u.cb.pMem++){
70050       u.cb.pMem->flags = MEM_Null;
70051       u.cb.pMem->db = db;
70052     }
70053   }else{
70054     u.cb.pFrame = u.cb.pRt->u.pFrame;
70055     assert( u.cb.pProgram->nMem+u.cb.pProgram->nCsr==u.cb.pFrame->nChildMem );
70056     assert( u.cb.pProgram->nCsr==u.cb.pFrame->nChildCsr );
70057     assert( pc==u.cb.pFrame->pc );
70058   }
70059
70060   p->nFrame++;
70061   u.cb.pFrame->pParent = p->pFrame;
70062   u.cb.pFrame->lastRowid = lastRowid;
70063   u.cb.pFrame->nChange = p->nChange;
70064   p->nChange = 0;
70065   p->pFrame = u.cb.pFrame;
70066   p->aMem = aMem = &VdbeFrameMem(u.cb.pFrame)[-1];
70067   p->nMem = u.cb.pFrame->nChildMem;
70068   p->nCursor = (u16)u.cb.pFrame->nChildCsr;
70069   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
70070   p->aOp = aOp = u.cb.pProgram->aOp;
70071   p->nOp = u.cb.pProgram->nOp;
70072   pc = -1;
70073
70074   break;
70075 }
70076
70077 /* Opcode: Param P1 P2 * * *
70078 **
70079 ** This opcode is only ever present in sub-programs called via the 
70080 ** OP_Program instruction. Copy a value currently stored in a memory 
70081 ** cell of the calling (parent) frame to cell P2 in the current frames 
70082 ** address space. This is used by trigger programs to access the new.* 
70083 ** and old.* values.
70084 **
70085 ** The address of the cell in the parent frame is determined by adding
70086 ** the value of the P1 argument to the value of the P1 argument to the
70087 ** calling OP_Program instruction.
70088 */
70089 case OP_Param: {           /* out2-prerelease */
70090 #if 0  /* local variables moved into u.cc */
70091   VdbeFrame *pFrame;
70092   Mem *pIn;
70093 #endif /* local variables moved into u.cc */
70094   u.cc.pFrame = p->pFrame;
70095   u.cc.pIn = &u.cc.pFrame->aMem[pOp->p1 + u.cc.pFrame->aOp[u.cc.pFrame->pc].p1];
70096   sqlcipher3VdbeMemShallowCopy(pOut, u.cc.pIn, MEM_Ephem);
70097   break;
70098 }
70099
70100 #endif /* #ifndef SQLCIPHER_OMIT_TRIGGER */
70101
70102 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
70103 /* Opcode: FkCounter P1 P2 * * *
70104 **
70105 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
70106 ** If P1 is non-zero, the database constraint counter is incremented 
70107 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
70108 ** statement counter is incremented (immediate foreign key constraints).
70109 */
70110 case OP_FkCounter: {
70111   if( pOp->p1 ){
70112     db->nDeferredCons += pOp->p2;
70113   }else{
70114     p->nFkConstraint += pOp->p2;
70115   }
70116   break;
70117 }
70118
70119 /* Opcode: FkIfZero P1 P2 * * *
70120 **
70121 ** This opcode tests if a foreign key constraint-counter is currently zero.
70122 ** If so, jump to instruction P2. Otherwise, fall through to the next 
70123 ** instruction.
70124 **
70125 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
70126 ** is zero (the one that counts deferred constraint violations). If P1 is
70127 ** zero, the jump is taken if the statement constraint-counter is zero
70128 ** (immediate foreign key constraint violations).
70129 */
70130 case OP_FkIfZero: {         /* jump */
70131   if( pOp->p1 ){
70132     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
70133   }else{
70134     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
70135   }
70136   break;
70137 }
70138 #endif /* #ifndef SQLCIPHER_OMIT_FOREIGN_KEY */
70139
70140 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
70141 /* Opcode: MemMax P1 P2 * * *
70142 **
70143 ** P1 is a register in the root frame of this VM (the root frame is
70144 ** different from the current frame if this instruction is being executed
70145 ** within a sub-program). Set the value of register P1 to the maximum of 
70146 ** its current value and the value in register P2.
70147 **
70148 ** This instruction throws an error if the memory cell is not initially
70149 ** an integer.
70150 */
70151 case OP_MemMax: {        /* in2 */
70152 #if 0  /* local variables moved into u.cd */
70153   Mem *pIn1;
70154   VdbeFrame *pFrame;
70155 #endif /* local variables moved into u.cd */
70156   if( p->pFrame ){
70157     for(u.cd.pFrame=p->pFrame; u.cd.pFrame->pParent; u.cd.pFrame=u.cd.pFrame->pParent);
70158     u.cd.pIn1 = &u.cd.pFrame->aMem[pOp->p1];
70159   }else{
70160     u.cd.pIn1 = &aMem[pOp->p1];
70161   }
70162   assert( memIsValid(u.cd.pIn1) );
70163   sqlcipher3VdbeMemIntegerify(u.cd.pIn1);
70164   pIn2 = &aMem[pOp->p2];
70165   sqlcipher3VdbeMemIntegerify(pIn2);
70166   if( u.cd.pIn1->u.i<pIn2->u.i){
70167     u.cd.pIn1->u.i = pIn2->u.i;
70168   }
70169   break;
70170 }
70171 #endif /* SQLCIPHER_OMIT_AUTOINCREMENT */
70172
70173 /* Opcode: IfPos P1 P2 * * *
70174 **
70175 ** If the value of register P1 is 1 or greater, jump to P2.
70176 **
70177 ** It is illegal to use this instruction on a register that does
70178 ** not contain an integer.  An assertion fault will result if you try.
70179 */
70180 case OP_IfPos: {        /* jump, in1 */
70181   pIn1 = &aMem[pOp->p1];
70182   assert( pIn1->flags&MEM_Int );
70183   if( pIn1->u.i>0 ){
70184      pc = pOp->p2 - 1;
70185   }
70186   break;
70187 }
70188
70189 /* Opcode: IfNeg P1 P2 * * *
70190 **
70191 ** If the value of register P1 is less than zero, jump to P2. 
70192 **
70193 ** It is illegal to use this instruction on a register that does
70194 ** not contain an integer.  An assertion fault will result if you try.
70195 */
70196 case OP_IfNeg: {        /* jump, in1 */
70197   pIn1 = &aMem[pOp->p1];
70198   assert( pIn1->flags&MEM_Int );
70199   if( pIn1->u.i<0 ){
70200      pc = pOp->p2 - 1;
70201   }
70202   break;
70203 }
70204
70205 /* Opcode: IfZero P1 P2 P3 * *
70206 **
70207 ** The register P1 must contain an integer.  Add literal P3 to the
70208 ** value in register P1.  If the result is exactly 0, jump to P2. 
70209 **
70210 ** It is illegal to use this instruction on a register that does
70211 ** not contain an integer.  An assertion fault will result if you try.
70212 */
70213 case OP_IfZero: {        /* jump, in1 */
70214   pIn1 = &aMem[pOp->p1];
70215   assert( pIn1->flags&MEM_Int );
70216   pIn1->u.i += pOp->p3;
70217   if( pIn1->u.i==0 ){
70218      pc = pOp->p2 - 1;
70219   }
70220   break;
70221 }
70222
70223 /* Opcode: AggStep * P2 P3 P4 P5
70224 **
70225 ** Execute the step function for an aggregate.  The
70226 ** function has P5 arguments.   P4 is a pointer to the FuncDef
70227 ** structure that specifies the function.  Use register
70228 ** P3 as the accumulator.
70229 **
70230 ** The P5 arguments are taken from register P2 and its
70231 ** successors.
70232 */
70233 case OP_AggStep: {
70234 #if 0  /* local variables moved into u.ce */
70235   int n;
70236   int i;
70237   Mem *pMem;
70238   Mem *pRec;
70239   sqlcipher3_context ctx;
70240   sqlcipher3_value **apVal;
70241 #endif /* local variables moved into u.ce */
70242
70243   u.ce.n = pOp->p5;
70244   assert( u.ce.n>=0 );
70245   u.ce.pRec = &aMem[pOp->p2];
70246   u.ce.apVal = p->apArg;
70247   assert( u.ce.apVal || u.ce.n==0 );
70248   for(u.ce.i=0; u.ce.i<u.ce.n; u.ce.i++, u.ce.pRec++){
70249     assert( memIsValid(u.ce.pRec) );
70250     u.ce.apVal[u.ce.i] = u.ce.pRec;
70251     memAboutToChange(p, u.ce.pRec);
70252     sqlcipher3VdbeMemStoreType(u.ce.pRec);
70253   }
70254   u.ce.ctx.pFunc = pOp->p4.pFunc;
70255   assert( pOp->p3>0 && pOp->p3<=p->nMem );
70256   u.ce.ctx.pMem = u.ce.pMem = &aMem[pOp->p3];
70257   u.ce.pMem->n++;
70258   u.ce.ctx.s.flags = MEM_Null;
70259   u.ce.ctx.s.z = 0;
70260   u.ce.ctx.s.zMalloc = 0;
70261   u.ce.ctx.s.xDel = 0;
70262   u.ce.ctx.s.db = db;
70263   u.ce.ctx.isError = 0;
70264   u.ce.ctx.pColl = 0;
70265   if( u.ce.ctx.pFunc->flags & SQLCIPHER_FUNC_NEEDCOLL ){
70266     assert( pOp>p->aOp );
70267     assert( pOp[-1].p4type==P4_COLLSEQ );
70268     assert( pOp[-1].opcode==OP_CollSeq );
70269     u.ce.ctx.pColl = pOp[-1].p4.pColl;
70270   }
70271   (u.ce.ctx.pFunc->xStep)(&u.ce.ctx, u.ce.n, u.ce.apVal); /* IMP: R-24505-23230 */
70272   if( u.ce.ctx.isError ){
70273     sqlcipher3SetString(&p->zErrMsg, db, "%s", sqlcipher3_value_text(&u.ce.ctx.s));
70274     rc = u.ce.ctx.isError;
70275   }
70276
70277   sqlcipher3VdbeMemRelease(&u.ce.ctx.s);
70278
70279   break;
70280 }
70281
70282 /* Opcode: AggFinal P1 P2 * P4 *
70283 **
70284 ** Execute the finalizer function for an aggregate.  P1 is
70285 ** the memory location that is the accumulator for the aggregate.
70286 **
70287 ** P2 is the number of arguments that the step function takes and
70288 ** P4 is a pointer to the FuncDef for this function.  The P2
70289 ** argument is not used by this opcode.  It is only there to disambiguate
70290 ** functions that can take varying numbers of arguments.  The
70291 ** P4 argument is only needed for the degenerate case where
70292 ** the step function was not previously called.
70293 */
70294 case OP_AggFinal: {
70295 #if 0  /* local variables moved into u.cf */
70296   Mem *pMem;
70297 #endif /* local variables moved into u.cf */
70298   assert( pOp->p1>0 && pOp->p1<=p->nMem );
70299   u.cf.pMem = &aMem[pOp->p1];
70300   assert( (u.cf.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
70301   rc = sqlcipher3VdbeMemFinalize(u.cf.pMem, pOp->p4.pFunc);
70302   if( rc ){
70303     sqlcipher3SetString(&p->zErrMsg, db, "%s", sqlcipher3_value_text(u.cf.pMem));
70304   }
70305   sqlcipher3VdbeChangeEncoding(u.cf.pMem, encoding);
70306   UPDATE_MAX_BLOBSIZE(u.cf.pMem);
70307   if( sqlcipher3VdbeMemTooBig(u.cf.pMem) ){
70308     goto too_big;
70309   }
70310   break;
70311 }
70312
70313 #ifndef SQLCIPHER_OMIT_WAL
70314 /* Opcode: Checkpoint P1 P2 P3 * *
70315 **
70316 ** Checkpoint database P1. This is a no-op if P1 is not currently in
70317 ** WAL mode. Parameter P2 is one of SQLCIPHER_CHECKPOINT_PASSIVE, FULL
70318 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
70319 ** SQLCIPHER_BUSY or not, respectively.  Write the number of pages in the
70320 ** WAL after the checkpoint into mem[P3+1] and the number of pages
70321 ** in the WAL that have been checkpointed after the checkpoint
70322 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
70323 ** mem[P3+2] are initialized to -1.
70324 */
70325 case OP_Checkpoint: {
70326 #if 0  /* local variables moved into u.cg */
70327   int i;                          /* Loop counter */
70328   int aRes[3];                    /* Results */
70329   Mem *pMem;                      /* Write results here */
70330 #endif /* local variables moved into u.cg */
70331
70332   u.cg.aRes[0] = 0;
70333   u.cg.aRes[1] = u.cg.aRes[2] = -1;
70334   assert( pOp->p2==SQLCIPHER_CHECKPOINT_PASSIVE
70335        || pOp->p2==SQLCIPHER_CHECKPOINT_FULL
70336        || pOp->p2==SQLCIPHER_CHECKPOINT_RESTART
70337   );
70338   rc = sqlcipher3Checkpoint(db, pOp->p1, pOp->p2, &u.cg.aRes[1], &u.cg.aRes[2]);
70339   if( rc==SQLCIPHER_BUSY ){
70340     rc = SQLCIPHER_OK;
70341     u.cg.aRes[0] = 1;
70342   }
70343   for(u.cg.i=0, u.cg.pMem = &aMem[pOp->p3]; u.cg.i<3; u.cg.i++, u.cg.pMem++){
70344     sqlcipher3VdbeMemSetInt64(u.cg.pMem, (i64)u.cg.aRes[u.cg.i]);
70345   }
70346   break;
70347 };  
70348 #endif
70349
70350 #ifndef SQLCIPHER_OMIT_PRAGMA
70351 /* Opcode: JournalMode P1 P2 P3 * P5
70352 **
70353 ** Change the journal mode of database P1 to P3. P3 must be one of the
70354 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
70355 ** modes (delete, truncate, persist, off and memory), this is a simple
70356 ** operation. No IO is required.
70357 **
70358 ** If changing into or out of WAL mode the procedure is more complicated.
70359 **
70360 ** Write a string containing the final journal-mode to register P2.
70361 */
70362 case OP_JournalMode: {    /* out2-prerelease */
70363 #if 0  /* local variables moved into u.ch */
70364   Btree *pBt;                     /* Btree to change journal mode of */
70365   Pager *pPager;                  /* Pager associated with pBt */
70366   int eNew;                       /* New journal mode */
70367   int eOld;                       /* The old journal mode */
70368   const char *zFilename;          /* Name of database file for pPager */
70369 #endif /* local variables moved into u.ch */
70370
70371   u.ch.eNew = pOp->p3;
70372   assert( u.ch.eNew==PAGER_JOURNALMODE_DELETE
70373        || u.ch.eNew==PAGER_JOURNALMODE_TRUNCATE
70374        || u.ch.eNew==PAGER_JOURNALMODE_PERSIST
70375        || u.ch.eNew==PAGER_JOURNALMODE_OFF
70376        || u.ch.eNew==PAGER_JOURNALMODE_MEMORY
70377        || u.ch.eNew==PAGER_JOURNALMODE_WAL
70378        || u.ch.eNew==PAGER_JOURNALMODE_QUERY
70379   );
70380   assert( pOp->p1>=0 && pOp->p1<db->nDb );
70381
70382   u.ch.pBt = db->aDb[pOp->p1].pBt;
70383   u.ch.pPager = sqlcipher3BtreePager(u.ch.pBt);
70384   u.ch.eOld = sqlcipher3PagerGetJournalMode(u.ch.pPager);
70385   if( u.ch.eNew==PAGER_JOURNALMODE_QUERY ) u.ch.eNew = u.ch.eOld;
70386   if( !sqlcipher3PagerOkToChangeJournalMode(u.ch.pPager) ) u.ch.eNew = u.ch.eOld;
70387
70388 #ifndef SQLCIPHER_OMIT_WAL
70389   u.ch.zFilename = sqlcipher3PagerFilename(u.ch.pPager);
70390
70391   /* Do not allow a transition to journal_mode=WAL for a database
70392   ** in temporary storage or if the VFS does not support shared memory
70393   */
70394   if( u.ch.eNew==PAGER_JOURNALMODE_WAL
70395    && (sqlcipher3Strlen30(u.ch.zFilename)==0           /* Temp file */
70396        || !sqlcipher3PagerWalSupported(u.ch.pPager))   /* No shared-memory support */
70397   ){
70398     u.ch.eNew = u.ch.eOld;
70399   }
70400
70401   if( (u.ch.eNew!=u.ch.eOld)
70402    && (u.ch.eOld==PAGER_JOURNALMODE_WAL || u.ch.eNew==PAGER_JOURNALMODE_WAL)
70403   ){
70404     if( !db->autoCommit || db->activeVdbeCnt>1 ){
70405       rc = SQLCIPHER_ERROR;
70406       sqlcipher3SetString(&p->zErrMsg, db,
70407           "cannot change %s wal mode from within a transaction",
70408           (u.ch.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
70409       );
70410       break;
70411     }else{
70412
70413       if( u.ch.eOld==PAGER_JOURNALMODE_WAL ){
70414         /* If leaving WAL mode, close the log file. If successful, the call
70415         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
70416         ** file. An EXCLUSIVE lock may still be held on the database file
70417         ** after a successful return.
70418         */
70419         rc = sqlcipher3PagerCloseWal(u.ch.pPager);
70420         if( rc==SQLCIPHER_OK ){
70421           sqlcipher3PagerSetJournalMode(u.ch.pPager, u.ch.eNew);
70422         }
70423       }else if( u.ch.eOld==PAGER_JOURNALMODE_MEMORY ){
70424         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
70425         ** as an intermediate */
70426         sqlcipher3PagerSetJournalMode(u.ch.pPager, PAGER_JOURNALMODE_OFF);
70427       }
70428
70429       /* Open a transaction on the database file. Regardless of the journal
70430       ** mode, this transaction always uses a rollback journal.
70431       */
70432       assert( sqlcipher3BtreeIsInTrans(u.ch.pBt)==0 );
70433       if( rc==SQLCIPHER_OK ){
70434         rc = sqlcipher3BtreeSetVersion(u.ch.pBt, (u.ch.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
70435       }
70436     }
70437   }
70438 #endif /* ifndef SQLCIPHER_OMIT_WAL */
70439
70440   if( rc ){
70441     u.ch.eNew = u.ch.eOld;
70442   }
70443   u.ch.eNew = sqlcipher3PagerSetJournalMode(u.ch.pPager, u.ch.eNew);
70444
70445   pOut = &aMem[pOp->p2];
70446   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
70447   pOut->z = (char *)sqlcipher3JournalModename(u.ch.eNew);
70448   pOut->n = sqlcipher3Strlen30(pOut->z);
70449   pOut->enc = SQLCIPHER_UTF8;
70450   sqlcipher3VdbeChangeEncoding(pOut, encoding);
70451   break;
70452 };
70453 #endif /* SQLCIPHER_OMIT_PRAGMA */
70454
70455 #if !defined(SQLCIPHER_OMIT_VACUUM) && !defined(SQLCIPHER_OMIT_ATTACH)
70456 /* Opcode: Vacuum * * * * *
70457 **
70458 ** Vacuum the entire database.  This opcode will cause other virtual
70459 ** machines to be created and run.  It may not be called from within
70460 ** a transaction.
70461 */
70462 case OP_Vacuum: {
70463   rc = sqlcipher3RunVacuum(&p->zErrMsg, db);
70464   break;
70465 }
70466 #endif
70467
70468 #if !defined(SQLCIPHER_OMIT_AUTOVACUUM)
70469 /* Opcode: IncrVacuum P1 P2 * * *
70470 **
70471 ** Perform a single step of the incremental vacuum procedure on
70472 ** the P1 database. If the vacuum has finished, jump to instruction
70473 ** P2. Otherwise, fall through to the next instruction.
70474 */
70475 case OP_IncrVacuum: {        /* jump */
70476 #if 0  /* local variables moved into u.ci */
70477   Btree *pBt;
70478 #endif /* local variables moved into u.ci */
70479
70480   assert( pOp->p1>=0 && pOp->p1<db->nDb );
70481   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
70482   u.ci.pBt = db->aDb[pOp->p1].pBt;
70483   rc = sqlcipher3BtreeIncrVacuum(u.ci.pBt);
70484   if( rc==SQLCIPHER_DONE ){
70485     pc = pOp->p2 - 1;
70486     rc = SQLCIPHER_OK;
70487   }
70488   break;
70489 }
70490 #endif
70491
70492 /* Opcode: Expire P1 * * * *
70493 **
70494 ** Cause precompiled statements to become expired. An expired statement
70495 ** fails with an error code of SQLCIPHER_SCHEMA if it is ever executed 
70496 ** (via sqlcipher3_step()).
70497 ** 
70498 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
70499 ** then only the currently executing statement is affected. 
70500 */
70501 case OP_Expire: {
70502   if( !pOp->p1 ){
70503     sqlcipher3ExpirePreparedStatements(db);
70504   }else{
70505     p->expired = 1;
70506   }
70507   break;
70508 }
70509
70510 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
70511 /* Opcode: TableLock P1 P2 P3 P4 *
70512 **
70513 ** Obtain a lock on a particular table. This instruction is only used when
70514 ** the shared-cache feature is enabled. 
70515 **
70516 ** P1 is the index of the database in sqlcipher3.aDb[] of the database
70517 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
70518 ** a write lock if P3==1.
70519 **
70520 ** P2 contains the root-page of the table to lock.
70521 **
70522 ** P4 contains a pointer to the name of the table being locked. This is only
70523 ** used to generate an error message if the lock cannot be obtained.
70524 */
70525 case OP_TableLock: {
70526   u8 isWriteLock = (u8)pOp->p3;
70527   if( isWriteLock || 0==(db->flags&SQLCIPHER_ReadUncommitted) ){
70528     int p1 = pOp->p1; 
70529     assert( p1>=0 && p1<db->nDb );
70530     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
70531     assert( isWriteLock==0 || isWriteLock==1 );
70532     rc = sqlcipher3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
70533     if( (rc&0xFF)==SQLCIPHER_LOCKED ){
70534       const char *z = pOp->p4.z;
70535       sqlcipher3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
70536     }
70537   }
70538   break;
70539 }
70540 #endif /* SQLCIPHER_OMIT_SHARED_CACHE */
70541
70542 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70543 /* Opcode: VBegin * * * P4 *
70544 **
70545 ** P4 may be a pointer to an sqlcipher3_vtab structure. If so, call the 
70546 ** xBegin method for that table.
70547 **
70548 ** Also, whether or not P4 is set, check that this is not being called from
70549 ** within a callback to a virtual table xSync() method. If it is, the error
70550 ** code will be set to SQLCIPHER_LOCKED.
70551 */
70552 case OP_VBegin: {
70553 #if 0  /* local variables moved into u.cj */
70554   VTable *pVTab;
70555 #endif /* local variables moved into u.cj */
70556   u.cj.pVTab = pOp->p4.pVtab;
70557   rc = sqlcipher3VtabBegin(db, u.cj.pVTab);
70558   if( u.cj.pVTab ) importVtabErrMsg(p, u.cj.pVTab->pVtab);
70559   break;
70560 }
70561 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70562
70563 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70564 /* Opcode: VCreate P1 * * P4 *
70565 **
70566 ** P4 is the name of a virtual table in database P1. Call the xCreate method
70567 ** for that table.
70568 */
70569 case OP_VCreate: {
70570   rc = sqlcipher3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
70571   break;
70572 }
70573 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70574
70575 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70576 /* Opcode: VDestroy P1 * * P4 *
70577 **
70578 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
70579 ** of that table.
70580 */
70581 case OP_VDestroy: {
70582   p->inVtabMethod = 2;
70583   rc = sqlcipher3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
70584   p->inVtabMethod = 0;
70585   break;
70586 }
70587 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70588
70589 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70590 /* Opcode: VOpen P1 * * P4 *
70591 **
70592 ** P4 is a pointer to a virtual table object, an sqlcipher3_vtab structure.
70593 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
70594 ** table and stores that cursor in P1.
70595 */
70596 case OP_VOpen: {
70597 #if 0  /* local variables moved into u.ck */
70598   VdbeCursor *pCur;
70599   sqlcipher3_vtab_cursor *pVtabCursor;
70600   sqlcipher3_vtab *pVtab;
70601   sqlcipher3_module *pModule;
70602 #endif /* local variables moved into u.ck */
70603
70604   u.ck.pCur = 0;
70605   u.ck.pVtabCursor = 0;
70606   u.ck.pVtab = pOp->p4.pVtab->pVtab;
70607   u.ck.pModule = (sqlcipher3_module *)u.ck.pVtab->pModule;
70608   assert(u.ck.pVtab && u.ck.pModule);
70609   rc = u.ck.pModule->xOpen(u.ck.pVtab, &u.ck.pVtabCursor);
70610   importVtabErrMsg(p, u.ck.pVtab);
70611   if( SQLCIPHER_OK==rc ){
70612     /* Initialize sqlcipher3_vtab_cursor base class */
70613     u.ck.pVtabCursor->pVtab = u.ck.pVtab;
70614
70615     /* Initialise vdbe cursor object */
70616     u.ck.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
70617     if( u.ck.pCur ){
70618       u.ck.pCur->pVtabCursor = u.ck.pVtabCursor;
70619       u.ck.pCur->pModule = u.ck.pVtabCursor->pVtab->pModule;
70620     }else{
70621       db->mallocFailed = 1;
70622       u.ck.pModule->xClose(u.ck.pVtabCursor);
70623     }
70624   }
70625   break;
70626 }
70627 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70628
70629 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70630 /* Opcode: VFilter P1 P2 P3 P4 *
70631 **
70632 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
70633 ** the filtered result set is empty.
70634 **
70635 ** P4 is either NULL or a string that was generated by the xBestIndex
70636 ** method of the module.  The interpretation of the P4 string is left
70637 ** to the module implementation.
70638 **
70639 ** This opcode invokes the xFilter method on the virtual table specified
70640 ** by P1.  The integer query plan parameter to xFilter is stored in register
70641 ** P3. Register P3+1 stores the argc parameter to be passed to the
70642 ** xFilter method. Registers P3+2..P3+1+argc are the argc
70643 ** additional parameters which are passed to
70644 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
70645 **
70646 ** A jump is made to P2 if the result set after filtering would be empty.
70647 */
70648 case OP_VFilter: {   /* jump */
70649 #if 0  /* local variables moved into u.cl */
70650   int nArg;
70651   int iQuery;
70652   const sqlcipher3_module *pModule;
70653   Mem *pQuery;
70654   Mem *pArgc;
70655   sqlcipher3_vtab_cursor *pVtabCursor;
70656   sqlcipher3_vtab *pVtab;
70657   VdbeCursor *pCur;
70658   int res;
70659   int i;
70660   Mem **apArg;
70661 #endif /* local variables moved into u.cl */
70662
70663   u.cl.pQuery = &aMem[pOp->p3];
70664   u.cl.pArgc = &u.cl.pQuery[1];
70665   u.cl.pCur = p->apCsr[pOp->p1];
70666   assert( memIsValid(u.cl.pQuery) );
70667   REGISTER_TRACE(pOp->p3, u.cl.pQuery);
70668   assert( u.cl.pCur->pVtabCursor );
70669   u.cl.pVtabCursor = u.cl.pCur->pVtabCursor;
70670   u.cl.pVtab = u.cl.pVtabCursor->pVtab;
70671   u.cl.pModule = u.cl.pVtab->pModule;
70672
70673   /* Grab the index number and argc parameters */
70674   assert( (u.cl.pQuery->flags&MEM_Int)!=0 && u.cl.pArgc->flags==MEM_Int );
70675   u.cl.nArg = (int)u.cl.pArgc->u.i;
70676   u.cl.iQuery = (int)u.cl.pQuery->u.i;
70677
70678   /* Invoke the xFilter method */
70679   {
70680     u.cl.res = 0;
70681     u.cl.apArg = p->apArg;
70682     for(u.cl.i = 0; u.cl.i<u.cl.nArg; u.cl.i++){
70683       u.cl.apArg[u.cl.i] = &u.cl.pArgc[u.cl.i+1];
70684       sqlcipher3VdbeMemStoreType(u.cl.apArg[u.cl.i]);
70685     }
70686
70687     p->inVtabMethod = 1;
70688     rc = u.cl.pModule->xFilter(u.cl.pVtabCursor, u.cl.iQuery, pOp->p4.z, u.cl.nArg, u.cl.apArg);
70689     p->inVtabMethod = 0;
70690     importVtabErrMsg(p, u.cl.pVtab);
70691     if( rc==SQLCIPHER_OK ){
70692       u.cl.res = u.cl.pModule->xEof(u.cl.pVtabCursor);
70693     }
70694
70695     if( u.cl.res ){
70696       pc = pOp->p2 - 1;
70697     }
70698   }
70699   u.cl.pCur->nullRow = 0;
70700
70701   break;
70702 }
70703 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70704
70705 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70706 /* Opcode: VColumn P1 P2 P3 * *
70707 **
70708 ** Store the value of the P2-th column of
70709 ** the row of the virtual-table that the 
70710 ** P1 cursor is pointing to into register P3.
70711 */
70712 case OP_VColumn: {
70713 #if 0  /* local variables moved into u.cm */
70714   sqlcipher3_vtab *pVtab;
70715   const sqlcipher3_module *pModule;
70716   Mem *pDest;
70717   sqlcipher3_context sContext;
70718 #endif /* local variables moved into u.cm */
70719
70720   VdbeCursor *pCur = p->apCsr[pOp->p1];
70721   assert( pCur->pVtabCursor );
70722   assert( pOp->p3>0 && pOp->p3<=p->nMem );
70723   u.cm.pDest = &aMem[pOp->p3];
70724   memAboutToChange(p, u.cm.pDest);
70725   if( pCur->nullRow ){
70726     sqlcipher3VdbeMemSetNull(u.cm.pDest);
70727     break;
70728   }
70729   u.cm.pVtab = pCur->pVtabCursor->pVtab;
70730   u.cm.pModule = u.cm.pVtab->pModule;
70731   assert( u.cm.pModule->xColumn );
70732   memset(&u.cm.sContext, 0, sizeof(u.cm.sContext));
70733
70734   /* The output cell may already have a buffer allocated. Move
70735   ** the current contents to u.cm.sContext.s so in case the user-function
70736   ** can use the already allocated buffer instead of allocating a
70737   ** new one.
70738   */
70739   sqlcipher3VdbeMemMove(&u.cm.sContext.s, u.cm.pDest);
70740   MemSetTypeFlag(&u.cm.sContext.s, MEM_Null);
70741
70742   rc = u.cm.pModule->xColumn(pCur->pVtabCursor, &u.cm.sContext, pOp->p2);
70743   importVtabErrMsg(p, u.cm.pVtab);
70744   if( u.cm.sContext.isError ){
70745     rc = u.cm.sContext.isError;
70746   }
70747
70748   /* Copy the result of the function to the P3 register. We
70749   ** do this regardless of whether or not an error occurred to ensure any
70750   ** dynamic allocation in u.cm.sContext.s (a Mem struct) is  released.
70751   */
70752   sqlcipher3VdbeChangeEncoding(&u.cm.sContext.s, encoding);
70753   sqlcipher3VdbeMemMove(u.cm.pDest, &u.cm.sContext.s);
70754   REGISTER_TRACE(pOp->p3, u.cm.pDest);
70755   UPDATE_MAX_BLOBSIZE(u.cm.pDest);
70756
70757   if( sqlcipher3VdbeMemTooBig(u.cm.pDest) ){
70758     goto too_big;
70759   }
70760   break;
70761 }
70762 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70763
70764 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70765 /* Opcode: VNext P1 P2 * * *
70766 **
70767 ** Advance virtual table P1 to the next row in its result set and
70768 ** jump to instruction P2.  Or, if the virtual table has reached
70769 ** the end of its result set, then fall through to the next instruction.
70770 */
70771 case OP_VNext: {   /* jump */
70772 #if 0  /* local variables moved into u.cn */
70773   sqlcipher3_vtab *pVtab;
70774   const sqlcipher3_module *pModule;
70775   int res;
70776   VdbeCursor *pCur;
70777 #endif /* local variables moved into u.cn */
70778
70779   u.cn.res = 0;
70780   u.cn.pCur = p->apCsr[pOp->p1];
70781   assert( u.cn.pCur->pVtabCursor );
70782   if( u.cn.pCur->nullRow ){
70783     break;
70784   }
70785   u.cn.pVtab = u.cn.pCur->pVtabCursor->pVtab;
70786   u.cn.pModule = u.cn.pVtab->pModule;
70787   assert( u.cn.pModule->xNext );
70788
70789   /* Invoke the xNext() method of the module. There is no way for the
70790   ** underlying implementation to return an error if one occurs during
70791   ** xNext(). Instead, if an error occurs, true is returned (indicating that
70792   ** data is available) and the error code returned when xColumn or
70793   ** some other method is next invoked on the save virtual table cursor.
70794   */
70795   p->inVtabMethod = 1;
70796   rc = u.cn.pModule->xNext(u.cn.pCur->pVtabCursor);
70797   p->inVtabMethod = 0;
70798   importVtabErrMsg(p, u.cn.pVtab);
70799   if( rc==SQLCIPHER_OK ){
70800     u.cn.res = u.cn.pModule->xEof(u.cn.pCur->pVtabCursor);
70801   }
70802
70803   if( !u.cn.res ){
70804     /* If there is data, jump to P2 */
70805     pc = pOp->p2 - 1;
70806   }
70807   break;
70808 }
70809 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70810
70811 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70812 /* Opcode: VRename P1 * * P4 *
70813 **
70814 ** P4 is a pointer to a virtual table object, an sqlcipher3_vtab structure.
70815 ** This opcode invokes the corresponding xRename method. The value
70816 ** in register P1 is passed as the zName argument to the xRename method.
70817 */
70818 case OP_VRename: {
70819 #if 0  /* local variables moved into u.co */
70820   sqlcipher3_vtab *pVtab;
70821   Mem *pName;
70822 #endif /* local variables moved into u.co */
70823
70824   u.co.pVtab = pOp->p4.pVtab->pVtab;
70825   u.co.pName = &aMem[pOp->p1];
70826   assert( u.co.pVtab->pModule->xRename );
70827   assert( memIsValid(u.co.pName) );
70828   REGISTER_TRACE(pOp->p1, u.co.pName);
70829   assert( u.co.pName->flags & MEM_Str );
70830   testcase( u.co.pName->enc==SQLCIPHER_UTF8 );
70831   testcase( u.co.pName->enc==SQLCIPHER_UTF16BE );
70832   testcase( u.co.pName->enc==SQLCIPHER_UTF16LE );
70833   rc = sqlcipher3VdbeChangeEncoding(u.co.pName, SQLCIPHER_UTF8);
70834   if( rc==SQLCIPHER_OK ){
70835     rc = u.co.pVtab->pModule->xRename(u.co.pVtab, u.co.pName->z);
70836     importVtabErrMsg(p, u.co.pVtab);
70837     p->expired = 0;
70838   }
70839   break;
70840 }
70841 #endif
70842
70843 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70844 /* Opcode: VUpdate P1 P2 P3 P4 *
70845 **
70846 ** P4 is a pointer to a virtual table object, an sqlcipher3_vtab structure.
70847 ** This opcode invokes the corresponding xUpdate method. P2 values
70848 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
70849 ** invocation. The value in register (P3+P2-1) corresponds to the 
70850 ** p2th element of the argv array passed to xUpdate.
70851 **
70852 ** The xUpdate method will do a DELETE or an INSERT or both.
70853 ** The argv[0] element (which corresponds to memory cell P3)
70854 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
70855 ** deletion occurs.  The argv[1] element is the rowid of the new 
70856 ** row.  This can be NULL to have the virtual table select the new 
70857 ** rowid for itself.  The subsequent elements in the array are 
70858 ** the values of columns in the new row.
70859 **
70860 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
70861 ** a row to delete.
70862 **
70863 ** P1 is a boolean flag. If it is set to true and the xUpdate call
70864 ** is successful, then the value returned by sqlcipher3_last_insert_rowid() 
70865 ** is set to the value of the rowid for the row just inserted.
70866 */
70867 case OP_VUpdate: {
70868 #if 0  /* local variables moved into u.cp */
70869   sqlcipher3_vtab *pVtab;
70870   sqlcipher3_module *pModule;
70871   int nArg;
70872   int i;
70873   sqlcipher_int64 rowid;
70874   Mem **apArg;
70875   Mem *pX;
70876 #endif /* local variables moved into u.cp */
70877
70878   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
70879        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
70880   );
70881   u.cp.pVtab = pOp->p4.pVtab->pVtab;
70882   u.cp.pModule = (sqlcipher3_module *)u.cp.pVtab->pModule;
70883   u.cp.nArg = pOp->p2;
70884   assert( pOp->p4type==P4_VTAB );
70885   if( ALWAYS(u.cp.pModule->xUpdate) ){
70886     u8 vtabOnConflict = db->vtabOnConflict;
70887     u.cp.apArg = p->apArg;
70888     u.cp.pX = &aMem[pOp->p3];
70889     for(u.cp.i=0; u.cp.i<u.cp.nArg; u.cp.i++){
70890       assert( memIsValid(u.cp.pX) );
70891       memAboutToChange(p, u.cp.pX);
70892       sqlcipher3VdbeMemStoreType(u.cp.pX);
70893       u.cp.apArg[u.cp.i] = u.cp.pX;
70894       u.cp.pX++;
70895     }
70896     db->vtabOnConflict = pOp->p5;
70897     rc = u.cp.pModule->xUpdate(u.cp.pVtab, u.cp.nArg, u.cp.apArg, &u.cp.rowid);
70898     db->vtabOnConflict = vtabOnConflict;
70899     importVtabErrMsg(p, u.cp.pVtab);
70900     if( rc==SQLCIPHER_OK && pOp->p1 ){
70901       assert( u.cp.nArg>1 && u.cp.apArg[0] && (u.cp.apArg[0]->flags&MEM_Null) );
70902       db->lastRowid = lastRowid = u.cp.rowid;
70903     }
70904     if( rc==SQLCIPHER_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
70905       if( pOp->p5==OE_Ignore ){
70906         rc = SQLCIPHER_OK;
70907       }else{
70908         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
70909       }
70910     }else{
70911       p->nChange++;
70912     }
70913   }
70914   break;
70915 }
70916 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70917
70918 #ifndef  SQLCIPHER_OMIT_PAGER_PRAGMAS
70919 /* Opcode: Pagecount P1 P2 * * *
70920 **
70921 ** Write the current number of pages in database P1 to memory cell P2.
70922 */
70923 case OP_Pagecount: {            /* out2-prerelease */
70924   pOut->u.i = sqlcipher3BtreeLastPage(db->aDb[pOp->p1].pBt);
70925   break;
70926 }
70927 #endif
70928
70929
70930 #ifndef  SQLCIPHER_OMIT_PAGER_PRAGMAS
70931 /* Opcode: MaxPgcnt P1 P2 P3 * *
70932 **
70933 ** Try to set the maximum page count for database P1 to the value in P3.
70934 ** Do not let the maximum page count fall below the current page count and
70935 ** do not change the maximum page count value if P3==0.
70936 **
70937 ** Store the maximum page count after the change in register P2.
70938 */
70939 case OP_MaxPgcnt: {            /* out2-prerelease */
70940   unsigned int newMax;
70941   Btree *pBt;
70942
70943   pBt = db->aDb[pOp->p1].pBt;
70944   newMax = 0;
70945   if( pOp->p3 ){
70946     newMax = sqlcipher3BtreeLastPage(pBt);
70947     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
70948   }
70949   pOut->u.i = sqlcipher3BtreeMaxPageCount(pBt, newMax);
70950   break;
70951 }
70952 #endif
70953
70954
70955 #ifndef SQLCIPHER_OMIT_TRACE
70956 /* Opcode: Trace * * * P4 *
70957 **
70958 ** If tracing is enabled (by the sqlcipher3_trace()) interface, then
70959 ** the UTF-8 string contained in P4 is emitted on the trace callback.
70960 */
70961 case OP_Trace: {
70962 #if 0  /* local variables moved into u.cq */
70963   char *zTrace;
70964   char *z;
70965 #endif /* local variables moved into u.cq */
70966
70967   if( db->xTrace && (u.cq.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){
70968     u.cq.z = sqlcipher3VdbeExpandSql(p, u.cq.zTrace);
70969     db->xTrace(db->pTraceArg, u.cq.z);
70970     sqlcipher3DbFree(db, u.cq.z);
70971   }
70972 #ifdef SQLCIPHER_DEBUG
70973   if( (db->flags & SQLCIPHER_SqlTrace)!=0
70974    && (u.cq.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
70975   ){
70976     sqlcipher3DebugPrintf("SQL-trace: %s\n", u.cq.zTrace);
70977   }
70978 #endif /* SQLCIPHER_DEBUG */
70979   break;
70980 }
70981 #endif
70982
70983
70984 /* Opcode: Noop * * * * *
70985 **
70986 ** Do nothing.  This instruction is often useful as a jump
70987 ** destination.
70988 */
70989 /*
70990 ** The magic Explain opcode are only inserted when explain==2 (which
70991 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
70992 ** This opcode records information from the optimizer.  It is the
70993 ** the same as a no-op.  This opcodesnever appears in a real VM program.
70994 */
70995 default: {          /* This is really OP_Noop and OP_Explain */
70996   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
70997   break;
70998 }
70999
71000 /*****************************************************************************
71001 ** The cases of the switch statement above this line should all be indented
71002 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
71003 ** readability.  From this point on down, the normal indentation rules are
71004 ** restored.
71005 *****************************************************************************/
71006     }
71007
71008 #ifdef VDBE_PROFILE
71009     {
71010       u64 elapsed = sqlcipher3Hwtime() - start;
71011       pOp->cycles += elapsed;
71012       pOp->cnt++;
71013 #if 0
71014         fprintf(stdout, "%10llu ", elapsed);
71015         sqlcipher3VdbePrintOp(stdout, origPc, &aOp[origPc]);
71016 #endif
71017     }
71018 #endif
71019
71020     /* The following code adds nothing to the actual functionality
71021     ** of the program.  It is only here for testing and debugging.
71022     ** On the other hand, it does burn CPU cycles every time through
71023     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
71024     */
71025 #ifndef NDEBUG
71026     assert( pc>=-1 && pc<p->nOp );
71027
71028 #ifdef SQLCIPHER_DEBUG
71029     if( p->trace ){
71030       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
71031       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
71032         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
71033       }
71034       if( pOp->opflags & OPFLG_OUT3 ){
71035         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
71036       }
71037     }
71038 #endif  /* SQLCIPHER_DEBUG */
71039 #endif  /* NDEBUG */
71040   }  /* The end of the for(;;) loop the loops through opcodes */
71041
71042   /* If we reach this point, it means that execution is finished with
71043   ** an error of some kind.
71044   */
71045 vdbe_error_halt:
71046   assert( rc );
71047   p->rc = rc;
71048   testcase( sqlcipher3GlobalConfig.xLog!=0 );
71049   sqlcipher3_log(rc, "statement aborts at %d: [%s] %s", 
71050                    pc, p->zSql, p->zErrMsg);
71051   sqlcipher3VdbeHalt(p);
71052   if( rc==SQLCIPHER_IOERR_NOMEM ) db->mallocFailed = 1;
71053   rc = SQLCIPHER_ERROR;
71054   if( resetSchemaOnFault>0 ){
71055     sqlcipher3ResetInternalSchema(db, resetSchemaOnFault-1);
71056   }
71057
71058   /* This is the only way out of this procedure.  We have to
71059   ** release the mutexes on btrees that were acquired at the
71060   ** top. */
71061 vdbe_return:
71062   db->lastRowid = lastRowid;
71063   sqlcipher3VdbeLeave(p);
71064   return rc;
71065
71066   /* Jump to here if a string or blob larger than SQLCIPHER_MAX_LENGTH
71067   ** is encountered.
71068   */
71069 too_big:
71070   sqlcipher3SetString(&p->zErrMsg, db, "string or blob too big");
71071   rc = SQLCIPHER_TOOBIG;
71072   goto vdbe_error_halt;
71073
71074   /* Jump to here if a malloc() fails.
71075   */
71076 no_mem:
71077   db->mallocFailed = 1;
71078   sqlcipher3SetString(&p->zErrMsg, db, "out of memory");
71079   rc = SQLCIPHER_NOMEM;
71080   goto vdbe_error_halt;
71081
71082   /* Jump to here for any other kind of fatal error.  The "rc" variable
71083   ** should hold the error number.
71084   */
71085 abort_due_to_error:
71086   assert( p->zErrMsg==0 );
71087   if( db->mallocFailed ) rc = SQLCIPHER_NOMEM;
71088   if( rc!=SQLCIPHER_IOERR_NOMEM ){
71089     sqlcipher3SetString(&p->zErrMsg, db, "%s", sqlcipher3ErrStr(rc));
71090   }
71091   goto vdbe_error_halt;
71092
71093   /* Jump to here if the sqlcipher3_interrupt() API sets the interrupt
71094   ** flag.
71095   */
71096 abort_due_to_interrupt:
71097   assert( db->u1.isInterrupted );
71098   rc = SQLCIPHER_INTERRUPT;
71099   p->rc = rc;
71100   sqlcipher3SetString(&p->zErrMsg, db, "%s", sqlcipher3ErrStr(rc));
71101   goto vdbe_error_halt;
71102 }
71103
71104 /************** End of vdbe.c ************************************************/
71105 /************** Begin file vdbeblob.c ****************************************/
71106 /*
71107 ** 2007 May 1
71108 **
71109 ** The author disclaims copyright to this source code.  In place of
71110 ** a legal notice, here is a blessing:
71111 **
71112 **    May you do good and not evil.
71113 **    May you find forgiveness for yourself and forgive others.
71114 **    May you share freely, never taking more than you give.
71115 **
71116 *************************************************************************
71117 **
71118 ** This file contains code used to implement incremental BLOB I/O.
71119 */
71120
71121
71122 #ifndef SQLCIPHER_OMIT_INCRBLOB
71123
71124 /*
71125 ** Valid sqlcipher3_blob* handles point to Incrblob structures.
71126 */
71127 typedef struct Incrblob Incrblob;
71128 struct Incrblob {
71129   int flags;              /* Copy of "flags" passed to sqlcipher3_blob_open() */
71130   int nByte;              /* Size of open blob, in bytes */
71131   int iOffset;            /* Byte offset of blob in cursor data */
71132   int iCol;               /* Table column this handle is open on */
71133   BtCursor *pCsr;         /* Cursor pointing at blob row */
71134   sqlcipher3_stmt *pStmt;    /* Statement holding cursor open */
71135   sqlcipher3 *db;            /* The associated database */
71136 };
71137
71138
71139 /*
71140 ** This function is used by both blob_open() and blob_reopen(). It seeks
71141 ** the b-tree cursor associated with blob handle p to point to row iRow.
71142 ** If successful, SQLCIPHER_OK is returned and subsequent calls to
71143 ** sqlcipher3_blob_read() or sqlcipher3_blob_write() access the specified row.
71144 **
71145 ** If an error occurs, or if the specified row does not exist or does not
71146 ** contain a value of type TEXT or BLOB in the column nominated when the
71147 ** blob handle was opened, then an error code is returned and *pzErr may
71148 ** be set to point to a buffer containing an error message. It is the
71149 ** responsibility of the caller to free the error message buffer using
71150 ** sqlcipher3DbFree().
71151 **
71152 ** If an error does occur, then the b-tree cursor is closed. All subsequent
71153 ** calls to sqlcipher3_blob_read(), blob_write() or blob_reopen() will 
71154 ** immediately return SQLCIPHER_ABORT.
71155 */
71156 static int blobSeekToRow(Incrblob *p, sqlcipher3_int64 iRow, char **pzErr){
71157   int rc;                         /* Error code */
71158   char *zErr = 0;                 /* Error message */
71159   Vdbe *v = (Vdbe *)p->pStmt;
71160
71161   /* Set the value of the SQL statements only variable to integer iRow. 
71162   ** This is done directly instead of using sqlcipher3_bind_int64() to avoid 
71163   ** triggering asserts related to mutexes.
71164   */
71165   assert( v->aVar[0].flags&MEM_Int );
71166   v->aVar[0].u.i = iRow;
71167
71168   rc = sqlcipher3_step(p->pStmt);
71169   if( rc==SQLCIPHER_ROW ){
71170     u32 type = v->apCsr[0]->aType[p->iCol];
71171     if( type<12 ){
71172       zErr = sqlcipher3MPrintf(p->db, "cannot open value of type %s",
71173           type==0?"null": type==7?"real": "integer"
71174       );
71175       rc = SQLCIPHER_ERROR;
71176       sqlcipher3_finalize(p->pStmt);
71177       p->pStmt = 0;
71178     }else{
71179       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
71180       p->nByte = sqlcipher3VdbeSerialTypeLen(type);
71181       p->pCsr =  v->apCsr[0]->pCursor;
71182       sqlcipher3BtreeEnterCursor(p->pCsr);
71183       sqlcipher3BtreeCacheOverflow(p->pCsr);
71184       sqlcipher3BtreeLeaveCursor(p->pCsr);
71185     }
71186   }
71187
71188   if( rc==SQLCIPHER_ROW ){
71189     rc = SQLCIPHER_OK;
71190   }else if( p->pStmt ){
71191     rc = sqlcipher3_finalize(p->pStmt);
71192     p->pStmt = 0;
71193     if( rc==SQLCIPHER_OK ){
71194       zErr = sqlcipher3MPrintf(p->db, "no such rowid: %lld", iRow);
71195       rc = SQLCIPHER_ERROR;
71196     }else{
71197       zErr = sqlcipher3MPrintf(p->db, "%s", sqlcipher3_errmsg(p->db));
71198     }
71199   }
71200
71201   assert( rc!=SQLCIPHER_OK || zErr==0 );
71202   assert( rc!=SQLCIPHER_ROW && rc!=SQLCIPHER_DONE );
71203
71204   *pzErr = zErr;
71205   return rc;
71206 }
71207
71208 /*
71209 ** Open a blob handle.
71210 */
71211 SQLCIPHER_API int sqlcipher3_blob_open(
71212   sqlcipher3* db,            /* The database connection */
71213   const char *zDb,        /* The attached database containing the blob */
71214   const char *zTable,     /* The table containing the blob */
71215   const char *zColumn,    /* The column containing the blob */
71216   sqlcipher_int64 iRow,      /* The row containing the glob */
71217   int flags,              /* True -> read/write access, false -> read-only */
71218   sqlcipher3_blob **ppBlob   /* Handle for accessing the blob returned here */
71219 ){
71220   int nAttempt = 0;
71221   int iCol;               /* Index of zColumn in row-record */
71222
71223   /* This VDBE program seeks a btree cursor to the identified 
71224   ** db/table/row entry. The reason for using a vdbe program instead
71225   ** of writing code to use the b-tree layer directly is that the
71226   ** vdbe program will take advantage of the various transaction,
71227   ** locking and error handling infrastructure built into the vdbe.
71228   **
71229   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
71230   ** Code external to the Vdbe then "borrows" the b-tree cursor and
71231   ** uses it to implement the blob_read(), blob_write() and 
71232   ** blob_bytes() functions.
71233   **
71234   ** The sqlcipher3_blob_close() function finalizes the vdbe program,
71235   ** which closes the b-tree cursor and (possibly) commits the 
71236   ** transaction.
71237   */
71238   static const VdbeOpList openBlob[] = {
71239     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
71240     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
71241     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
71242
71243     /* One of the following two instructions is replaced by an OP_Noop. */
71244     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
71245     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
71246
71247     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
71248     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
71249     {OP_Column, 0, 0, 1},          /* 7  */
71250     {OP_ResultRow, 1, 0, 0},       /* 8  */
71251     {OP_Goto, 0, 5, 0},            /* 9  */
71252     {OP_Close, 0, 0, 0},           /* 10 */
71253     {OP_Halt, 0, 0, 0},            /* 11 */
71254   };
71255
71256   int rc = SQLCIPHER_OK;
71257   char *zErr = 0;
71258   Table *pTab;
71259   Parse *pParse = 0;
71260   Incrblob *pBlob = 0;
71261
71262   flags = !!flags;                /* flags = (flags ? 1 : 0); */
71263   *ppBlob = 0;
71264
71265   sqlcipher3_mutex_enter(db->mutex);
71266
71267   pBlob = (Incrblob *)sqlcipher3DbMallocZero(db, sizeof(Incrblob));
71268   if( !pBlob ) goto blob_open_out;
71269   pParse = sqlcipher3StackAllocRaw(db, sizeof(*pParse));
71270   if( !pParse ) goto blob_open_out;
71271
71272   do {
71273     memset(pParse, 0, sizeof(Parse));
71274     pParse->db = db;
71275     sqlcipher3DbFree(db, zErr);
71276     zErr = 0;
71277
71278     sqlcipher3BtreeEnterAll(db);
71279     pTab = sqlcipher3LocateTable(pParse, 0, zTable, zDb);
71280     if( pTab && IsVirtual(pTab) ){
71281       pTab = 0;
71282       sqlcipher3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
71283     }
71284 #ifndef SQLCIPHER_OMIT_VIEW
71285     if( pTab && pTab->pSelect ){
71286       pTab = 0;
71287       sqlcipher3ErrorMsg(pParse, "cannot open view: %s", zTable);
71288     }
71289 #endif
71290     if( !pTab ){
71291       if( pParse->zErrMsg ){
71292         sqlcipher3DbFree(db, zErr);
71293         zErr = pParse->zErrMsg;
71294         pParse->zErrMsg = 0;
71295       }
71296       rc = SQLCIPHER_ERROR;
71297       sqlcipher3BtreeLeaveAll(db);
71298       goto blob_open_out;
71299     }
71300
71301     /* Now search pTab for the exact column. */
71302     for(iCol=0; iCol<pTab->nCol; iCol++) {
71303       if( sqlcipher3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
71304         break;
71305       }
71306     }
71307     if( iCol==pTab->nCol ){
71308       sqlcipher3DbFree(db, zErr);
71309       zErr = sqlcipher3MPrintf(db, "no such column: \"%s\"", zColumn);
71310       rc = SQLCIPHER_ERROR;
71311       sqlcipher3BtreeLeaveAll(db);
71312       goto blob_open_out;
71313     }
71314
71315     /* If the value is being opened for writing, check that the
71316     ** column is not indexed, and that it is not part of a foreign key. 
71317     ** It is against the rules to open a column to which either of these
71318     ** descriptions applies for writing.  */
71319     if( flags ){
71320       const char *zFault = 0;
71321       Index *pIdx;
71322 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
71323       if( db->flags&SQLCIPHER_ForeignKeys ){
71324         /* Check that the column is not part of an FK child key definition. It
71325         ** is not necessary to check if it is part of a parent key, as parent
71326         ** key columns must be indexed. The check below will pick up this 
71327         ** case.  */
71328         FKey *pFKey;
71329         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
71330           int j;
71331           for(j=0; j<pFKey->nCol; j++){
71332             if( pFKey->aCol[j].iFrom==iCol ){
71333               zFault = "foreign key";
71334             }
71335           }
71336         }
71337       }
71338 #endif
71339       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
71340         int j;
71341         for(j=0; j<pIdx->nColumn; j++){
71342           if( pIdx->aiColumn[j]==iCol ){
71343             zFault = "indexed";
71344           }
71345         }
71346       }
71347       if( zFault ){
71348         sqlcipher3DbFree(db, zErr);
71349         zErr = sqlcipher3MPrintf(db, "cannot open %s column for writing", zFault);
71350         rc = SQLCIPHER_ERROR;
71351         sqlcipher3BtreeLeaveAll(db);
71352         goto blob_open_out;
71353       }
71354     }
71355
71356     pBlob->pStmt = (sqlcipher3_stmt *)sqlcipher3VdbeCreate(db);
71357     assert( pBlob->pStmt || db->mallocFailed );
71358     if( pBlob->pStmt ){
71359       Vdbe *v = (Vdbe *)pBlob->pStmt;
71360       int iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
71361
71362       sqlcipher3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
71363
71364
71365       /* Configure the OP_Transaction */
71366       sqlcipher3VdbeChangeP1(v, 0, iDb);
71367       sqlcipher3VdbeChangeP2(v, 0, flags);
71368
71369       /* Configure the OP_VerifyCookie */
71370       sqlcipher3VdbeChangeP1(v, 1, iDb);
71371       sqlcipher3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
71372       sqlcipher3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
71373
71374       /* Make sure a mutex is held on the table to be accessed */
71375       sqlcipher3VdbeUsesBtree(v, iDb); 
71376
71377       /* Configure the OP_TableLock instruction */
71378 #ifdef SQLCIPHER_OMIT_SHARED_CACHE
71379       sqlcipher3VdbeChangeToNoop(v, 2);
71380 #else
71381       sqlcipher3VdbeChangeP1(v, 2, iDb);
71382       sqlcipher3VdbeChangeP2(v, 2, pTab->tnum);
71383       sqlcipher3VdbeChangeP3(v, 2, flags);
71384       sqlcipher3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
71385 #endif
71386
71387       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
71388       ** parameter of the other to pTab->tnum.  */
71389       sqlcipher3VdbeChangeToNoop(v, 4 - flags);
71390       sqlcipher3VdbeChangeP2(v, 3 + flags, pTab->tnum);
71391       sqlcipher3VdbeChangeP3(v, 3 + flags, iDb);
71392
71393       /* Configure the number of columns. Configure the cursor to
71394       ** think that the table has one more column than it really
71395       ** does. An OP_Column to retrieve this imaginary column will
71396       ** always return an SQL NULL. This is useful because it means
71397       ** we can invoke OP_Column to fill in the vdbe cursors type 
71398       ** and offset cache without causing any IO.
71399       */
71400       sqlcipher3VdbeChangeP4(v, 3+flags, SQLCIPHER_INT_TO_PTR(pTab->nCol+1),P4_INT32);
71401       sqlcipher3VdbeChangeP2(v, 7, pTab->nCol);
71402       if( !db->mallocFailed ){
71403         pParse->nVar = 1;
71404         pParse->nMem = 1;
71405         pParse->nTab = 1;
71406         sqlcipher3VdbeMakeReady(v, pParse);
71407       }
71408     }
71409    
71410     pBlob->flags = flags;
71411     pBlob->iCol = iCol;
71412     pBlob->db = db;
71413     sqlcipher3BtreeLeaveAll(db);
71414     if( db->mallocFailed ){
71415       goto blob_open_out;
71416     }
71417     sqlcipher3_bind_int64(pBlob->pStmt, 1, iRow);
71418     rc = blobSeekToRow(pBlob, iRow, &zErr);
71419   } while( (++nAttempt)<5 && rc==SQLCIPHER_SCHEMA );
71420
71421 blob_open_out:
71422   if( rc==SQLCIPHER_OK && db->mallocFailed==0 ){
71423     *ppBlob = (sqlcipher3_blob *)pBlob;
71424   }else{
71425     if( pBlob && pBlob->pStmt ) sqlcipher3VdbeFinalize((Vdbe *)pBlob->pStmt);
71426     sqlcipher3DbFree(db, pBlob);
71427   }
71428   sqlcipher3Error(db, rc, (zErr ? "%s" : 0), zErr);
71429   sqlcipher3DbFree(db, zErr);
71430   sqlcipher3StackFree(db, pParse);
71431   rc = sqlcipher3ApiExit(db, rc);
71432   sqlcipher3_mutex_leave(db->mutex);
71433   return rc;
71434 }
71435
71436 /*
71437 ** Close a blob handle that was previously created using
71438 ** sqlcipher3_blob_open().
71439 */
71440 SQLCIPHER_API int sqlcipher3_blob_close(sqlcipher3_blob *pBlob){
71441   Incrblob *p = (Incrblob *)pBlob;
71442   int rc;
71443   sqlcipher3 *db;
71444
71445   if( p ){
71446     db = p->db;
71447     sqlcipher3_mutex_enter(db->mutex);
71448     rc = sqlcipher3_finalize(p->pStmt);
71449     sqlcipher3DbFree(db, p);
71450     sqlcipher3_mutex_leave(db->mutex);
71451   }else{
71452     rc = SQLCIPHER_OK;
71453   }
71454   return rc;
71455 }
71456
71457 /*
71458 ** Perform a read or write operation on a blob
71459 */
71460 static int blobReadWrite(
71461   sqlcipher3_blob *pBlob, 
71462   void *z, 
71463   int n, 
71464   int iOffset, 
71465   int (*xCall)(BtCursor*, u32, u32, void*)
71466 ){
71467   int rc;
71468   Incrblob *p = (Incrblob *)pBlob;
71469   Vdbe *v;
71470   sqlcipher3 *db;
71471
71472   if( p==0 ) return SQLCIPHER_MISUSE_BKPT;
71473   db = p->db;
71474   sqlcipher3_mutex_enter(db->mutex);
71475   v = (Vdbe*)p->pStmt;
71476
71477   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
71478     /* Request is out of range. Return a transient error. */
71479     rc = SQLCIPHER_ERROR;
71480     sqlcipher3Error(db, SQLCIPHER_ERROR, 0);
71481   }else if( v==0 ){
71482     /* If there is no statement handle, then the blob-handle has
71483     ** already been invalidated. Return SQLCIPHER_ABORT in this case.
71484     */
71485     rc = SQLCIPHER_ABORT;
71486   }else{
71487     /* Call either BtreeData() or BtreePutData(). If SQLCIPHER_ABORT is
71488     ** returned, clean-up the statement handle.
71489     */
71490     assert( db == v->db );
71491     sqlcipher3BtreeEnterCursor(p->pCsr);
71492     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
71493     sqlcipher3BtreeLeaveCursor(p->pCsr);
71494     if( rc==SQLCIPHER_ABORT ){
71495       sqlcipher3VdbeFinalize(v);
71496       p->pStmt = 0;
71497     }else{
71498       db->errCode = rc;
71499       v->rc = rc;
71500     }
71501   }
71502   rc = sqlcipher3ApiExit(db, rc);
71503   sqlcipher3_mutex_leave(db->mutex);
71504   return rc;
71505 }
71506
71507 /*
71508 ** Read data from a blob handle.
71509 */
71510 SQLCIPHER_API int sqlcipher3_blob_read(sqlcipher3_blob *pBlob, void *z, int n, int iOffset){
71511   return blobReadWrite(pBlob, z, n, iOffset, sqlcipher3BtreeData);
71512 }
71513
71514 /*
71515 ** Write data to a blob handle.
71516 */
71517 SQLCIPHER_API int sqlcipher3_blob_write(sqlcipher3_blob *pBlob, const void *z, int n, int iOffset){
71518   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlcipher3BtreePutData);
71519 }
71520
71521 /*
71522 ** Query a blob handle for the size of the data.
71523 **
71524 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
71525 ** so no mutex is required for access.
71526 */
71527 SQLCIPHER_API int sqlcipher3_blob_bytes(sqlcipher3_blob *pBlob){
71528   Incrblob *p = (Incrblob *)pBlob;
71529   return (p && p->pStmt) ? p->nByte : 0;
71530 }
71531
71532 /*
71533 ** Move an existing blob handle to point to a different row of the same
71534 ** database table.
71535 **
71536 ** If an error occurs, or if the specified row does not exist or does not
71537 ** contain a blob or text value, then an error code is returned and the
71538 ** database handle error code and message set. If this happens, then all 
71539 ** subsequent calls to sqlcipher3_blob_xxx() functions (except blob_close()) 
71540 ** immediately return SQLCIPHER_ABORT.
71541 */
71542 SQLCIPHER_API int sqlcipher3_blob_reopen(sqlcipher3_blob *pBlob, sqlcipher3_int64 iRow){
71543   int rc;
71544   Incrblob *p = (Incrblob *)pBlob;
71545   sqlcipher3 *db;
71546
71547   if( p==0 ) return SQLCIPHER_MISUSE_BKPT;
71548   db = p->db;
71549   sqlcipher3_mutex_enter(db->mutex);
71550
71551   if( p->pStmt==0 ){
71552     /* If there is no statement handle, then the blob-handle has
71553     ** already been invalidated. Return SQLCIPHER_ABORT in this case.
71554     */
71555     rc = SQLCIPHER_ABORT;
71556   }else{
71557     char *zErr;
71558     rc = blobSeekToRow(p, iRow, &zErr);
71559     if( rc!=SQLCIPHER_OK ){
71560       sqlcipher3Error(db, rc, (zErr ? "%s" : 0), zErr);
71561       sqlcipher3DbFree(db, zErr);
71562     }
71563     assert( rc!=SQLCIPHER_SCHEMA );
71564   }
71565
71566   rc = sqlcipher3ApiExit(db, rc);
71567   assert( rc==SQLCIPHER_OK || p->pStmt==0 );
71568   sqlcipher3_mutex_leave(db->mutex);
71569   return rc;
71570 }
71571
71572 #endif /* #ifndef SQLCIPHER_OMIT_INCRBLOB */
71573
71574 /************** End of vdbeblob.c ********************************************/
71575 /************** Begin file vdbesort.c ****************************************/
71576 /*
71577 ** 2011 July 9
71578 **
71579 ** The author disclaims copyright to this source code.  In place of
71580 ** a legal notice, here is a blessing:
71581 **
71582 **    May you do good and not evil.
71583 **    May you find forgiveness for yourself and forgive others.
71584 **    May you share freely, never taking more than you give.
71585 **
71586 *************************************************************************
71587 ** This file contains code for the VdbeSorter object, used in concert with
71588 ** a VdbeCursor to sort large numbers of keys (as may be required, for
71589 ** example, by CREATE INDEX statements on tables too large to fit in main
71590 ** memory).
71591 */
71592
71593
71594 #ifndef SQLCIPHER_OMIT_MERGE_SORT
71595
71596 typedef struct VdbeSorterIter VdbeSorterIter;
71597 typedef struct SorterRecord SorterRecord;
71598
71599 /*
71600 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
71601 **
71602 ** As keys are added to the sorter, they are written to disk in a series
71603 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
71604 ** the same as the cache-size allowed for temporary databases. In order
71605 ** to allow the caller to extract keys from the sorter in sorted order,
71606 ** all PMAs currently stored on disk must be merged together. This comment
71607 ** describes the data structure used to do so. The structure supports 
71608 ** merging any number of arrays in a single pass with no redundant comparison 
71609 ** operations.
71610 **
71611 ** The aIter[] array contains an iterator for each of the PMAs being merged.
71612 ** An aIter[] iterator either points to a valid key or else is at EOF. For 
71613 ** the purposes of the paragraphs below, we assume that the array is actually 
71614 ** N elements in size, where N is the smallest power of 2 greater to or equal 
71615 ** to the number of iterators being merged. The extra aIter[] elements are 
71616 ** treated as if they are empty (always at EOF).
71617 **
71618 ** The aTree[] array is also N elements in size. The value of N is stored in
71619 ** the VdbeSorter.nTree variable.
71620 **
71621 ** The final (N/2) elements of aTree[] contain the results of comparing
71622 ** pairs of iterator keys together. Element i contains the result of 
71623 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
71624 ** aTree element is set to the index of it. 
71625 **
71626 ** For the purposes of this comparison, EOF is considered greater than any
71627 ** other key value. If the keys are equal (only possible with two EOF
71628 ** values), it doesn't matter which index is stored.
71629 **
71630 ** The (N/4) elements of aTree[] that preceed the final (N/2) described 
71631 ** above contains the index of the smallest of each block of 4 iterators.
71632 ** And so on. So that aTree[1] contains the index of the iterator that 
71633 ** currently points to the smallest key value. aTree[0] is unused.
71634 **
71635 ** Example:
71636 **
71637 **     aIter[0] -> Banana
71638 **     aIter[1] -> Feijoa
71639 **     aIter[2] -> Elderberry
71640 **     aIter[3] -> Currant
71641 **     aIter[4] -> Grapefruit
71642 **     aIter[5] -> Apple
71643 **     aIter[6] -> Durian
71644 **     aIter[7] -> EOF
71645 **
71646 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
71647 **
71648 ** The current element is "Apple" (the value of the key indicated by 
71649 ** iterator 5). When the Next() operation is invoked, iterator 5 will
71650 ** be advanced to the next key in its segment. Say the next key is
71651 ** "Eggplant":
71652 **
71653 **     aIter[5] -> Eggplant
71654 **
71655 ** The contents of aTree[] are updated first by comparing the new iterator
71656 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
71657 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
71658 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
71659 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
71660 ** so the value written into element 1 of the array is 0. As follows:
71661 **
71662 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
71663 **
71664 ** In other words, each time we advance to the next sorter element, log2(N)
71665 ** key comparison operations are required, where N is the number of segments
71666 ** being merged (rounded up to the next power of 2).
71667 */
71668 struct VdbeSorter {
71669   int nInMemory;                  /* Current size of pRecord list as PMA */
71670   int nTree;                      /* Used size of aTree/aIter (power of 2) */
71671   VdbeSorterIter *aIter;          /* Array of iterators to merge */
71672   int *aTree;                     /* Current state of incremental merge */
71673   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
71674   i64 iReadOff;                   /* Current read offset within file pTemp1 */
71675   sqlcipher3_file *pTemp1;           /* PMA file 1 */
71676   int nPMA;                       /* Number of PMAs stored in pTemp1 */
71677   SorterRecord *pRecord;          /* Head of in-memory record list */
71678   int mnPmaSize;                  /* Minimum PMA size, in bytes */
71679   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
71680   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
71681 };
71682
71683 /*
71684 ** The following type is an iterator for a PMA. It caches the current key in 
71685 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
71686 */
71687 struct VdbeSorterIter {
71688   i64 iReadOff;                   /* Current read offset */
71689   i64 iEof;                       /* 1 byte past EOF for this iterator */
71690   sqlcipher3_file *pFile;            /* File iterator is reading from */
71691   int nAlloc;                     /* Bytes of space at aAlloc */
71692   u8 *aAlloc;                     /* Allocated space */
71693   int nKey;                       /* Number of bytes in key */
71694   u8 *aKey;                       /* Pointer to current key */
71695 };
71696
71697 /*
71698 ** A structure to store a single record. All in-memory records are connected
71699 ** together into a linked list headed at VdbeSorter.pRecord using the 
71700 ** SorterRecord.pNext pointer.
71701 */
71702 struct SorterRecord {
71703   void *pVal;
71704   int nVal;
71705   SorterRecord *pNext;
71706 };
71707
71708 /* Minimum allowable value for the VdbeSorter.nWorking variable */
71709 #define SORTER_MIN_WORKING 10
71710
71711 /* Maximum number of segments to merge in a single pass. */
71712 #define SORTER_MAX_MERGE_COUNT 16
71713
71714 /*
71715 ** Free all memory belonging to the VdbeSorterIter object passed as the second
71716 ** argument. All structure fields are set to zero before returning.
71717 */
71718 static void vdbeSorterIterZero(sqlcipher3 *db, VdbeSorterIter *pIter){
71719   sqlcipher3DbFree(db, pIter->aAlloc);
71720   memset(pIter, 0, sizeof(VdbeSorterIter));
71721 }
71722
71723 /*
71724 ** Advance iterator pIter to the next key in its PMA. Return SQLCIPHER_OK if
71725 ** no error occurs, or an SQLite error code if one does.
71726 */
71727 static int vdbeSorterIterNext(
71728   sqlcipher3 *db,                    /* Database handle (for sqlcipher3DbMalloc() ) */
71729   VdbeSorterIter *pIter           /* Iterator to advance */
71730 ){
71731   int rc;                         /* Return Code */
71732   int nRead;                      /* Number of bytes read */
71733   int nRec = 0;                   /* Size of record in bytes */
71734   int iOff = 0;                   /* Size of serialized size varint in bytes */
71735
71736   assert( pIter->iEof>=pIter->iReadOff );
71737   if( pIter->iEof-pIter->iReadOff>5 ){
71738     nRead = 5;
71739   }else{
71740     nRead = (int)(pIter->iEof - pIter->iReadOff);
71741   }
71742   if( nRead<=0 ){
71743     /* This is an EOF condition */
71744     vdbeSorterIterZero(db, pIter);
71745     return SQLCIPHER_OK;
71746   }
71747
71748   rc = sqlcipher3OsRead(pIter->pFile, pIter->aAlloc, nRead, pIter->iReadOff);
71749   if( rc==SQLCIPHER_OK ){
71750     iOff = getVarint32(pIter->aAlloc, nRec);
71751     if( (iOff+nRec)>nRead ){
71752       int nRead2;                   /* Number of extra bytes to read */
71753       if( (iOff+nRec)>pIter->nAlloc ){
71754         int nNew = pIter->nAlloc*2;
71755         while( (iOff+nRec)>nNew ) nNew = nNew*2;
71756         pIter->aAlloc = sqlcipher3DbReallocOrFree(db, pIter->aAlloc, nNew);
71757         if( !pIter->aAlloc ) return SQLCIPHER_NOMEM;
71758         pIter->nAlloc = nNew;
71759       }
71760   
71761       nRead2 = iOff + nRec - nRead;
71762       rc = sqlcipher3OsRead(
71763           pIter->pFile, &pIter->aAlloc[nRead], nRead2, pIter->iReadOff+nRead
71764       );
71765     }
71766   }
71767
71768   assert( rc!=SQLCIPHER_OK || nRec>0 );
71769   pIter->iReadOff += iOff+nRec;
71770   pIter->nKey = nRec;
71771   pIter->aKey = &pIter->aAlloc[iOff];
71772   return rc;
71773 }
71774
71775 /*
71776 ** Write a single varint, value iVal, to file-descriptor pFile. Return
71777 ** SQLCIPHER_OK if successful, or an SQLite error code if some error occurs.
71778 **
71779 ** The value of *piOffset when this function is called is used as the byte
71780 ** offset in file pFile to write to. Before returning, *piOffset is 
71781 ** incremented by the number of bytes written.
71782 */
71783 static int vdbeSorterWriteVarint(
71784   sqlcipher3_file *pFile,            /* File to write to */
71785   i64 iVal,                       /* Value to write as a varint */
71786   i64 *piOffset                   /* IN/OUT: Write offset in file pFile */
71787 ){
71788   u8 aVarint[9];                  /* Buffer large enough for a varint */
71789   int nVarint;                    /* Number of used bytes in varint */
71790   int rc;                         /* Result of write() call */
71791
71792   nVarint = sqlcipher3PutVarint(aVarint, iVal);
71793   rc = sqlcipher3OsWrite(pFile, aVarint, nVarint, *piOffset);
71794   *piOffset += nVarint;
71795
71796   return rc;
71797 }
71798
71799 /*
71800 ** Read a single varint from file-descriptor pFile. Return SQLCIPHER_OK if
71801 ** successful, or an SQLite error code if some error occurs.
71802 **
71803 ** The value of *piOffset when this function is called is used as the
71804 ** byte offset in file pFile from whence to read the varint. If successful
71805 ** (i.e. if no IO error occurs), then *piOffset is set to the offset of
71806 ** the first byte past the end of the varint before returning. *piVal is
71807 ** set to the integer value read. If an error occurs, the final values of
71808 ** both *piOffset and *piVal are undefined.
71809 */
71810 static int vdbeSorterReadVarint(
71811   sqlcipher3_file *pFile,            /* File to read from */
71812   i64 *piOffset,                  /* IN/OUT: Read offset in pFile */
71813   i64 *piVal                      /* OUT: Value read from file */
71814 ){
71815   u8 aVarint[9];                  /* Buffer large enough for a varint */
71816   i64 iOff = *piOffset;           /* Offset in file to read from */
71817   int rc;                         /* Return code */
71818
71819   rc = sqlcipher3OsRead(pFile, aVarint, 9, iOff);
71820   if( rc==SQLCIPHER_OK ){
71821     *piOffset += getVarint(aVarint, (u64 *)piVal);
71822   }
71823
71824   return rc;
71825 }
71826
71827 /*
71828 ** Initialize iterator pIter to scan through the PMA stored in file pFile
71829 ** starting at offset iStart and ending at offset iEof-1. This function 
71830 ** leaves the iterator pointing to the first key in the PMA (or EOF if the 
71831 ** PMA is empty).
71832 */
71833 static int vdbeSorterIterInit(
71834   sqlcipher3 *db,                    /* Database handle */
71835   VdbeSorter *pSorter,            /* Sorter object */
71836   i64 iStart,                     /* Start offset in pFile */
71837   VdbeSorterIter *pIter,          /* Iterator to populate */
71838   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
71839 ){
71840   int rc;
71841
71842   assert( pSorter->iWriteOff>iStart );
71843   assert( pIter->aAlloc==0 );
71844   pIter->pFile = pSorter->pTemp1;
71845   pIter->iReadOff = iStart;
71846   pIter->nAlloc = 128;
71847   pIter->aAlloc = (u8 *)sqlcipher3DbMallocRaw(db, pIter->nAlloc);
71848   if( !pIter->aAlloc ){
71849     rc = SQLCIPHER_NOMEM;
71850   }else{
71851     i64 nByte;                         /* Total size of PMA in bytes */
71852     rc = vdbeSorterReadVarint(pSorter->pTemp1, &pIter->iReadOff, &nByte);
71853     *pnByte += nByte;
71854     pIter->iEof = pIter->iReadOff + nByte;
71855   }
71856   if( rc==SQLCIPHER_OK ){
71857     rc = vdbeSorterIterNext(db, pIter);
71858   }
71859   return rc;
71860 }
71861
71862
71863 /*
71864 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 
71865 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
71866 ** used by the comparison. If an error occurs, return an SQLite error code.
71867 ** Otherwise, return SQLCIPHER_OK and set *pRes to a negative, zero or positive
71868 ** value, depending on whether key1 is smaller, equal to or larger than key2.
71869 **
71870 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
71871 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
71872 ** is true and key1 contains even a single NULL value, it is considered to
71873 ** be less than key2. Even if key2 also contains NULL values.
71874 **
71875 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
71876 ** has been allocated and contains an unpacked record that is used as key2.
71877 */
71878 static void vdbeSorterCompare(
71879   VdbeCursor *pCsr,               /* Cursor object (for pKeyInfo) */
71880   int bOmitRowid,                 /* Ignore rowid field at end of keys */
71881   void *pKey1, int nKey1,         /* Left side of comparison */
71882   void *pKey2, int nKey2,         /* Right side of comparison */
71883   int *pRes                       /* OUT: Result of comparison */
71884 ){
71885   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
71886   VdbeSorter *pSorter = pCsr->pSorter;
71887   UnpackedRecord *r2 = pSorter->pUnpacked;
71888   int i;
71889
71890   if( pKey2 ){
71891     sqlcipher3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
71892   }
71893
71894   if( bOmitRowid ){
71895     r2->nField = pKeyInfo->nField;
71896     assert( r2->nField>0 );
71897     for(i=0; i<r2->nField; i++){
71898       if( r2->aMem[i].flags & MEM_Null ){
71899         *pRes = -1;
71900         return;
71901       }
71902     }
71903     r2->flags |= UNPACKED_PREFIX_MATCH;
71904   }
71905
71906   *pRes = sqlcipher3VdbeRecordCompare(nKey1, pKey1, r2);
71907 }
71908
71909 /*
71910 ** This function is called to compare two iterator keys when merging 
71911 ** multiple b-tree segments. Parameter iOut is the index of the aTree[] 
71912 ** value to recalculate.
71913 */
71914 static int vdbeSorterDoCompare(VdbeCursor *pCsr, int iOut){
71915   VdbeSorter *pSorter = pCsr->pSorter;
71916   int i1;
71917   int i2;
71918   int iRes;
71919   VdbeSorterIter *p1;
71920   VdbeSorterIter *p2;
71921
71922   assert( iOut<pSorter->nTree && iOut>0 );
71923
71924   if( iOut>=(pSorter->nTree/2) ){
71925     i1 = (iOut - pSorter->nTree/2) * 2;
71926     i2 = i1 + 1;
71927   }else{
71928     i1 = pSorter->aTree[iOut*2];
71929     i2 = pSorter->aTree[iOut*2+1];
71930   }
71931
71932   p1 = &pSorter->aIter[i1];
71933   p2 = &pSorter->aIter[i2];
71934
71935   if( p1->pFile==0 ){
71936     iRes = i2;
71937   }else if( p2->pFile==0 ){
71938     iRes = i1;
71939   }else{
71940     int res;
71941     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
71942     vdbeSorterCompare(
71943         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
71944     );
71945     if( res<=0 ){
71946       iRes = i1;
71947     }else{
71948       iRes = i2;
71949     }
71950   }
71951
71952   pSorter->aTree[iOut] = iRes;
71953   return SQLCIPHER_OK;
71954 }
71955
71956 /*
71957 ** Initialize the temporary index cursor just opened as a sorter cursor.
71958 */
71959 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterInit(sqlcipher3 *db, VdbeCursor *pCsr){
71960   int pgsz;                       /* Page size of main database */
71961   int mxCache;                    /* Cache size */
71962   VdbeSorter *pSorter;            /* The new sorter */
71963   char *d;                        /* Dummy */
71964
71965   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
71966   pCsr->pSorter = pSorter = sqlcipher3DbMallocZero(db, sizeof(VdbeSorter));
71967   if( pSorter==0 ){
71968     return SQLCIPHER_NOMEM;
71969   }
71970   
71971   pSorter->pUnpacked = sqlcipher3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
71972   if( pSorter->pUnpacked==0 ) return SQLCIPHER_NOMEM;
71973   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
71974
71975   if( !sqlcipher3TempInMemory(db) ){
71976     pgsz = sqlcipher3BtreeGetPageSize(db->aDb[0].pBt);
71977     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
71978     mxCache = db->aDb[0].pSchema->cache_size;
71979     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
71980     pSorter->mxPmaSize = mxCache * pgsz;
71981   }
71982
71983   return SQLCIPHER_OK;
71984 }
71985
71986 /*
71987 ** Free the list of sorted records starting at pRecord.
71988 */
71989 static void vdbeSorterRecordFree(sqlcipher3 *db, SorterRecord *pRecord){
71990   SorterRecord *p;
71991   SorterRecord *pNext;
71992   for(p=pRecord; p; p=pNext){
71993     pNext = p->pNext;
71994     sqlcipher3DbFree(db, p);
71995   }
71996 }
71997
71998 /*
71999 ** Free any cursor components allocated by sqlcipher3VdbeSorterXXX routines.
72000 */
72001 SQLCIPHER_PRIVATE void sqlcipher3VdbeSorterClose(sqlcipher3 *db, VdbeCursor *pCsr){
72002   VdbeSorter *pSorter = pCsr->pSorter;
72003   if( pSorter ){
72004     if( pSorter->aIter ){
72005       int i;
72006       for(i=0; i<pSorter->nTree; i++){
72007         vdbeSorterIterZero(db, &pSorter->aIter[i]);
72008       }
72009       sqlcipher3DbFree(db, pSorter->aIter);
72010     }
72011     if( pSorter->pTemp1 ){
72012       sqlcipher3OsCloseFree(pSorter->pTemp1);
72013     }
72014     vdbeSorterRecordFree(db, pSorter->pRecord);
72015     sqlcipher3DbFree(db, pSorter->pUnpacked);
72016     sqlcipher3DbFree(db, pSorter);
72017     pCsr->pSorter = 0;
72018   }
72019 }
72020
72021 /*
72022 ** Allocate space for a file-handle and open a temporary file. If successful,
72023 ** set *ppFile to point to the malloc'd file-handle and return SQLCIPHER_OK.
72024 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
72025 */
72026 static int vdbeSorterOpenTempFile(sqlcipher3 *db, sqlcipher3_file **ppFile){
72027   int dummy;
72028   return sqlcipher3OsOpenMalloc(db->pVfs, 0, ppFile,
72029       SQLCIPHER_OPEN_TEMP_JOURNAL |
72030       SQLCIPHER_OPEN_READWRITE    | SQLCIPHER_OPEN_CREATE |
72031       SQLCIPHER_OPEN_EXCLUSIVE    | SQLCIPHER_OPEN_DELETEONCLOSE, &dummy
72032   );
72033 }
72034
72035 /*
72036 ** Merge the two sorted lists p1 and p2 into a single list.
72037 ** Set *ppOut to the head of the new list.
72038 */
72039 static void vdbeSorterMerge(
72040   VdbeCursor *pCsr,               /* For pKeyInfo */
72041   SorterRecord *p1,               /* First list to merge */
72042   SorterRecord *p2,               /* Second list to merge */
72043   SorterRecord **ppOut            /* OUT: Head of merged list */
72044 ){
72045   SorterRecord *pFinal = 0;
72046   SorterRecord **pp = &pFinal;
72047   void *pVal2 = p2 ? p2->pVal : 0;
72048
72049   while( p1 && p2 ){
72050     int res;
72051     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
72052     if( res<=0 ){
72053       *pp = p1;
72054       pp = &p1->pNext;
72055       p1 = p1->pNext;
72056       pVal2 = 0;
72057     }else{
72058       *pp = p2;
72059        pp = &p2->pNext;
72060       p2 = p2->pNext;
72061       if( p2==0 ) break;
72062       pVal2 = p2->pVal;
72063     }
72064   }
72065   *pp = p1 ? p1 : p2;
72066   *ppOut = pFinal;
72067 }
72068
72069 /*
72070 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLCIPHER_OK
72071 ** if successful, or an SQLite error code (i.e. SQLCIPHER_NOMEM) if an error
72072 ** occurs.
72073 */
72074 static int vdbeSorterSort(VdbeCursor *pCsr){
72075   int i;
72076   SorterRecord **aSlot;
72077   SorterRecord *p;
72078   VdbeSorter *pSorter = pCsr->pSorter;
72079
72080   aSlot = (SorterRecord **)sqlcipher3MallocZero(64 * sizeof(SorterRecord *));
72081   if( !aSlot ){
72082     return SQLCIPHER_NOMEM;
72083   }
72084
72085   p = pSorter->pRecord;
72086   while( p ){
72087     SorterRecord *pNext = p->pNext;
72088     p->pNext = 0;
72089     for(i=0; aSlot[i]; i++){
72090       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72091       aSlot[i] = 0;
72092     }
72093     aSlot[i] = p;
72094     p = pNext;
72095   }
72096
72097   p = 0;
72098   for(i=0; i<64; i++){
72099     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72100   }
72101   pSorter->pRecord = p;
72102
72103   sqlcipher3_free(aSlot);
72104   return SQLCIPHER_OK;
72105 }
72106
72107
72108 /*
72109 ** Write the current contents of the in-memory linked-list to a PMA. Return
72110 ** SQLCIPHER_OK if successful, or an SQLite error code otherwise.
72111 **
72112 ** The format of a PMA is:
72113 **
72114 **     * A varint. This varint contains the total number of bytes of content
72115 **       in the PMA (not including the varint itself).
72116 **
72117 **     * One or more records packed end-to-end in order of ascending keys. 
72118 **       Each record consists of a varint followed by a blob of data (the 
72119 **       key). The varint is the number of bytes in the blob of data.
72120 */
72121 static int vdbeSorterListToPMA(sqlcipher3 *db, VdbeCursor *pCsr){
72122   int rc = SQLCIPHER_OK;             /* Return code */
72123   VdbeSorter *pSorter = pCsr->pSorter;
72124
72125   if( pSorter->nInMemory==0 ){
72126     assert( pSorter->pRecord==0 );
72127     return rc;
72128   }
72129
72130   rc = vdbeSorterSort(pCsr);
72131
72132   /* If the first temporary PMA file has not been opened, open it now. */
72133   if( rc==SQLCIPHER_OK && pSorter->pTemp1==0 ){
72134     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
72135     assert( rc!=SQLCIPHER_OK || pSorter->pTemp1 );
72136     assert( pSorter->iWriteOff==0 );
72137     assert( pSorter->nPMA==0 );
72138   }
72139
72140   if( rc==SQLCIPHER_OK ){
72141     i64 iOff = pSorter->iWriteOff;
72142     SorterRecord *p;
72143     SorterRecord *pNext = 0;
72144     static const char eightZeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
72145
72146     pSorter->nPMA++;
72147     rc = vdbeSorterWriteVarint(pSorter->pTemp1, pSorter->nInMemory, &iOff);
72148     for(p=pSorter->pRecord; rc==SQLCIPHER_OK && p; p=pNext){
72149       pNext = p->pNext;
72150       rc = vdbeSorterWriteVarint(pSorter->pTemp1, p->nVal, &iOff);
72151
72152       if( rc==SQLCIPHER_OK ){
72153         rc = sqlcipher3OsWrite(pSorter->pTemp1, p->pVal, p->nVal, iOff);
72154         iOff += p->nVal;
72155       }
72156
72157       sqlcipher3DbFree(db, p);
72158     }
72159
72160     /* This assert verifies that unless an error has occurred, the size of 
72161     ** the PMA on disk is the same as the expected size stored in
72162     ** pSorter->nInMemory. */ 
72163     assert( rc!=SQLCIPHER_OK || pSorter->nInMemory==(
72164           iOff-pSorter->iWriteOff-sqlcipher3VarintLen(pSorter->nInMemory)
72165     ));
72166
72167     pSorter->iWriteOff = iOff;
72168     if( rc==SQLCIPHER_OK ){
72169       /* Terminate each file with 8 extra bytes so that from any offset
72170       ** in the file we can always read 9 bytes without a SHORT_READ error */
72171       rc = sqlcipher3OsWrite(pSorter->pTemp1, eightZeros, 8, iOff);
72172     }
72173     pSorter->pRecord = p;
72174   }
72175
72176   return rc;
72177 }
72178
72179 /*
72180 ** Add a record to the sorter.
72181 */
72182 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterWrite(
72183   sqlcipher3 *db,                    /* Database handle */
72184   VdbeCursor *pCsr,               /* Sorter cursor */
72185   Mem *pVal                       /* Memory cell containing record */
72186 ){
72187   VdbeSorter *pSorter = pCsr->pSorter;
72188   int rc = SQLCIPHER_OK;             /* Return Code */
72189   SorterRecord *pNew;             /* New list element */
72190
72191   assert( pSorter );
72192   pSorter->nInMemory += sqlcipher3VarintLen(pVal->n) + pVal->n;
72193
72194   pNew = (SorterRecord *)sqlcipher3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
72195   if( pNew==0 ){
72196     rc = SQLCIPHER_NOMEM;
72197   }else{
72198     pNew->pVal = (void *)&pNew[1];
72199     memcpy(pNew->pVal, pVal->z, pVal->n);
72200     pNew->nVal = pVal->n;
72201     pNew->pNext = pSorter->pRecord;
72202     pSorter->pRecord = pNew;
72203   }
72204
72205   /* See if the contents of the sorter should now be written out. They
72206   ** are written out when either of the following are true:
72207   **
72208   **   * The total memory allocated for the in-memory list is greater 
72209   **     than (page-size * cache-size), or
72210   **
72211   **   * The total memory allocated for the in-memory list is greater 
72212   **     than (page-size * 10) and sqlcipher3HeapNearlyFull() returns true.
72213   */
72214   if( rc==SQLCIPHER_OK && pSorter->mxPmaSize>0 && (
72215         (pSorter->nInMemory>pSorter->mxPmaSize)
72216      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlcipher3HeapNearlyFull())
72217   )){
72218     rc = vdbeSorterListToPMA(db, pCsr);
72219     pSorter->nInMemory = 0;
72220   }
72221
72222   return rc;
72223 }
72224
72225 /*
72226 ** Helper function for sqlcipher3VdbeSorterRewind(). 
72227 */
72228 static int vdbeSorterInitMerge(
72229   sqlcipher3 *db,                    /* Database handle */
72230   VdbeCursor *pCsr,               /* Cursor handle for this sorter */
72231   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
72232 ){
72233   VdbeSorter *pSorter = pCsr->pSorter;
72234   int rc = SQLCIPHER_OK;             /* Return code */
72235   int i;                          /* Used to iterator through aIter[] */
72236   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
72237
72238   /* Initialize the iterators. */
72239   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
72240     VdbeSorterIter *pIter = &pSorter->aIter[i];
72241     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
72242     pSorter->iReadOff = pIter->iEof;
72243     assert( rc!=SQLCIPHER_OK || pSorter->iReadOff<=pSorter->iWriteOff );
72244     if( rc!=SQLCIPHER_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
72245   }
72246
72247   /* Initialize the aTree[] array. */
72248   for(i=pSorter->nTree-1; rc==SQLCIPHER_OK && i>0; i--){
72249     rc = vdbeSorterDoCompare(pCsr, i);
72250   }
72251
72252   *pnByte = nByte;
72253   return rc;
72254 }
72255
72256 /*
72257 ** Once the sorter has been populated, this function is called to prepare
72258 ** for iterating through its contents in sorted order.
72259 */
72260 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterRewind(sqlcipher3 *db, VdbeCursor *pCsr, int *pbEof){
72261   VdbeSorter *pSorter = pCsr->pSorter;
72262   int rc;                         /* Return code */
72263   sqlcipher3_file *pTemp2 = 0;       /* Second temp file to use */
72264   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
72265   int nIter;                      /* Number of iterators used */
72266   int nByte;                      /* Bytes of space required for aIter/aTree */
72267   int N = 2;                      /* Power of 2 >= nIter */
72268
72269   assert( pSorter );
72270
72271   /* If no data has been written to disk, then do not do so now. Instead,
72272   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
72273   ** from the in-memory list.  */
72274   if( pSorter->nPMA==0 ){
72275     *pbEof = !pSorter->pRecord;
72276     assert( pSorter->aTree==0 );
72277     return vdbeSorterSort(pCsr);
72278   }
72279
72280   /* Write the current b-tree to a PMA. Close the b-tree cursor. */
72281   rc = vdbeSorterListToPMA(db, pCsr);
72282   if( rc!=SQLCIPHER_OK ) return rc;
72283
72284   /* Allocate space for aIter[] and aTree[]. */
72285   nIter = pSorter->nPMA;
72286   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
72287   assert( nIter>0 );
72288   while( N<nIter ) N += N;
72289   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
72290   pSorter->aIter = (VdbeSorterIter *)sqlcipher3DbMallocZero(db, nByte);
72291   if( !pSorter->aIter ) return SQLCIPHER_NOMEM;
72292   pSorter->aTree = (int *)&pSorter->aIter[N];
72293   pSorter->nTree = N;
72294
72295   do {
72296     int iNew;                     /* Index of new, merged, PMA */
72297
72298     for(iNew=0; 
72299         rc==SQLCIPHER_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA; 
72300         iNew++
72301     ){
72302       i64 nWrite;                 /* Number of bytes in new PMA */
72303
72304       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
72305       ** initialize an iterator for each of them and break out of the loop.
72306       ** These iterators will be incrementally merged as the VDBE layer calls
72307       ** sqlcipher3VdbeSorterNext().
72308       **
72309       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
72310       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
72311       ** are merged into a single PMA that is written to file pTemp2.
72312       */
72313       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
72314       assert( rc!=SQLCIPHER_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
72315       if( rc!=SQLCIPHER_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
72316         break;
72317       }
72318
72319       /* Open the second temp file, if it is not already open. */
72320       if( pTemp2==0 ){
72321         assert( iWrite2==0 );
72322         rc = vdbeSorterOpenTempFile(db, &pTemp2);
72323       }
72324
72325       if( rc==SQLCIPHER_OK ){
72326         rc = vdbeSorterWriteVarint(pTemp2, nWrite, &iWrite2);
72327       }
72328
72329       if( rc==SQLCIPHER_OK ){
72330         int bEof = 0;
72331         while( rc==SQLCIPHER_OK && bEof==0 ){
72332           int nToWrite;
72333           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
72334           assert( pIter->pFile );
72335           nToWrite = pIter->nKey + sqlcipher3VarintLen(pIter->nKey);
72336           rc = sqlcipher3OsWrite(pTemp2, pIter->aAlloc, nToWrite, iWrite2);
72337           iWrite2 += nToWrite;
72338           if( rc==SQLCIPHER_OK ){
72339             rc = sqlcipher3VdbeSorterNext(db, pCsr, &bEof);
72340           }
72341         }
72342       }
72343     }
72344
72345     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
72346       break;
72347     }else{
72348       sqlcipher3_file *pTmp = pSorter->pTemp1;
72349       pSorter->nPMA = iNew;
72350       pSorter->pTemp1 = pTemp2;
72351       pTemp2 = pTmp;
72352       pSorter->iWriteOff = iWrite2;
72353       pSorter->iReadOff = 0;
72354       iWrite2 = 0;
72355     }
72356   }while( rc==SQLCIPHER_OK );
72357
72358   if( pTemp2 ){
72359     sqlcipher3OsCloseFree(pTemp2);
72360   }
72361   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
72362   return rc;
72363 }
72364
72365 /*
72366 ** Advance to the next element in the sorter.
72367 */
72368 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterNext(sqlcipher3 *db, VdbeCursor *pCsr, int *pbEof){
72369   VdbeSorter *pSorter = pCsr->pSorter;
72370   int rc;                         /* Return code */
72371
72372   if( pSorter->aTree ){
72373     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
72374     int i;                        /* Index of aTree[] to recalculate */
72375
72376     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
72377     for(i=(pSorter->nTree+iPrev)/2; rc==SQLCIPHER_OK && i>0; i=i/2){
72378       rc = vdbeSorterDoCompare(pCsr, i);
72379     }
72380
72381     *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
72382   }else{
72383     SorterRecord *pFree = pSorter->pRecord;
72384     pSorter->pRecord = pFree->pNext;
72385     pFree->pNext = 0;
72386     vdbeSorterRecordFree(db, pFree);
72387     *pbEof = !pSorter->pRecord;
72388     rc = SQLCIPHER_OK;
72389   }
72390   return rc;
72391 }
72392
72393 /*
72394 ** Return a pointer to a buffer owned by the sorter that contains the 
72395 ** current key.
72396 */
72397 static void *vdbeSorterRowkey(
72398   VdbeSorter *pSorter,            /* Sorter object */
72399   int *pnKey                      /* OUT: Size of current key in bytes */
72400 ){
72401   void *pKey;
72402   if( pSorter->aTree ){
72403     VdbeSorterIter *pIter;
72404     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
72405     *pnKey = pIter->nKey;
72406     pKey = pIter->aKey;
72407   }else{
72408     *pnKey = pSorter->pRecord->nVal;
72409     pKey = pSorter->pRecord->pVal;
72410   }
72411   return pKey;
72412 }
72413
72414 /*
72415 ** Copy the current sorter key into the memory cell pOut.
72416 */
72417 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterRowkey(VdbeCursor *pCsr, Mem *pOut){
72418   VdbeSorter *pSorter = pCsr->pSorter;
72419   void *pKey; int nKey;           /* Sorter key to copy into pOut */
72420
72421   pKey = vdbeSorterRowkey(pSorter, &nKey);
72422   if( sqlcipher3VdbeMemGrow(pOut, nKey, 0) ){
72423     return SQLCIPHER_NOMEM;
72424   }
72425   pOut->n = nKey;
72426   MemSetTypeFlag(pOut, MEM_Blob);
72427   memcpy(pOut->z, pKey, nKey);
72428
72429   return SQLCIPHER_OK;
72430 }
72431
72432 /*
72433 ** Compare the key in memory cell pVal with the key that the sorter cursor
72434 ** passed as the first argument currently points to. For the purposes of
72435 ** the comparison, ignore the rowid field at the end of each record.
72436 **
72437 ** If an error occurs, return an SQLite error code (i.e. SQLCIPHER_NOMEM).
72438 ** Otherwise, set *pRes to a negative, zero or positive value if the
72439 ** key in pVal is smaller than, equal to or larger than the current sorter
72440 ** key.
72441 */
72442 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterCompare(
72443   VdbeCursor *pCsr,               /* Sorter cursor */
72444   Mem *pVal,                      /* Value to compare to current sorter key */
72445   int *pRes                       /* OUT: Result of comparison */
72446 ){
72447   VdbeSorter *pSorter = pCsr->pSorter;
72448   void *pKey; int nKey;           /* Sorter key to compare pVal with */
72449
72450   pKey = vdbeSorterRowkey(pSorter, &nKey);
72451   vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
72452   return SQLCIPHER_OK;
72453 }
72454
72455 #endif /* #ifndef SQLCIPHER_OMIT_MERGE_SORT */
72456
72457 /************** End of vdbesort.c ********************************************/
72458 /************** Begin file journal.c *****************************************/
72459 /*
72460 ** 2007 August 22
72461 **
72462 ** The author disclaims copyright to this source code.  In place of
72463 ** a legal notice, here is a blessing:
72464 **
72465 **    May you do good and not evil.
72466 **    May you find forgiveness for yourself and forgive others.
72467 **    May you share freely, never taking more than you give.
72468 **
72469 *************************************************************************
72470 **
72471 ** This file implements a special kind of sqlcipher3_file object used
72472 ** by SQLite to create journal files if the atomic-write optimization
72473 ** is enabled.
72474 **
72475 ** The distinctive characteristic of this sqlcipher3_file is that the
72476 ** actual on disk file is created lazily. When the file is created,
72477 ** the caller specifies a buffer size for an in-memory buffer to
72478 ** be used to service read() and write() requests. The actual file
72479 ** on disk is not created or populated until either:
72480 **
72481 **   1) The in-memory representation grows too large for the allocated 
72482 **      buffer, or
72483 **   2) The sqlcipher3JournalCreate() function is called.
72484 */
72485 #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
72486
72487
72488 /*
72489 ** A JournalFile object is a subclass of sqlcipher3_file used by
72490 ** as an open file handle for journal files.
72491 */
72492 struct JournalFile {
72493   sqlcipher3_io_methods *pMethod;    /* I/O methods on journal files */
72494   int nBuf;                       /* Size of zBuf[] in bytes */
72495   char *zBuf;                     /* Space to buffer journal writes */
72496   int iSize;                      /* Amount of zBuf[] currently used */
72497   int flags;                      /* xOpen flags */
72498   sqlcipher3_vfs *pVfs;              /* The "real" underlying VFS */
72499   sqlcipher3_file *pReal;            /* The "real" underlying file descriptor */
72500   const char *zJournal;           /* Name of the journal file */
72501 };
72502 typedef struct JournalFile JournalFile;
72503
72504 /*
72505 ** If it does not already exists, create and populate the on-disk file 
72506 ** for JournalFile p.
72507 */
72508 static int createFile(JournalFile *p){
72509   int rc = SQLCIPHER_OK;
72510   if( !p->pReal ){
72511     sqlcipher3_file *pReal = (sqlcipher3_file *)&p[1];
72512     rc = sqlcipher3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
72513     if( rc==SQLCIPHER_OK ){
72514       p->pReal = pReal;
72515       if( p->iSize>0 ){
72516         assert(p->iSize<=p->nBuf);
72517         rc = sqlcipher3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
72518       }
72519     }
72520   }
72521   return rc;
72522 }
72523
72524 /*
72525 ** Close the file.
72526 */
72527 static int jrnlClose(sqlcipher3_file *pJfd){
72528   JournalFile *p = (JournalFile *)pJfd;
72529   if( p->pReal ){
72530     sqlcipher3OsClose(p->pReal);
72531   }
72532   sqlcipher3_free(p->zBuf);
72533   return SQLCIPHER_OK;
72534 }
72535
72536 /*
72537 ** Read data from the file.
72538 */
72539 static int jrnlRead(
72540   sqlcipher3_file *pJfd,    /* The journal file from which to read */
72541   void *zBuf,            /* Put the results here */
72542   int iAmt,              /* Number of bytes to read */
72543   sqlcipher_int64 iOfst     /* Begin reading at this offset */
72544 ){
72545   int rc = SQLCIPHER_OK;
72546   JournalFile *p = (JournalFile *)pJfd;
72547   if( p->pReal ){
72548     rc = sqlcipher3OsRead(p->pReal, zBuf, iAmt, iOfst);
72549   }else if( (iAmt+iOfst)>p->iSize ){
72550     rc = SQLCIPHER_IOERR_SHORT_READ;
72551   }else{
72552     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
72553   }
72554   return rc;
72555 }
72556
72557 /*
72558 ** Write data to the file.
72559 */
72560 static int jrnlWrite(
72561   sqlcipher3_file *pJfd,    /* The journal file into which to write */
72562   const void *zBuf,      /* Take data to be written from here */
72563   int iAmt,              /* Number of bytes to write */
72564   sqlcipher_int64 iOfst     /* Begin writing at this offset into the file */
72565 ){
72566   int rc = SQLCIPHER_OK;
72567   JournalFile *p = (JournalFile *)pJfd;
72568   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
72569     rc = createFile(p);
72570   }
72571   if( rc==SQLCIPHER_OK ){
72572     if( p->pReal ){
72573       rc = sqlcipher3OsWrite(p->pReal, zBuf, iAmt, iOfst);
72574     }else{
72575       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
72576       if( p->iSize<(iOfst+iAmt) ){
72577         p->iSize = (iOfst+iAmt);
72578       }
72579     }
72580   }
72581   return rc;
72582 }
72583
72584 /*
72585 ** Truncate the file.
72586 */
72587 static int jrnlTruncate(sqlcipher3_file *pJfd, sqlcipher_int64 size){
72588   int rc = SQLCIPHER_OK;
72589   JournalFile *p = (JournalFile *)pJfd;
72590   if( p->pReal ){
72591     rc = sqlcipher3OsTruncate(p->pReal, size);
72592   }else if( size<p->iSize ){
72593     p->iSize = size;
72594   }
72595   return rc;
72596 }
72597
72598 /*
72599 ** Sync the file.
72600 */
72601 static int jrnlSync(sqlcipher3_file *pJfd, int flags){
72602   int rc;
72603   JournalFile *p = (JournalFile *)pJfd;
72604   if( p->pReal ){
72605     rc = sqlcipher3OsSync(p->pReal, flags);
72606   }else{
72607     rc = SQLCIPHER_OK;
72608   }
72609   return rc;
72610 }
72611
72612 /*
72613 ** Query the size of the file in bytes.
72614 */
72615 static int jrnlFileSize(sqlcipher3_file *pJfd, sqlcipher_int64 *pSize){
72616   int rc = SQLCIPHER_OK;
72617   JournalFile *p = (JournalFile *)pJfd;
72618   if( p->pReal ){
72619     rc = sqlcipher3OsFileSize(p->pReal, pSize);
72620   }else{
72621     *pSize = (sqlcipher_int64) p->iSize;
72622   }
72623   return rc;
72624 }
72625
72626 /*
72627 ** Table of methods for JournalFile sqlcipher3_file object.
72628 */
72629 static struct sqlcipher3_io_methods JournalFileMethods = {
72630   1,             /* iVersion */
72631   jrnlClose,     /* xClose */
72632   jrnlRead,      /* xRead */
72633   jrnlWrite,     /* xWrite */
72634   jrnlTruncate,  /* xTruncate */
72635   jrnlSync,      /* xSync */
72636   jrnlFileSize,  /* xFileSize */
72637   0,             /* xLock */
72638   0,             /* xUnlock */
72639   0,             /* xCheckReservedLock */
72640   0,             /* xFileControl */
72641   0,             /* xSectorSize */
72642   0,             /* xDeviceCharacteristics */
72643   0,             /* xShmMap */
72644   0,             /* xShmLock */
72645   0,             /* xShmBarrier */
72646   0              /* xShmUnmap */
72647 };
72648
72649 /* 
72650 ** Open a journal file.
72651 */
72652 SQLCIPHER_PRIVATE int sqlcipher3JournalOpen(
72653   sqlcipher3_vfs *pVfs,         /* The VFS to use for actual file I/O */
72654   const char *zName,         /* Name of the journal file */
72655   sqlcipher3_file *pJfd,        /* Preallocated, blank file handle */
72656   int flags,                 /* Opening flags */
72657   int nBuf                   /* Bytes buffered before opening the file */
72658 ){
72659   JournalFile *p = (JournalFile *)pJfd;
72660   memset(p, 0, sqlcipher3JournalSize(pVfs));
72661   if( nBuf>0 ){
72662     p->zBuf = sqlcipher3MallocZero(nBuf);
72663     if( !p->zBuf ){
72664       return SQLCIPHER_NOMEM;
72665     }
72666   }else{
72667     return sqlcipher3OsOpen(pVfs, zName, pJfd, flags, 0);
72668   }
72669   p->pMethod = &JournalFileMethods;
72670   p->nBuf = nBuf;
72671   p->flags = flags;
72672   p->zJournal = zName;
72673   p->pVfs = pVfs;
72674   return SQLCIPHER_OK;
72675 }
72676
72677 /*
72678 ** If the argument p points to a JournalFile structure, and the underlying
72679 ** file has not yet been created, create it now.
72680 */
72681 SQLCIPHER_PRIVATE int sqlcipher3JournalCreate(sqlcipher3_file *p){
72682   if( p->pMethods!=&JournalFileMethods ){
72683     return SQLCIPHER_OK;
72684   }
72685   return createFile((JournalFile *)p);
72686 }
72687
72688 /* 
72689 ** Return the number of bytes required to store a JournalFile that uses vfs
72690 ** pVfs to create the underlying on-disk files.
72691 */
72692 SQLCIPHER_PRIVATE int sqlcipher3JournalSize(sqlcipher3_vfs *pVfs){
72693   return (pVfs->szOsFile+sizeof(JournalFile));
72694 }
72695 #endif
72696
72697 /************** End of journal.c *********************************************/
72698 /************** Begin file memjournal.c **************************************/
72699 /*
72700 ** 2008 October 7
72701 **
72702 ** The author disclaims copyright to this source code.  In place of
72703 ** a legal notice, here is a blessing:
72704 **
72705 **    May you do good and not evil.
72706 **    May you find forgiveness for yourself and forgive others.
72707 **    May you share freely, never taking more than you give.
72708 **
72709 *************************************************************************
72710 **
72711 ** This file contains code use to implement an in-memory rollback journal.
72712 ** The in-memory rollback journal is used to journal transactions for
72713 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
72714 */
72715
72716 /* Forward references to internal structures */
72717 typedef struct MemJournal MemJournal;
72718 typedef struct FilePoint FilePoint;
72719 typedef struct FileChunk FileChunk;
72720
72721 /* Space to hold the rollback journal is allocated in increments of
72722 ** this many bytes.
72723 **
72724 ** The size chosen is a little less than a power of two.  That way,
72725 ** the FileChunk object will have a size that almost exactly fills
72726 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
72727 ** memory allocators.
72728 */
72729 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
72730
72731 /* Macro to find the minimum of two numeric values.
72732 */
72733 #ifndef MIN
72734 # define MIN(x,y) ((x)<(y)?(x):(y))
72735 #endif
72736
72737 /*
72738 ** The rollback journal is composed of a linked list of these structures.
72739 */
72740 struct FileChunk {
72741   FileChunk *pNext;               /* Next chunk in the journal */
72742   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
72743 };
72744
72745 /*
72746 ** An instance of this object serves as a cursor into the rollback journal.
72747 ** The cursor can be either for reading or writing.
72748 */
72749 struct FilePoint {
72750   sqlcipher3_int64 iOffset;          /* Offset from the beginning of the file */
72751   FileChunk *pChunk;              /* Specific chunk into which cursor points */
72752 };
72753
72754 /*
72755 ** This subclass is a subclass of sqlcipher3_file.  Each open memory-journal
72756 ** is an instance of this class.
72757 */
72758 struct MemJournal {
72759   sqlcipher3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
72760   FileChunk *pFirst;              /* Head of in-memory chunk-list */
72761   FilePoint endpoint;             /* Pointer to the end of the file */
72762   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
72763 };
72764
72765 /*
72766 ** Read data from the in-memory journal file.  This is the implementation
72767 ** of the sqlcipher3_vfs.xRead method.
72768 */
72769 static int memjrnlRead(
72770   sqlcipher3_file *pJfd,    /* The journal file from which to read */
72771   void *zBuf,            /* Put the results here */
72772   int iAmt,              /* Number of bytes to read */
72773   sqlcipher_int64 iOfst     /* Begin reading at this offset */
72774 ){
72775   MemJournal *p = (MemJournal *)pJfd;
72776   u8 *zOut = zBuf;
72777   int nRead = iAmt;
72778   int iChunkOffset;
72779   FileChunk *pChunk;
72780
72781   /* SQLite never tries to read past the end of a rollback journal file */
72782   assert( iOfst+iAmt<=p->endpoint.iOffset );
72783
72784   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
72785     sqlcipher3_int64 iOff = 0;
72786     for(pChunk=p->pFirst; 
72787         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
72788         pChunk=pChunk->pNext
72789     ){
72790       iOff += JOURNAL_CHUNKSIZE;
72791     }
72792   }else{
72793     pChunk = p->readpoint.pChunk;
72794   }
72795
72796   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
72797   do {
72798     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
72799     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
72800     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
72801     zOut += nCopy;
72802     nRead -= iSpace;
72803     iChunkOffset = 0;
72804   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
72805   p->readpoint.iOffset = iOfst+iAmt;
72806   p->readpoint.pChunk = pChunk;
72807
72808   return SQLCIPHER_OK;
72809 }
72810
72811 /*
72812 ** Write data to the file.
72813 */
72814 static int memjrnlWrite(
72815   sqlcipher3_file *pJfd,    /* The journal file into which to write */
72816   const void *zBuf,      /* Take data to be written from here */
72817   int iAmt,              /* Number of bytes to write */
72818   sqlcipher_int64 iOfst     /* Begin writing at this offset into the file */
72819 ){
72820   MemJournal *p = (MemJournal *)pJfd;
72821   int nWrite = iAmt;
72822   u8 *zWrite = (u8 *)zBuf;
72823
72824   /* An in-memory journal file should only ever be appended to. Random
72825   ** access writes are not required by sqlcipher.
72826   */
72827   assert( iOfst==p->endpoint.iOffset );
72828   UNUSED_PARAMETER(iOfst);
72829
72830   while( nWrite>0 ){
72831     FileChunk *pChunk = p->endpoint.pChunk;
72832     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
72833     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
72834
72835     if( iChunkOffset==0 ){
72836       /* New chunk is required to extend the file. */
72837       FileChunk *pNew = sqlcipher3_malloc(sizeof(FileChunk));
72838       if( !pNew ){
72839         return SQLCIPHER_IOERR_NOMEM;
72840       }
72841       pNew->pNext = 0;
72842       if( pChunk ){
72843         assert( p->pFirst );
72844         pChunk->pNext = pNew;
72845       }else{
72846         assert( !p->pFirst );
72847         p->pFirst = pNew;
72848       }
72849       p->endpoint.pChunk = pNew;
72850     }
72851
72852     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
72853     zWrite += iSpace;
72854     nWrite -= iSpace;
72855     p->endpoint.iOffset += iSpace;
72856   }
72857
72858   return SQLCIPHER_OK;
72859 }
72860
72861 /*
72862 ** Truncate the file.
72863 */
72864 static int memjrnlTruncate(sqlcipher3_file *pJfd, sqlcipher_int64 size){
72865   MemJournal *p = (MemJournal *)pJfd;
72866   FileChunk *pChunk;
72867   assert(size==0);
72868   UNUSED_PARAMETER(size);
72869   pChunk = p->pFirst;
72870   while( pChunk ){
72871     FileChunk *pTmp = pChunk;
72872     pChunk = pChunk->pNext;
72873     sqlcipher3_free(pTmp);
72874   }
72875   sqlcipher3MemJournalOpen(pJfd);
72876   return SQLCIPHER_OK;
72877 }
72878
72879 /*
72880 ** Close the file.
72881 */
72882 static int memjrnlClose(sqlcipher3_file *pJfd){
72883   memjrnlTruncate(pJfd, 0);
72884   return SQLCIPHER_OK;
72885 }
72886
72887
72888 /*
72889 ** Sync the file.
72890 **
72891 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
72892 ** is never called in a working implementation.  This implementation
72893 ** exists purely as a contingency, in case some malfunction in some other
72894 ** part of SQLite causes Sync to be called by mistake.
72895 */
72896 static int memjrnlSync(sqlcipher3_file *NotUsed, int NotUsed2){
72897   UNUSED_PARAMETER2(NotUsed, NotUsed2);
72898   return SQLCIPHER_OK;
72899 }
72900
72901 /*
72902 ** Query the size of the file in bytes.
72903 */
72904 static int memjrnlFileSize(sqlcipher3_file *pJfd, sqlcipher_int64 *pSize){
72905   MemJournal *p = (MemJournal *)pJfd;
72906   *pSize = (sqlcipher_int64) p->endpoint.iOffset;
72907   return SQLCIPHER_OK;
72908 }
72909
72910 /*
72911 ** Table of methods for MemJournal sqlcipher3_file object.
72912 */
72913 static const struct sqlcipher3_io_methods MemJournalMethods = {
72914   1,                /* iVersion */
72915   memjrnlClose,     /* xClose */
72916   memjrnlRead,      /* xRead */
72917   memjrnlWrite,     /* xWrite */
72918   memjrnlTruncate,  /* xTruncate */
72919   memjrnlSync,      /* xSync */
72920   memjrnlFileSize,  /* xFileSize */
72921   0,                /* xLock */
72922   0,                /* xUnlock */
72923   0,                /* xCheckReservedLock */
72924   0,                /* xFileControl */
72925   0,                /* xSectorSize */
72926   0,                /* xDeviceCharacteristics */
72927   0,                /* xShmMap */
72928   0,                /* xShmLock */
72929   0,                /* xShmBarrier */
72930   0                 /* xShmUnlock */
72931 };
72932
72933 /* 
72934 ** Open a journal file.
72935 */
72936 SQLCIPHER_PRIVATE void sqlcipher3MemJournalOpen(sqlcipher3_file *pJfd){
72937   MemJournal *p = (MemJournal *)pJfd;
72938   assert( EIGHT_BYTE_ALIGNMENT(p) );
72939   memset(p, 0, sqlcipher3MemJournalSize());
72940   p->pMethod = (sqlcipher3_io_methods*)&MemJournalMethods;
72941 }
72942
72943 /*
72944 ** Return true if the file-handle passed as an argument is 
72945 ** an in-memory journal 
72946 */
72947 SQLCIPHER_PRIVATE int sqlcipher3IsMemJournal(sqlcipher3_file *pJfd){
72948   return pJfd->pMethods==&MemJournalMethods;
72949 }
72950
72951 /* 
72952 ** Return the number of bytes required to store a MemJournal file descriptor.
72953 */
72954 SQLCIPHER_PRIVATE int sqlcipher3MemJournalSize(void){
72955   return sizeof(MemJournal);
72956 }
72957
72958 /************** End of memjournal.c ******************************************/
72959 /************** Begin file walker.c ******************************************/
72960 /*
72961 ** 2008 August 16
72962 **
72963 ** The author disclaims copyright to this source code.  In place of
72964 ** a legal notice, here is a blessing:
72965 **
72966 **    May you do good and not evil.
72967 **    May you find forgiveness for yourself and forgive others.
72968 **    May you share freely, never taking more than you give.
72969 **
72970 *************************************************************************
72971 ** This file contains routines used for walking the parser tree for
72972 ** an SQL statement.
72973 */
72974 /* #include <stdlib.h> */
72975 /* #include <string.h> */
72976
72977
72978 /*
72979 ** Walk an expression tree.  Invoke the callback once for each node
72980 ** of the expression, while decending.  (In other words, the callback
72981 ** is invoked before visiting children.)
72982 **
72983 ** The return value from the callback should be one of the WRC_*
72984 ** constants to specify how to proceed with the walk.
72985 **
72986 **    WRC_Continue      Continue descending down the tree.
72987 **
72988 **    WRC_Prune         Do not descend into child nodes.  But allow
72989 **                      the walk to continue with sibling nodes.
72990 **
72991 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
72992 **                      return the top-level walk call.
72993 **
72994 ** The return value from this routine is WRC_Abort to abandon the tree walk
72995 ** and WRC_Continue to continue.
72996 */
72997 SQLCIPHER_PRIVATE int sqlcipher3WalkExpr(Walker *pWalker, Expr *pExpr){
72998   int rc;
72999   if( pExpr==0 ) return WRC_Continue;
73000   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
73001   testcase( ExprHasProperty(pExpr, EP_Reduced) );
73002   rc = pWalker->xExprCallback(pWalker, pExpr);
73003   if( rc==WRC_Continue
73004               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
73005     if( sqlcipher3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
73006     if( sqlcipher3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
73007     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73008       if( sqlcipher3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
73009     }else{
73010       if( sqlcipher3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
73011     }
73012   }
73013   return rc & WRC_Abort;
73014 }
73015
73016 /*
73017 ** Call sqlcipher3WalkExpr() for every expression in list p or until
73018 ** an abort request is seen.
73019 */
73020 SQLCIPHER_PRIVATE int sqlcipher3WalkExprList(Walker *pWalker, ExprList *p){
73021   int i;
73022   struct ExprList_item *pItem;
73023   if( p ){
73024     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
73025       if( sqlcipher3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
73026     }
73027   }
73028   return WRC_Continue;
73029 }
73030
73031 /*
73032 ** Walk all expressions associated with SELECT statement p.  Do
73033 ** not invoke the SELECT callback on p, but do (of course) invoke
73034 ** any expr callbacks and SELECT callbacks that come from subqueries.
73035 ** Return WRC_Abort or WRC_Continue.
73036 */
73037 SQLCIPHER_PRIVATE int sqlcipher3WalkSelectExpr(Walker *pWalker, Select *p){
73038   if( sqlcipher3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
73039   if( sqlcipher3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
73040   if( sqlcipher3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
73041   if( sqlcipher3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
73042   if( sqlcipher3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
73043   if( sqlcipher3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
73044   if( sqlcipher3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
73045   return WRC_Continue;
73046 }
73047
73048 /*
73049 ** Walk the parse trees associated with all subqueries in the
73050 ** FROM clause of SELECT statement p.  Do not invoke the select
73051 ** callback on p, but do invoke it on each FROM clause subquery
73052 ** and on any subqueries further down in the tree.  Return 
73053 ** WRC_Abort or WRC_Continue;
73054 */
73055 SQLCIPHER_PRIVATE int sqlcipher3WalkSelectFrom(Walker *pWalker, Select *p){
73056   SrcList *pSrc;
73057   int i;
73058   struct SrcList_item *pItem;
73059
73060   pSrc = p->pSrc;
73061   if( ALWAYS(pSrc) ){
73062     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
73063       if( sqlcipher3WalkSelect(pWalker, pItem->pSelect) ){
73064         return WRC_Abort;
73065       }
73066     }
73067   }
73068   return WRC_Continue;
73069
73070
73071 /*
73072 ** Call sqlcipher3WalkExpr() for every expression in Select statement p.
73073 ** Invoke sqlcipher3WalkSelect() for subqueries in the FROM clause and
73074 ** on the compound select chain, p->pPrior.
73075 **
73076 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
73077 ** there is an abort request.
73078 **
73079 ** If the Walker does not have an xSelectCallback() then this routine
73080 ** is a no-op returning WRC_Continue.
73081 */
73082 SQLCIPHER_PRIVATE int sqlcipher3WalkSelect(Walker *pWalker, Select *p){
73083   int rc;
73084   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
73085   rc = WRC_Continue;
73086   while( p  ){
73087     rc = pWalker->xSelectCallback(pWalker, p);
73088     if( rc ) break;
73089     if( sqlcipher3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
73090     if( sqlcipher3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
73091     p = p->pPrior;
73092   }
73093   return rc & WRC_Abort;
73094 }
73095
73096 /************** End of walker.c **********************************************/
73097 /************** Begin file resolve.c *****************************************/
73098 /*
73099 ** 2008 August 18
73100 **
73101 ** The author disclaims copyright to this source code.  In place of
73102 ** a legal notice, here is a blessing:
73103 **
73104 **    May you do good and not evil.
73105 **    May you find forgiveness for yourself and forgive others.
73106 **    May you share freely, never taking more than you give.
73107 **
73108 *************************************************************************
73109 **
73110 ** This file contains routines used for walking the parser tree and
73111 ** resolve all identifiers by associating them with a particular
73112 ** table and column.
73113 */
73114 /* #include <stdlib.h> */
73115 /* #include <string.h> */
73116
73117 /*
73118 ** Turn the pExpr expression into an alias for the iCol-th column of the
73119 ** result set in pEList.
73120 **
73121 ** If the result set column is a simple column reference, then this routine
73122 ** makes an exact copy.  But for any other kind of expression, this
73123 ** routine make a copy of the result set column as the argument to the
73124 ** TK_AS operator.  The TK_AS operator causes the expression to be
73125 ** evaluated just once and then reused for each alias.
73126 **
73127 ** The reason for suppressing the TK_AS term when the expression is a simple
73128 ** column reference is so that the column reference will be recognized as
73129 ** usable by indices within the WHERE clause processing logic. 
73130 **
73131 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
73132 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
73133 **
73134 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
73135 **
73136 ** Is equivalent to:
73137 **
73138 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
73139 **
73140 ** The result of random()%5 in the GROUP BY clause is probably different
73141 ** from the result in the result-set.  We might fix this someday.  Or
73142 ** then again, we might not...
73143 */
73144 static void resolveAlias(
73145   Parse *pParse,         /* Parsing context */
73146   ExprList *pEList,      /* A result set */
73147   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
73148   Expr *pExpr,           /* Transform this into an alias to the result set */
73149   const char *zType      /* "GROUP" or "ORDER" or "" */
73150 ){
73151   Expr *pOrig;           /* The iCol-th column of the result set */
73152   Expr *pDup;            /* Copy of pOrig */
73153   sqlcipher3 *db;           /* The database connection */
73154
73155   assert( iCol>=0 && iCol<pEList->nExpr );
73156   pOrig = pEList->a[iCol].pExpr;
73157   assert( pOrig!=0 );
73158   assert( pOrig->flags & EP_Resolved );
73159   db = pParse->db;
73160   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
73161     pDup = sqlcipher3ExprDup(db, pOrig, 0);
73162     pDup = sqlcipher3PExpr(pParse, TK_AS, pDup, 0, 0);
73163     if( pDup==0 ) return;
73164     if( pEList->a[iCol].iAlias==0 ){
73165       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
73166     }
73167     pDup->iTable = pEList->a[iCol].iAlias;
73168   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
73169     pDup = sqlcipher3ExprDup(db, pOrig, 0);
73170     if( pDup==0 ) return;
73171   }else{
73172     char *zToken = pOrig->u.zToken;
73173     assert( zToken!=0 );
73174     pOrig->u.zToken = 0;
73175     pDup = sqlcipher3ExprDup(db, pOrig, 0);
73176     pOrig->u.zToken = zToken;
73177     if( pDup==0 ) return;
73178     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
73179     pDup->flags2 |= EP2_MallocedToken;
73180     pDup->u.zToken = sqlcipher3DbStrDup(db, zToken);
73181   }
73182   if( pExpr->flags & EP_ExpCollate ){
73183     pDup->pColl = pExpr->pColl;
73184     pDup->flags |= EP_ExpCollate;
73185   }
73186
73187   /* Before calling sqlcipher3ExprDelete(), set the EP_Static flag. This 
73188   ** prevents ExprDelete() from deleting the Expr structure itself,
73189   ** allowing it to be repopulated by the memcpy() on the following line.
73190   */
73191   ExprSetProperty(pExpr, EP_Static);
73192   sqlcipher3ExprDelete(db, pExpr);
73193   memcpy(pExpr, pDup, sizeof(*pExpr));
73194   sqlcipher3DbFree(db, pDup);
73195 }
73196
73197
73198 /*
73199 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
73200 **
73201 ** Return FALSE if the USING clause is NULL or if it does not contain
73202 ** zCol.
73203 */
73204 static int nameInUsingClause(IdList *pUsing, const char *zCol){
73205   if( pUsing ){
73206     int k;
73207     for(k=0; k<pUsing->nId; k++){
73208       if( sqlcipher3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
73209     }
73210   }
73211   return 0;
73212 }
73213
73214
73215 /*
73216 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
73217 ** that name in the set of source tables in pSrcList and make the pExpr 
73218 ** expression node refer back to that source column.  The following changes
73219 ** are made to pExpr:
73220 **
73221 **    pExpr->iDb           Set the index in db->aDb[] of the database X
73222 **                         (even if X is implied).
73223 **    pExpr->iTable        Set to the cursor number for the table obtained
73224 **                         from pSrcList.
73225 **    pExpr->pTab          Points to the Table structure of X.Y (even if
73226 **                         X and/or Y are implied.)
73227 **    pExpr->iColumn       Set to the column number within the table.
73228 **    pExpr->op            Set to TK_COLUMN.
73229 **    pExpr->pLeft         Any expression this points to is deleted
73230 **    pExpr->pRight        Any expression this points to is deleted.
73231 **
73232 ** The zDb variable is the name of the database (the "X").  This value may be
73233 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
73234 ** can be used.  The zTable variable is the name of the table (the "Y").  This
73235 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
73236 ** means that the form of the name is Z and that columns from any table
73237 ** can be used.
73238 **
73239 ** If the name cannot be resolved unambiguously, leave an error message
73240 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
73241 */
73242 static int lookupName(
73243   Parse *pParse,       /* The parsing context */
73244   const char *zDb,     /* Name of the database containing table, or NULL */
73245   const char *zTab,    /* Name of table containing column, or NULL */
73246   const char *zCol,    /* Name of the column. */
73247   NameContext *pNC,    /* The name context used to resolve the name */
73248   Expr *pExpr          /* Make this EXPR node point to the selected column */
73249 ){
73250   int i, j;            /* Loop counters */
73251   int cnt = 0;                      /* Number of matching column names */
73252   int cntTab = 0;                   /* Number of matching table names */
73253   sqlcipher3 *db = pParse->db;         /* The database connection */
73254   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
73255   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
73256   NameContext *pTopNC = pNC;        /* First namecontext in the list */
73257   Schema *pSchema = 0;              /* Schema of the expression */
73258   int isTrigger = 0;
73259
73260   assert( pNC );     /* the name context cannot be NULL. */
73261   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
73262   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
73263
73264   /* Initialize the node to no-match */
73265   pExpr->iTable = -1;
73266   pExpr->pTab = 0;
73267   ExprSetIrreducible(pExpr);
73268
73269   /* Start at the inner-most context and move outward until a match is found */
73270   while( pNC && cnt==0 ){
73271     ExprList *pEList;
73272     SrcList *pSrcList = pNC->pSrcList;
73273
73274     if( pSrcList ){
73275       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
73276         Table *pTab;
73277         int iDb;
73278         Column *pCol;
73279   
73280         pTab = pItem->pTab;
73281         assert( pTab!=0 && pTab->zName!=0 );
73282         iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
73283         assert( pTab->nCol>0 );
73284         if( zTab ){
73285           if( pItem->zAlias ){
73286             char *zTabName = pItem->zAlias;
73287             if( sqlcipher3StrICmp(zTabName, zTab)!=0 ) continue;
73288           }else{
73289             char *zTabName = pTab->zName;
73290             if( NEVER(zTabName==0) || sqlcipher3StrICmp(zTabName, zTab)!=0 ){
73291               continue;
73292             }
73293             if( zDb!=0 && sqlcipher3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
73294               continue;
73295             }
73296           }
73297         }
73298         if( 0==(cntTab++) ){
73299           pExpr->iTable = pItem->iCursor;
73300           pExpr->pTab = pTab;
73301           pSchema = pTab->pSchema;
73302           pMatch = pItem;
73303         }
73304         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
73305           if( sqlcipher3StrICmp(pCol->zName, zCol)==0 ){
73306             /* If there has been exactly one prior match and this match
73307             ** is for the right-hand table of a NATURAL JOIN or is in a 
73308             ** USING clause, then skip this match.
73309             */
73310             if( cnt==1 ){
73311               if( pItem->jointype & JT_NATURAL ) continue;
73312               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
73313             }
73314             cnt++;
73315             pExpr->iTable = pItem->iCursor;
73316             pExpr->pTab = pTab;
73317             pMatch = pItem;
73318             pSchema = pTab->pSchema;
73319             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
73320             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
73321             break;
73322           }
73323         }
73324       }
73325     }
73326
73327 #ifndef SQLCIPHER_OMIT_TRIGGER
73328     /* If we have not already resolved the name, then maybe 
73329     ** it is a new.* or old.* trigger argument reference
73330     */
73331     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
73332       int op = pParse->eTriggerOp;
73333       Table *pTab = 0;
73334       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
73335       if( op!=TK_DELETE && sqlcipher3StrICmp("new",zTab) == 0 ){
73336         pExpr->iTable = 1;
73337         pTab = pParse->pTriggerTab;
73338       }else if( op!=TK_INSERT && sqlcipher3StrICmp("old",zTab)==0 ){
73339         pExpr->iTable = 0;
73340         pTab = pParse->pTriggerTab;
73341       }
73342
73343       if( pTab ){ 
73344         int iCol;
73345         pSchema = pTab->pSchema;
73346         cntTab++;
73347         for(iCol=0; iCol<pTab->nCol; iCol++){
73348           Column *pCol = &pTab->aCol[iCol];
73349           if( sqlcipher3StrICmp(pCol->zName, zCol)==0 ){
73350             if( iCol==pTab->iPKey ){
73351               iCol = -1;
73352             }
73353             break;
73354           }
73355         }
73356         if( iCol>=pTab->nCol && sqlcipher3IsRowid(zCol) ){
73357           iCol = -1;        /* IMP: R-44911-55124 */
73358         }
73359         if( iCol<pTab->nCol ){
73360           cnt++;
73361           if( iCol<0 ){
73362             pExpr->affinity = SQLCIPHER_AFF_INTEGER;
73363           }else if( pExpr->iTable==0 ){
73364             testcase( iCol==31 );
73365             testcase( iCol==32 );
73366             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
73367           }else{
73368             testcase( iCol==31 );
73369             testcase( iCol==32 );
73370             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
73371           }
73372           pExpr->iColumn = (i16)iCol;
73373           pExpr->pTab = pTab;
73374           isTrigger = 1;
73375         }
73376       }
73377     }
73378 #endif /* !defined(SQLCIPHER_OMIT_TRIGGER) */
73379
73380     /*
73381     ** Perhaps the name is a reference to the ROWID
73382     */
73383     if( cnt==0 && cntTab==1 && sqlcipher3IsRowid(zCol) ){
73384       cnt = 1;
73385       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
73386       pExpr->affinity = SQLCIPHER_AFF_INTEGER;
73387     }
73388
73389     /*
73390     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
73391     ** might refer to an result-set alias.  This happens, for example, when
73392     ** we are resolving names in the WHERE clause of the following command:
73393     **
73394     **     SELECT a+b AS x FROM table WHERE x<10;
73395     **
73396     ** In cases like this, replace pExpr with a copy of the expression that
73397     ** forms the result set entry ("a+b" in the example) and return immediately.
73398     ** Note that the expression in the result set should have already been
73399     ** resolved by the time the WHERE clause is resolved.
73400     */
73401     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
73402       for(j=0; j<pEList->nExpr; j++){
73403         char *zAs = pEList->a[j].zName;
73404         if( zAs!=0 && sqlcipher3StrICmp(zAs, zCol)==0 ){
73405           Expr *pOrig;
73406           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
73407           assert( pExpr->x.pList==0 );
73408           assert( pExpr->x.pSelect==0 );
73409           pOrig = pEList->a[j].pExpr;
73410           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
73411             sqlcipher3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
73412             return WRC_Abort;
73413           }
73414           resolveAlias(pParse, pEList, j, pExpr, "");
73415           cnt = 1;
73416           pMatch = 0;
73417           assert( zTab==0 && zDb==0 );
73418           goto lookupname_end;
73419         }
73420       } 
73421     }
73422
73423     /* Advance to the next name context.  The loop will exit when either
73424     ** we have a match (cnt>0) or when we run out of name contexts.
73425     */
73426     if( cnt==0 ){
73427       pNC = pNC->pNext;
73428     }
73429   }
73430
73431   /*
73432   ** If X and Y are NULL (in other words if only the column name Z is
73433   ** supplied) and the value of Z is enclosed in double-quotes, then
73434   ** Z is a string literal if it doesn't match any column names.  In that
73435   ** case, we need to return right away and not make any changes to
73436   ** pExpr.
73437   **
73438   ** Because no reference was made to outer contexts, the pNC->nRef
73439   ** fields are not changed in any context.
73440   */
73441   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
73442     pExpr->op = TK_STRING;
73443     pExpr->pTab = 0;
73444     return WRC_Prune;
73445   }
73446
73447   /*
73448   ** cnt==0 means there was not match.  cnt>1 means there were two or
73449   ** more matches.  Either way, we have an error.
73450   */
73451   if( cnt!=1 ){
73452     const char *zErr;
73453     zErr = cnt==0 ? "no such column" : "ambiguous column name";
73454     if( zDb ){
73455       sqlcipher3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
73456     }else if( zTab ){
73457       sqlcipher3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
73458     }else{
73459       sqlcipher3ErrorMsg(pParse, "%s: %s", zErr, zCol);
73460     }
73461     pParse->checkSchema = 1;
73462     pTopNC->nErr++;
73463   }
73464
73465   /* If a column from a table in pSrcList is referenced, then record
73466   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
73467   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
73468   ** column number is greater than the number of bits in the bitmask
73469   ** then set the high-order bit of the bitmask.
73470   */
73471   if( pExpr->iColumn>=0 && pMatch!=0 ){
73472     int n = pExpr->iColumn;
73473     testcase( n==BMS-1 );
73474     if( n>=BMS ){
73475       n = BMS-1;
73476     }
73477     assert( pMatch->iCursor==pExpr->iTable );
73478     pMatch->colUsed |= ((Bitmask)1)<<n;
73479   }
73480
73481   /* Clean up and return
73482   */
73483   sqlcipher3ExprDelete(db, pExpr->pLeft);
73484   pExpr->pLeft = 0;
73485   sqlcipher3ExprDelete(db, pExpr->pRight);
73486   pExpr->pRight = 0;
73487   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
73488 lookupname_end:
73489   if( cnt==1 ){
73490     assert( pNC!=0 );
73491     sqlcipher3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
73492     /* Increment the nRef value on all name contexts from TopNC up to
73493     ** the point where the name matched. */
73494     for(;;){
73495       assert( pTopNC!=0 );
73496       pTopNC->nRef++;
73497       if( pTopNC==pNC ) break;
73498       pTopNC = pTopNC->pNext;
73499     }
73500     return WRC_Prune;
73501   } else {
73502     return WRC_Abort;
73503   }
73504 }
73505
73506 /*
73507 ** Allocate and return a pointer to an expression to load the column iCol
73508 ** from datasource iSrc in SrcList pSrc.
73509 */
73510 SQLCIPHER_PRIVATE Expr *sqlcipher3CreateColumnExpr(sqlcipher3 *db, SrcList *pSrc, int iSrc, int iCol){
73511   Expr *p = sqlcipher3ExprAlloc(db, TK_COLUMN, 0, 0);
73512   if( p ){
73513     struct SrcList_item *pItem = &pSrc->a[iSrc];
73514     p->pTab = pItem->pTab;
73515     p->iTable = pItem->iCursor;
73516     if( p->pTab->iPKey==iCol ){
73517       p->iColumn = -1;
73518     }else{
73519       p->iColumn = (ynVar)iCol;
73520       testcase( iCol==BMS );
73521       testcase( iCol==BMS-1 );
73522       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
73523     }
73524     ExprSetProperty(p, EP_Resolved);
73525   }
73526   return p;
73527 }
73528
73529 /*
73530 ** This routine is callback for sqlcipher3WalkExpr().
73531 **
73532 ** Resolve symbolic names into TK_COLUMN operators for the current
73533 ** node in the expression tree.  Return 0 to continue the search down
73534 ** the tree or 2 to abort the tree walk.
73535 **
73536 ** This routine also does error checking and name resolution for
73537 ** function names.  The operator for aggregate functions is changed
73538 ** to TK_AGG_FUNCTION.
73539 */
73540 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
73541   NameContext *pNC;
73542   Parse *pParse;
73543
73544   pNC = pWalker->u.pNC;
73545   assert( pNC!=0 );
73546   pParse = pNC->pParse;
73547   assert( pParse==pWalker->pParse );
73548
73549   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
73550   ExprSetProperty(pExpr, EP_Resolved);
73551 #ifndef NDEBUG
73552   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
73553     SrcList *pSrcList = pNC->pSrcList;
73554     int i;
73555     for(i=0; i<pNC->pSrcList->nSrc; i++){
73556       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
73557     }
73558   }
73559 #endif
73560   switch( pExpr->op ){
73561
73562 #if defined(SQLCIPHER_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLCIPHER_OMIT_SUBQUERY)
73563     /* The special operator TK_ROW means use the rowid for the first
73564     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
73565     ** clause processing on UPDATE and DELETE statements.
73566     */
73567     case TK_ROW: {
73568       SrcList *pSrcList = pNC->pSrcList;
73569       struct SrcList_item *pItem;
73570       assert( pSrcList && pSrcList->nSrc==1 );
73571       pItem = pSrcList->a; 
73572       pExpr->op = TK_COLUMN;
73573       pExpr->pTab = pItem->pTab;
73574       pExpr->iTable = pItem->iCursor;
73575       pExpr->iColumn = -1;
73576       pExpr->affinity = SQLCIPHER_AFF_INTEGER;
73577       break;
73578     }
73579 #endif /* defined(SQLCIPHER_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLCIPHER_OMIT_SUBQUERY) */
73580
73581     /* A lone identifier is the name of a column.
73582     */
73583     case TK_ID: {
73584       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
73585     }
73586   
73587     /* A table name and column name:     ID.ID
73588     ** Or a database, table and column:  ID.ID.ID
73589     */
73590     case TK_DOT: {
73591       const char *zColumn;
73592       const char *zTable;
73593       const char *zDb;
73594       Expr *pRight;
73595
73596       /* if( pSrcList==0 ) break; */
73597       pRight = pExpr->pRight;
73598       if( pRight->op==TK_ID ){
73599         zDb = 0;
73600         zTable = pExpr->pLeft->u.zToken;
73601         zColumn = pRight->u.zToken;
73602       }else{
73603         assert( pRight->op==TK_DOT );
73604         zDb = pExpr->pLeft->u.zToken;
73605         zTable = pRight->pLeft->u.zToken;
73606         zColumn = pRight->pRight->u.zToken;
73607       }
73608       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
73609     }
73610
73611     /* Resolve function names
73612     */
73613     case TK_CONST_FUNC:
73614     case TK_FUNCTION: {
73615       ExprList *pList = pExpr->x.pList;    /* The argument list */
73616       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
73617       int no_such_func = 0;       /* True if no such function exists */
73618       int wrong_num_args = 0;     /* True if wrong number of arguments */
73619       int is_agg = 0;             /* True if is an aggregate function */
73620       int auth;                   /* Authorization to use the function */
73621       int nId;                    /* Number of characters in function name */
73622       const char *zId;            /* The function name. */
73623       FuncDef *pDef;              /* Information about the function */
73624       u8 enc = ENC(pParse->db);   /* The database encoding */
73625
73626       testcase( pExpr->op==TK_CONST_FUNC );
73627       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73628       zId = pExpr->u.zToken;
73629       nId = sqlcipher3Strlen30(zId);
73630       pDef = sqlcipher3FindFunction(pParse->db, zId, nId, n, enc, 0);
73631       if( pDef==0 ){
73632         pDef = sqlcipher3FindFunction(pParse->db, zId, nId, -1, enc, 0);
73633         if( pDef==0 ){
73634           no_such_func = 1;
73635         }else{
73636           wrong_num_args = 1;
73637         }
73638       }else{
73639         is_agg = pDef->xFunc==0;
73640       }
73641 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
73642       if( pDef ){
73643         auth = sqlcipher3AuthCheck(pParse, SQLCIPHER_FUNCTION, 0, pDef->zName, 0);
73644         if( auth!=SQLCIPHER_OK ){
73645           if( auth==SQLCIPHER_DENY ){
73646             sqlcipher3ErrorMsg(pParse, "not authorized to use function: %s",
73647                                     pDef->zName);
73648             pNC->nErr++;
73649           }
73650           pExpr->op = TK_NULL;
73651           return WRC_Prune;
73652         }
73653       }
73654 #endif
73655       if( is_agg && !pNC->allowAgg ){
73656         sqlcipher3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
73657         pNC->nErr++;
73658         is_agg = 0;
73659       }else if( no_such_func ){
73660         sqlcipher3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
73661         pNC->nErr++;
73662       }else if( wrong_num_args ){
73663         sqlcipher3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
73664              nId, zId);
73665         pNC->nErr++;
73666       }
73667       if( is_agg ){
73668         pExpr->op = TK_AGG_FUNCTION;
73669         pNC->hasAgg = 1;
73670       }
73671       if( is_agg ) pNC->allowAgg = 0;
73672       sqlcipher3WalkExprList(pWalker, pList);
73673       if( is_agg ) pNC->allowAgg = 1;
73674       /* FIX ME:  Compute pExpr->affinity based on the expected return
73675       ** type of the function 
73676       */
73677       return WRC_Prune;
73678     }
73679 #ifndef SQLCIPHER_OMIT_SUBQUERY
73680     case TK_SELECT:
73681     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
73682 #endif
73683     case TK_IN: {
73684       testcase( pExpr->op==TK_IN );
73685       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73686         int nRef = pNC->nRef;
73687 #ifndef SQLCIPHER_OMIT_CHECK
73688         if( pNC->isCheck ){
73689           sqlcipher3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
73690         }
73691 #endif
73692         sqlcipher3WalkSelect(pWalker, pExpr->x.pSelect);
73693         assert( pNC->nRef>=nRef );
73694         if( nRef!=pNC->nRef ){
73695           ExprSetProperty(pExpr, EP_VarSelect);
73696         }
73697       }
73698       break;
73699     }
73700 #ifndef SQLCIPHER_OMIT_CHECK
73701     case TK_VARIABLE: {
73702       if( pNC->isCheck ){
73703         sqlcipher3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
73704       }
73705       break;
73706     }
73707 #endif
73708   }
73709   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
73710 }
73711
73712 /*
73713 ** pEList is a list of expressions which are really the result set of the
73714 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
73715 ** This routine checks to see if pE is a simple identifier which corresponds
73716 ** to the AS-name of one of the terms of the expression list.  If it is,
73717 ** this routine return an integer between 1 and N where N is the number of
73718 ** elements in pEList, corresponding to the matching entry.  If there is
73719 ** no match, or if pE is not a simple identifier, then this routine
73720 ** return 0.
73721 **
73722 ** pEList has been resolved.  pE has not.
73723 */
73724 static int resolveAsName(
73725   Parse *pParse,     /* Parsing context for error messages */
73726   ExprList *pEList,  /* List of expressions to scan */
73727   Expr *pE           /* Expression we are trying to match */
73728 ){
73729   int i;             /* Loop counter */
73730
73731   UNUSED_PARAMETER(pParse);
73732
73733   if( pE->op==TK_ID ){
73734     char *zCol = pE->u.zToken;
73735     for(i=0; i<pEList->nExpr; i++){
73736       char *zAs = pEList->a[i].zName;
73737       if( zAs!=0 && sqlcipher3StrICmp(zAs, zCol)==0 ){
73738         return i+1;
73739       }
73740     }
73741   }
73742   return 0;
73743 }
73744
73745 /*
73746 ** pE is a pointer to an expression which is a single term in the
73747 ** ORDER BY of a compound SELECT.  The expression has not been
73748 ** name resolved.
73749 **
73750 ** At the point this routine is called, we already know that the
73751 ** ORDER BY term is not an integer index into the result set.  That
73752 ** case is handled by the calling routine.
73753 **
73754 ** Attempt to match pE against result set columns in the left-most
73755 ** SELECT statement.  Return the index i of the matching column,
73756 ** as an indication to the caller that it should sort by the i-th column.
73757 ** The left-most column is 1.  In other words, the value returned is the
73758 ** same integer value that would be used in the SQL statement to indicate
73759 ** the column.
73760 **
73761 ** If there is no match, return 0.  Return -1 if an error occurs.
73762 */
73763 static int resolveOrderByTermToExprList(
73764   Parse *pParse,     /* Parsing context for error messages */
73765   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
73766   Expr *pE           /* The specific ORDER BY term */
73767 ){
73768   int i;             /* Loop counter */
73769   ExprList *pEList;  /* The columns of the result set */
73770   NameContext nc;    /* Name context for resolving pE */
73771   sqlcipher3 *db;       /* Database connection */
73772   int rc;            /* Return code from subprocedures */
73773   u8 savedSuppErr;   /* Saved value of db->suppressErr */
73774
73775   assert( sqlcipher3ExprIsInteger(pE, &i)==0 );
73776   pEList = pSelect->pEList;
73777
73778   /* Resolve all names in the ORDER BY term expression
73779   */
73780   memset(&nc, 0, sizeof(nc));
73781   nc.pParse = pParse;
73782   nc.pSrcList = pSelect->pSrc;
73783   nc.pEList = pEList;
73784   nc.allowAgg = 1;
73785   nc.nErr = 0;
73786   db = pParse->db;
73787   savedSuppErr = db->suppressErr;
73788   db->suppressErr = 1;
73789   rc = sqlcipher3ResolveExprNames(&nc, pE);
73790   db->suppressErr = savedSuppErr;
73791   if( rc ) return 0;
73792
73793   /* Try to match the ORDER BY expression against an expression
73794   ** in the result set.  Return an 1-based index of the matching
73795   ** result-set entry.
73796   */
73797   for(i=0; i<pEList->nExpr; i++){
73798     if( sqlcipher3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
73799       return i+1;
73800     }
73801   }
73802
73803   /* If no match, return 0. */
73804   return 0;
73805 }
73806
73807 /*
73808 ** Generate an ORDER BY or GROUP BY term out-of-range error.
73809 */
73810 static void resolveOutOfRangeError(
73811   Parse *pParse,         /* The error context into which to write the error */
73812   const char *zType,     /* "ORDER" or "GROUP" */
73813   int i,                 /* The index (1-based) of the term out of range */
73814   int mx                 /* Largest permissible value of i */
73815 ){
73816   sqlcipher3ErrorMsg(pParse, 
73817     "%r %s BY term out of range - should be "
73818     "between 1 and %d", i, zType, mx);
73819 }
73820
73821 /*
73822 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
73823 ** each term of the ORDER BY clause is a constant integer between 1
73824 ** and N where N is the number of columns in the compound SELECT.
73825 **
73826 ** ORDER BY terms that are already an integer between 1 and N are
73827 ** unmodified.  ORDER BY terms that are integers outside the range of
73828 ** 1 through N generate an error.  ORDER BY terms that are expressions
73829 ** are matched against result set expressions of compound SELECT
73830 ** beginning with the left-most SELECT and working toward the right.
73831 ** At the first match, the ORDER BY expression is transformed into
73832 ** the integer column number.
73833 **
73834 ** Return the number of errors seen.
73835 */
73836 static int resolveCompoundOrderBy(
73837   Parse *pParse,        /* Parsing context.  Leave error messages here */
73838   Select *pSelect       /* The SELECT statement containing the ORDER BY */
73839 ){
73840   int i;
73841   ExprList *pOrderBy;
73842   ExprList *pEList;
73843   sqlcipher3 *db;
73844   int moreToDo = 1;
73845
73846   pOrderBy = pSelect->pOrderBy;
73847   if( pOrderBy==0 ) return 0;
73848   db = pParse->db;
73849 #if SQLCIPHER_MAX_COLUMN
73850   if( pOrderBy->nExpr>db->aLimit[SQLCIPHER_LIMIT_COLUMN] ){
73851     sqlcipher3ErrorMsg(pParse, "too many terms in ORDER BY clause");
73852     return 1;
73853   }
73854 #endif
73855   for(i=0; i<pOrderBy->nExpr; i++){
73856     pOrderBy->a[i].done = 0;
73857   }
73858   pSelect->pNext = 0;
73859   while( pSelect->pPrior ){
73860     pSelect->pPrior->pNext = pSelect;
73861     pSelect = pSelect->pPrior;
73862   }
73863   while( pSelect && moreToDo ){
73864     struct ExprList_item *pItem;
73865     moreToDo = 0;
73866     pEList = pSelect->pEList;
73867     assert( pEList!=0 );
73868     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73869       int iCol = -1;
73870       Expr *pE, *pDup;
73871       if( pItem->done ) continue;
73872       pE = pItem->pExpr;
73873       if( sqlcipher3ExprIsInteger(pE, &iCol) ){
73874         if( iCol<=0 || iCol>pEList->nExpr ){
73875           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
73876           return 1;
73877         }
73878       }else{
73879         iCol = resolveAsName(pParse, pEList, pE);
73880         if( iCol==0 ){
73881           pDup = sqlcipher3ExprDup(db, pE, 0);
73882           if( !db->mallocFailed ){
73883             assert(pDup);
73884             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
73885           }
73886           sqlcipher3ExprDelete(db, pDup);
73887         }
73888       }
73889       if( iCol>0 ){
73890         CollSeq *pColl = pE->pColl;
73891         int flags = pE->flags & EP_ExpCollate;
73892         sqlcipher3ExprDelete(db, pE);
73893         pItem->pExpr = pE = sqlcipher3Expr(db, TK_INTEGER, 0);
73894         if( pE==0 ) return 1;
73895         pE->pColl = pColl;
73896         pE->flags |= EP_IntValue | flags;
73897         pE->u.iValue = iCol;
73898         pItem->iCol = (u16)iCol;
73899         pItem->done = 1;
73900       }else{
73901         moreToDo = 1;
73902       }
73903     }
73904     pSelect = pSelect->pNext;
73905   }
73906   for(i=0; i<pOrderBy->nExpr; i++){
73907     if( pOrderBy->a[i].done==0 ){
73908       sqlcipher3ErrorMsg(pParse, "%r ORDER BY term does not match any "
73909             "column in the result set", i+1);
73910       return 1;
73911     }
73912   }
73913   return 0;
73914 }
73915
73916 /*
73917 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
73918 ** the SELECT statement pSelect.  If any term is reference to a
73919 ** result set expression (as determined by the ExprList.a.iCol field)
73920 ** then convert that term into a copy of the corresponding result set
73921 ** column.
73922 **
73923 ** If any errors are detected, add an error message to pParse and
73924 ** return non-zero.  Return zero if no errors are seen.
73925 */
73926 SQLCIPHER_PRIVATE int sqlcipher3ResolveOrderGroupBy(
73927   Parse *pParse,        /* Parsing context.  Leave error messages here */
73928   Select *pSelect,      /* The SELECT statement containing the clause */
73929   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
73930   const char *zType     /* "ORDER" or "GROUP" */
73931 ){
73932   int i;
73933   sqlcipher3 *db = pParse->db;
73934   ExprList *pEList;
73935   struct ExprList_item *pItem;
73936
73937   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
73938 #if SQLCIPHER_MAX_COLUMN
73939   if( pOrderBy->nExpr>db->aLimit[SQLCIPHER_LIMIT_COLUMN] ){
73940     sqlcipher3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
73941     return 1;
73942   }
73943 #endif
73944   pEList = pSelect->pEList;
73945   assert( pEList!=0 );  /* sqlcipher3SelectNew() guarantees this */
73946   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73947     if( pItem->iCol ){
73948       if( pItem->iCol>pEList->nExpr ){
73949         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
73950         return 1;
73951       }
73952       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
73953     }
73954   }
73955   return 0;
73956 }
73957
73958 /*
73959 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
73960 ** The Name context of the SELECT statement is pNC.  zType is either
73961 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
73962 **
73963 ** This routine resolves each term of the clause into an expression.
73964 ** If the order-by term is an integer I between 1 and N (where N is the
73965 ** number of columns in the result set of the SELECT) then the expression
73966 ** in the resolution is a copy of the I-th result-set expression.  If
73967 ** the order-by term is an identify that corresponds to the AS-name of
73968 ** a result-set expression, then the term resolves to a copy of the
73969 ** result-set expression.  Otherwise, the expression is resolved in
73970 ** the usual way - using sqlcipher3ResolveExprNames().
73971 **
73972 ** This routine returns the number of errors.  If errors occur, then
73973 ** an appropriate error message might be left in pParse.  (OOM errors
73974 ** excepted.)
73975 */
73976 static int resolveOrderGroupBy(
73977   NameContext *pNC,     /* The name context of the SELECT statement */
73978   Select *pSelect,      /* The SELECT statement holding pOrderBy */
73979   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
73980   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
73981 ){
73982   int i;                         /* Loop counter */
73983   int iCol;                      /* Column number */
73984   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
73985   Parse *pParse;                 /* Parsing context */
73986   int nResult;                   /* Number of terms in the result set */
73987
73988   if( pOrderBy==0 ) return 0;
73989   nResult = pSelect->pEList->nExpr;
73990   pParse = pNC->pParse;
73991   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73992     Expr *pE = pItem->pExpr;
73993     iCol = resolveAsName(pParse, pSelect->pEList, pE);
73994     if( iCol>0 ){
73995       /* If an AS-name match is found, mark this ORDER BY column as being
73996       ** a copy of the iCol-th result-set column.  The subsequent call to
73997       ** sqlcipher3ResolveOrderGroupBy() will convert the expression to a
73998       ** copy of the iCol-th result-set expression. */
73999       pItem->iCol = (u16)iCol;
74000       continue;
74001     }
74002     if( sqlcipher3ExprIsInteger(pE, &iCol) ){
74003       /* The ORDER BY term is an integer constant.  Again, set the column
74004       ** number so that sqlcipher3ResolveOrderGroupBy() will convert the
74005       ** order-by term to a copy of the result-set expression */
74006       if( iCol<1 ){
74007         resolveOutOfRangeError(pParse, zType, i+1, nResult);
74008         return 1;
74009       }
74010       pItem->iCol = (u16)iCol;
74011       continue;
74012     }
74013
74014     /* Otherwise, treat the ORDER BY term as an ordinary expression */
74015     pItem->iCol = 0;
74016     if( sqlcipher3ResolveExprNames(pNC, pE) ){
74017       return 1;
74018     }
74019   }
74020   return sqlcipher3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
74021 }
74022
74023 /*
74024 ** Resolve names in the SELECT statement p and all of its descendents.
74025 */
74026 static int resolveSelectStep(Walker *pWalker, Select *p){
74027   NameContext *pOuterNC;  /* Context that contains this SELECT */
74028   NameContext sNC;        /* Name context of this SELECT */
74029   int isCompound;         /* True if p is a compound select */
74030   int nCompound;          /* Number of compound terms processed so far */
74031   Parse *pParse;          /* Parsing context */
74032   ExprList *pEList;       /* Result set expression list */
74033   int i;                  /* Loop counter */
74034   ExprList *pGroupBy;     /* The GROUP BY clause */
74035   Select *pLeftmost;      /* Left-most of SELECT of a compound */
74036   sqlcipher3 *db;            /* Database connection */
74037   
74038
74039   assert( p!=0 );
74040   if( p->selFlags & SF_Resolved ){
74041     return WRC_Prune;
74042   }
74043   pOuterNC = pWalker->u.pNC;
74044   pParse = pWalker->pParse;
74045   db = pParse->db;
74046
74047   /* Normally sqlcipher3SelectExpand() will be called first and will have
74048   ** already expanded this SELECT.  However, if this is a subquery within
74049   ** an expression, sqlcipher3ResolveExprNames() will be called without a
74050   ** prior call to sqlcipher3SelectExpand().  When that happens, let
74051   ** sqlcipher3SelectPrep() do all of the processing for this SELECT.
74052   ** sqlcipher3SelectPrep() will invoke both sqlcipher3SelectExpand() and
74053   ** this routine in the correct order.
74054   */
74055   if( (p->selFlags & SF_Expanded)==0 ){
74056     sqlcipher3SelectPrep(pParse, p, pOuterNC);
74057     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
74058   }
74059
74060   isCompound = p->pPrior!=0;
74061   nCompound = 0;
74062   pLeftmost = p;
74063   while( p ){
74064     assert( (p->selFlags & SF_Expanded)!=0 );
74065     assert( (p->selFlags & SF_Resolved)==0 );
74066     p->selFlags |= SF_Resolved;
74067
74068     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
74069     ** are not allowed to refer to any names, so pass an empty NameContext.
74070     */
74071     memset(&sNC, 0, sizeof(sNC));
74072     sNC.pParse = pParse;
74073     if( sqlcipher3ResolveExprNames(&sNC, p->pLimit) ||
74074         sqlcipher3ResolveExprNames(&sNC, p->pOffset) ){
74075       return WRC_Abort;
74076     }
74077   
74078     /* Set up the local name-context to pass to sqlcipher3ResolveExprNames() to
74079     ** resolve the result-set expression list.
74080     */
74081     sNC.allowAgg = 1;
74082     sNC.pSrcList = p->pSrc;
74083     sNC.pNext = pOuterNC;
74084   
74085     /* Resolve names in the result set. */
74086     pEList = p->pEList;
74087     assert( pEList!=0 );
74088     for(i=0; i<pEList->nExpr; i++){
74089       Expr *pX = pEList->a[i].pExpr;
74090       if( sqlcipher3ResolveExprNames(&sNC, pX) ){
74091         return WRC_Abort;
74092       }
74093     }
74094   
74095     /* Recursively resolve names in all subqueries
74096     */
74097     for(i=0; i<p->pSrc->nSrc; i++){
74098       struct SrcList_item *pItem = &p->pSrc->a[i];
74099       if( pItem->pSelect ){
74100         NameContext *pNC;         /* Used to iterate name contexts */
74101         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
74102         const char *zSavedContext = pParse->zAuthContext;
74103
74104         /* Count the total number of references to pOuterNC and all of its
74105         ** parent contexts. After resolving references to expressions in
74106         ** pItem->pSelect, check if this value has changed. If so, then
74107         ** SELECT statement pItem->pSelect must be correlated. Set the
74108         ** pItem->isCorrelated flag if this is the case. */
74109         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
74110
74111         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
74112         sqlcipher3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
74113         pParse->zAuthContext = zSavedContext;
74114         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
74115
74116         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
74117         assert( pItem->isCorrelated==0 && nRef<=0 );
74118         pItem->isCorrelated = (nRef!=0);
74119       }
74120     }
74121   
74122     /* If there are no aggregate functions in the result-set, and no GROUP BY 
74123     ** expression, do not allow aggregates in any of the other expressions.
74124     */
74125     assert( (p->selFlags & SF_Aggregate)==0 );
74126     pGroupBy = p->pGroupBy;
74127     if( pGroupBy || sNC.hasAgg ){
74128       p->selFlags |= SF_Aggregate;
74129     }else{
74130       sNC.allowAgg = 0;
74131     }
74132   
74133     /* If a HAVING clause is present, then there must be a GROUP BY clause.
74134     */
74135     if( p->pHaving && !pGroupBy ){
74136       sqlcipher3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
74137       return WRC_Abort;
74138     }
74139   
74140     /* Add the expression list to the name-context before parsing the
74141     ** other expressions in the SELECT statement. This is so that
74142     ** expressions in the WHERE clause (etc.) can refer to expressions by
74143     ** aliases in the result set.
74144     **
74145     ** Minor point: If this is the case, then the expression will be
74146     ** re-evaluated for each reference to it.
74147     */
74148     sNC.pEList = p->pEList;
74149     if( sqlcipher3ResolveExprNames(&sNC, p->pWhere) ||
74150        sqlcipher3ResolveExprNames(&sNC, p->pHaving)
74151     ){
74152       return WRC_Abort;
74153     }
74154
74155     /* The ORDER BY and GROUP BY clauses may not refer to terms in
74156     ** outer queries 
74157     */
74158     sNC.pNext = 0;
74159     sNC.allowAgg = 1;
74160
74161     /* Process the ORDER BY clause for singleton SELECT statements.
74162     ** The ORDER BY clause for compounds SELECT statements is handled
74163     ** below, after all of the result-sets for all of the elements of
74164     ** the compound have been resolved.
74165     */
74166     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
74167       return WRC_Abort;
74168     }
74169     if( db->mallocFailed ){
74170       return WRC_Abort;
74171     }
74172   
74173     /* Resolve the GROUP BY clause.  At the same time, make sure 
74174     ** the GROUP BY clause does not contain aggregate functions.
74175     */
74176     if( pGroupBy ){
74177       struct ExprList_item *pItem;
74178     
74179       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
74180         return WRC_Abort;
74181       }
74182       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
74183         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
74184           sqlcipher3ErrorMsg(pParse, "aggregate functions are not allowed in "
74185               "the GROUP BY clause");
74186           return WRC_Abort;
74187         }
74188       }
74189     }
74190
74191     /* Advance to the next term of the compound
74192     */
74193     p = p->pPrior;
74194     nCompound++;
74195   }
74196
74197   /* Resolve the ORDER BY on a compound SELECT after all terms of
74198   ** the compound have been resolved.
74199   */
74200   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
74201     return WRC_Abort;
74202   }
74203
74204   return WRC_Prune;
74205 }
74206
74207 /*
74208 ** This routine walks an expression tree and resolves references to
74209 ** table columns and result-set columns.  At the same time, do error
74210 ** checking on function usage and set a flag if any aggregate functions
74211 ** are seen.
74212 **
74213 ** To resolve table columns references we look for nodes (or subtrees) of the 
74214 ** form X.Y.Z or Y.Z or just Z where
74215 **
74216 **      X:   The name of a database.  Ex:  "main" or "temp" or
74217 **           the symbolic name assigned to an ATTACH-ed database.
74218 **
74219 **      Y:   The name of a table in a FROM clause.  Or in a trigger
74220 **           one of the special names "old" or "new".
74221 **
74222 **      Z:   The name of a column in table Y.
74223 **
74224 ** The node at the root of the subtree is modified as follows:
74225 **
74226 **    Expr.op        Changed to TK_COLUMN
74227 **    Expr.pTab      Points to the Table object for X.Y
74228 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
74229 **    Expr.iTable    The VDBE cursor number for X.Y
74230 **
74231 **
74232 ** To resolve result-set references, look for expression nodes of the
74233 ** form Z (with no X and Y prefix) where the Z matches the right-hand
74234 ** size of an AS clause in the result-set of a SELECT.  The Z expression
74235 ** is replaced by a copy of the left-hand side of the result-set expression.
74236 ** Table-name and function resolution occurs on the substituted expression
74237 ** tree.  For example, in:
74238 **
74239 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
74240 **
74241 ** The "x" term of the order by is replaced by "a+b" to render:
74242 **
74243 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
74244 **
74245 ** Function calls are checked to make sure that the function is 
74246 ** defined and that the correct number of arguments are specified.
74247 ** If the function is an aggregate function, then the pNC->hasAgg is
74248 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
74249 ** If an expression contains aggregate functions then the EP_Agg
74250 ** property on the expression is set.
74251 **
74252 ** An error message is left in pParse if anything is amiss.  The number
74253 ** if errors is returned.
74254 */
74255 SQLCIPHER_PRIVATE int sqlcipher3ResolveExprNames( 
74256   NameContext *pNC,       /* Namespace to resolve expressions in. */
74257   Expr *pExpr             /* The expression to be analyzed. */
74258 ){
74259   int savedHasAgg;
74260   Walker w;
74261
74262   if( pExpr==0 ) return 0;
74263 #if SQLCIPHER_MAX_EXPR_DEPTH>0
74264   {
74265     Parse *pParse = pNC->pParse;
74266     if( sqlcipher3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
74267       return 1;
74268     }
74269     pParse->nHeight += pExpr->nHeight;
74270   }
74271 #endif
74272   savedHasAgg = pNC->hasAgg;
74273   pNC->hasAgg = 0;
74274   w.xExprCallback = resolveExprStep;
74275   w.xSelectCallback = resolveSelectStep;
74276   w.pParse = pNC->pParse;
74277   w.u.pNC = pNC;
74278   sqlcipher3WalkExpr(&w, pExpr);
74279 #if SQLCIPHER_MAX_EXPR_DEPTH>0
74280   pNC->pParse->nHeight -= pExpr->nHeight;
74281 #endif
74282   if( pNC->nErr>0 || w.pParse->nErr>0 ){
74283     ExprSetProperty(pExpr, EP_Error);
74284   }
74285   if( pNC->hasAgg ){
74286     ExprSetProperty(pExpr, EP_Agg);
74287   }else if( savedHasAgg ){
74288     pNC->hasAgg = 1;
74289   }
74290   return ExprHasProperty(pExpr, EP_Error);
74291 }
74292
74293
74294 /*
74295 ** Resolve all names in all expressions of a SELECT and in all
74296 ** decendents of the SELECT, including compounds off of p->pPrior,
74297 ** subqueries in expressions, and subqueries used as FROM clause
74298 ** terms.
74299 **
74300 ** See sqlcipher3ResolveExprNames() for a description of the kinds of
74301 ** transformations that occur.
74302 **
74303 ** All SELECT statements should have been expanded using
74304 ** sqlcipher3SelectExpand() prior to invoking this routine.
74305 */
74306 SQLCIPHER_PRIVATE void sqlcipher3ResolveSelectNames(
74307   Parse *pParse,         /* The parser context */
74308   Select *p,             /* The SELECT statement being coded. */
74309   NameContext *pOuterNC  /* Name context for parent SELECT statement */
74310 ){
74311   Walker w;
74312
74313   assert( p!=0 );
74314   w.xExprCallback = resolveExprStep;
74315   w.xSelectCallback = resolveSelectStep;
74316   w.pParse = pParse;
74317   w.u.pNC = pOuterNC;
74318   sqlcipher3WalkSelect(&w, p);
74319 }
74320
74321 /************** End of resolve.c *********************************************/
74322 /************** Begin file expr.c ********************************************/
74323 /*
74324 ** 2001 September 15
74325 **
74326 ** The author disclaims copyright to this source code.  In place of
74327 ** a legal notice, here is a blessing:
74328 **
74329 **    May you do good and not evil.
74330 **    May you find forgiveness for yourself and forgive others.
74331 **    May you share freely, never taking more than you give.
74332 **
74333 *************************************************************************
74334 ** This file contains routines used for analyzing expressions and
74335 ** for generating VDBE code that evaluates expressions in SQLite.
74336 */
74337
74338 /*
74339 ** Return the 'affinity' of the expression pExpr if any.
74340 **
74341 ** If pExpr is a column, a reference to a column via an 'AS' alias,
74342 ** or a sub-select with a column as the return value, then the 
74343 ** affinity of that column is returned. Otherwise, 0x00 is returned,
74344 ** indicating no affinity for the expression.
74345 **
74346 ** i.e. the WHERE clause expresssions in the following statements all
74347 ** have an affinity:
74348 **
74349 ** CREATE TABLE t1(a);
74350 ** SELECT * FROM t1 WHERE a;
74351 ** SELECT a AS b FROM t1 WHERE b;
74352 ** SELECT * FROM t1 WHERE (select a from t1);
74353 */
74354 SQLCIPHER_PRIVATE char sqlcipher3ExprAffinity(Expr *pExpr){
74355   int op = pExpr->op;
74356   if( op==TK_SELECT ){
74357     assert( pExpr->flags&EP_xIsSelect );
74358     return sqlcipher3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
74359   }
74360 #ifndef SQLCIPHER_OMIT_CAST
74361   if( op==TK_CAST ){
74362     assert( !ExprHasProperty(pExpr, EP_IntValue) );
74363     return sqlcipher3AffinityType(pExpr->u.zToken);
74364   }
74365 #endif
74366   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
74367    && pExpr->pTab!=0
74368   ){
74369     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
74370     ** a TK_COLUMN but was previously evaluated and cached in a register */
74371     int j = pExpr->iColumn;
74372     if( j<0 ) return SQLCIPHER_AFF_INTEGER;
74373     assert( pExpr->pTab && j<pExpr->pTab->nCol );
74374     return pExpr->pTab->aCol[j].affinity;
74375   }
74376   return pExpr->affinity;
74377 }
74378
74379 /*
74380 ** Set the explicit collating sequence for an expression to the
74381 ** collating sequence supplied in the second argument.
74382 */
74383 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprSetColl(Expr *pExpr, CollSeq *pColl){
74384   if( pExpr && pColl ){
74385     pExpr->pColl = pColl;
74386     pExpr->flags |= EP_ExpCollate;
74387   }
74388   return pExpr;
74389 }
74390
74391 /*
74392 ** Set the collating sequence for expression pExpr to be the collating
74393 ** sequence named by pToken.   Return a pointer to the revised expression.
74394 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
74395 ** flag.  An explicit collating sequence will override implicit
74396 ** collating sequences.
74397 */
74398 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
74399   char *zColl = 0;            /* Dequoted name of collation sequence */
74400   CollSeq *pColl;
74401   sqlcipher3 *db = pParse->db;
74402   zColl = sqlcipher3NameFromToken(db, pCollName);
74403   pColl = sqlcipher3LocateCollSeq(pParse, zColl);
74404   sqlcipher3ExprSetColl(pExpr, pColl);
74405   sqlcipher3DbFree(db, zColl);
74406   return pExpr;
74407 }
74408
74409 /*
74410 ** Return the default collation sequence for the expression pExpr. If
74411 ** there is no default collation type, return 0.
74412 */
74413 SQLCIPHER_PRIVATE CollSeq *sqlcipher3ExprCollSeq(Parse *pParse, Expr *pExpr){
74414   CollSeq *pColl = 0;
74415   Expr *p = pExpr;
74416   while( p ){
74417     int op;
74418     pColl = p->pColl;
74419     if( pColl ) break;
74420     op = p->op;
74421     if( p->pTab!=0 && (
74422         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
74423     )){
74424       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
74425       ** a TK_COLUMN but was previously evaluated and cached in a register */
74426       const char *zColl;
74427       int j = p->iColumn;
74428       if( j>=0 ){
74429         sqlcipher3 *db = pParse->db;
74430         zColl = p->pTab->aCol[j].zColl;
74431         pColl = sqlcipher3FindCollSeq(db, ENC(db), zColl, 0);
74432         pExpr->pColl = pColl;
74433       }
74434       break;
74435     }
74436     if( op!=TK_CAST && op!=TK_UPLUS ){
74437       break;
74438     }
74439     p = p->pLeft;
74440   }
74441   if( sqlcipher3CheckCollSeq(pParse, pColl) ){ 
74442     pColl = 0;
74443   }
74444   return pColl;
74445 }
74446
74447 /*
74448 ** pExpr is an operand of a comparison operator.  aff2 is the
74449 ** type affinity of the other operand.  This routine returns the
74450 ** type affinity that should be used for the comparison operator.
74451 */
74452 SQLCIPHER_PRIVATE char sqlcipher3CompareAffinity(Expr *pExpr, char aff2){
74453   char aff1 = sqlcipher3ExprAffinity(pExpr);
74454   if( aff1 && aff2 ){
74455     /* Both sides of the comparison are columns. If one has numeric
74456     ** affinity, use that. Otherwise use no affinity.
74457     */
74458     if( sqlcipher3IsNumericAffinity(aff1) || sqlcipher3IsNumericAffinity(aff2) ){
74459       return SQLCIPHER_AFF_NUMERIC;
74460     }else{
74461       return SQLCIPHER_AFF_NONE;
74462     }
74463   }else if( !aff1 && !aff2 ){
74464     /* Neither side of the comparison is a column.  Compare the
74465     ** results directly.
74466     */
74467     return SQLCIPHER_AFF_NONE;
74468   }else{
74469     /* One side is a column, the other is not. Use the columns affinity. */
74470     assert( aff1==0 || aff2==0 );
74471     return (aff1 + aff2);
74472   }
74473 }
74474
74475 /*
74476 ** pExpr is a comparison operator.  Return the type affinity that should
74477 ** be applied to both operands prior to doing the comparison.
74478 */
74479 static char comparisonAffinity(Expr *pExpr){
74480   char aff;
74481   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
74482           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
74483           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
74484   assert( pExpr->pLeft );
74485   aff = sqlcipher3ExprAffinity(pExpr->pLeft);
74486   if( pExpr->pRight ){
74487     aff = sqlcipher3CompareAffinity(pExpr->pRight, aff);
74488   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74489     aff = sqlcipher3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
74490   }else if( !aff ){
74491     aff = SQLCIPHER_AFF_NONE;
74492   }
74493   return aff;
74494 }
74495
74496 /*
74497 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
74498 ** idx_affinity is the affinity of an indexed column. Return true
74499 ** if the index with affinity idx_affinity may be used to implement
74500 ** the comparison in pExpr.
74501 */
74502 SQLCIPHER_PRIVATE int sqlcipher3IndexAffinityOk(Expr *pExpr, char idx_affinity){
74503   char aff = comparisonAffinity(pExpr);
74504   switch( aff ){
74505     case SQLCIPHER_AFF_NONE:
74506       return 1;
74507     case SQLCIPHER_AFF_TEXT:
74508       return idx_affinity==SQLCIPHER_AFF_TEXT;
74509     default:
74510       return sqlcipher3IsNumericAffinity(idx_affinity);
74511   }
74512 }
74513
74514 /*
74515 ** Return the P5 value that should be used for a binary comparison
74516 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
74517 */
74518 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
74519   u8 aff = (char)sqlcipher3ExprAffinity(pExpr2);
74520   aff = (u8)sqlcipher3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
74521   return aff;
74522 }
74523
74524 /*
74525 ** Return a pointer to the collation sequence that should be used by
74526 ** a binary comparison operator comparing pLeft and pRight.
74527 **
74528 ** If the left hand expression has a collating sequence type, then it is
74529 ** used. Otherwise the collation sequence for the right hand expression
74530 ** is used, or the default (BINARY) if neither expression has a collating
74531 ** type.
74532 **
74533 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
74534 ** it is not considered.
74535 */
74536 SQLCIPHER_PRIVATE CollSeq *sqlcipher3BinaryCompareCollSeq(
74537   Parse *pParse, 
74538   Expr *pLeft, 
74539   Expr *pRight
74540 ){
74541   CollSeq *pColl;
74542   assert( pLeft );
74543   if( pLeft->flags & EP_ExpCollate ){
74544     assert( pLeft->pColl );
74545     pColl = pLeft->pColl;
74546   }else if( pRight && pRight->flags & EP_ExpCollate ){
74547     assert( pRight->pColl );
74548     pColl = pRight->pColl;
74549   }else{
74550     pColl = sqlcipher3ExprCollSeq(pParse, pLeft);
74551     if( !pColl ){
74552       pColl = sqlcipher3ExprCollSeq(pParse, pRight);
74553     }
74554   }
74555   return pColl;
74556 }
74557
74558 /*
74559 ** Generate code for a comparison operator.
74560 */
74561 static int codeCompare(
74562   Parse *pParse,    /* The parsing (and code generating) context */
74563   Expr *pLeft,      /* The left operand */
74564   Expr *pRight,     /* The right operand */
74565   int opcode,       /* The comparison opcode */
74566   int in1, int in2, /* Register holding operands */
74567   int dest,         /* Jump here if true.  */
74568   int jumpIfNull    /* If true, jump if either operand is NULL */
74569 ){
74570   int p5;
74571   int addr;
74572   CollSeq *p4;
74573
74574   p4 = sqlcipher3BinaryCompareCollSeq(pParse, pLeft, pRight);
74575   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
74576   addr = sqlcipher3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
74577                            (void*)p4, P4_COLLSEQ);
74578   sqlcipher3VdbeChangeP5(pParse->pVdbe, (u8)p5);
74579   return addr;
74580 }
74581
74582 #if SQLCIPHER_MAX_EXPR_DEPTH>0
74583 /*
74584 ** Check that argument nHeight is less than or equal to the maximum
74585 ** expression depth allowed. If it is not, leave an error message in
74586 ** pParse.
74587 */
74588 SQLCIPHER_PRIVATE int sqlcipher3ExprCheckHeight(Parse *pParse, int nHeight){
74589   int rc = SQLCIPHER_OK;
74590   int mxHeight = pParse->db->aLimit[SQLCIPHER_LIMIT_EXPR_DEPTH];
74591   if( nHeight>mxHeight ){
74592     sqlcipher3ErrorMsg(pParse, 
74593        "Expression tree is too large (maximum depth %d)", mxHeight
74594     );
74595     rc = SQLCIPHER_ERROR;
74596   }
74597   return rc;
74598 }
74599
74600 /* The following three functions, heightOfExpr(), heightOfExprList()
74601 ** and heightOfSelect(), are used to determine the maximum height
74602 ** of any expression tree referenced by the structure passed as the
74603 ** first argument.
74604 **
74605 ** If this maximum height is greater than the current value pointed
74606 ** to by pnHeight, the second parameter, then set *pnHeight to that
74607 ** value.
74608 */
74609 static void heightOfExpr(Expr *p, int *pnHeight){
74610   if( p ){
74611     if( p->nHeight>*pnHeight ){
74612       *pnHeight = p->nHeight;
74613     }
74614   }
74615 }
74616 static void heightOfExprList(ExprList *p, int *pnHeight){
74617   if( p ){
74618     int i;
74619     for(i=0; i<p->nExpr; i++){
74620       heightOfExpr(p->a[i].pExpr, pnHeight);
74621     }
74622   }
74623 }
74624 static void heightOfSelect(Select *p, int *pnHeight){
74625   if( p ){
74626     heightOfExpr(p->pWhere, pnHeight);
74627     heightOfExpr(p->pHaving, pnHeight);
74628     heightOfExpr(p->pLimit, pnHeight);
74629     heightOfExpr(p->pOffset, pnHeight);
74630     heightOfExprList(p->pEList, pnHeight);
74631     heightOfExprList(p->pGroupBy, pnHeight);
74632     heightOfExprList(p->pOrderBy, pnHeight);
74633     heightOfSelect(p->pPrior, pnHeight);
74634   }
74635 }
74636
74637 /*
74638 ** Set the Expr.nHeight variable in the structure passed as an 
74639 ** argument. An expression with no children, Expr.pList or 
74640 ** Expr.pSelect member has a height of 1. Any other expression
74641 ** has a height equal to the maximum height of any other 
74642 ** referenced Expr plus one.
74643 */
74644 static void exprSetHeight(Expr *p){
74645   int nHeight = 0;
74646   heightOfExpr(p->pLeft, &nHeight);
74647   heightOfExpr(p->pRight, &nHeight);
74648   if( ExprHasProperty(p, EP_xIsSelect) ){
74649     heightOfSelect(p->x.pSelect, &nHeight);
74650   }else{
74651     heightOfExprList(p->x.pList, &nHeight);
74652   }
74653   p->nHeight = nHeight + 1;
74654 }
74655
74656 /*
74657 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
74658 ** the height is greater than the maximum allowed expression depth,
74659 ** leave an error in pParse.
74660 */
74661 SQLCIPHER_PRIVATE void sqlcipher3ExprSetHeight(Parse *pParse, Expr *p){
74662   exprSetHeight(p);
74663   sqlcipher3ExprCheckHeight(pParse, p->nHeight);
74664 }
74665
74666 /*
74667 ** Return the maximum height of any expression tree referenced
74668 ** by the select statement passed as an argument.
74669 */
74670 SQLCIPHER_PRIVATE int sqlcipher3SelectExprHeight(Select *p){
74671   int nHeight = 0;
74672   heightOfSelect(p, &nHeight);
74673   return nHeight;
74674 }
74675 #else
74676   #define exprSetHeight(y)
74677 #endif /* SQLCIPHER_MAX_EXPR_DEPTH>0 */
74678
74679 /*
74680 ** This routine is the core allocator for Expr nodes.
74681 **
74682 ** Construct a new expression node and return a pointer to it.  Memory
74683 ** for this node and for the pToken argument is a single allocation
74684 ** obtained from sqlcipher3DbMalloc().  The calling function
74685 ** is responsible for making sure the node eventually gets freed.
74686 **
74687 ** If dequote is true, then the token (if it exists) is dequoted.
74688 ** If dequote is false, no dequoting is performance.  The deQuote
74689 ** parameter is ignored if pToken is NULL or if the token does not
74690 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
74691 ** then the EP_DblQuoted flag is set on the expression node.
74692 **
74693 ** Special case:  If op==TK_INTEGER and pToken points to a string that
74694 ** can be translated into a 32-bit integer, then the token is not
74695 ** stored in u.zToken.  Instead, the integer values is written
74696 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
74697 ** is allocated to hold the integer text and the dequote flag is ignored.
74698 */
74699 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprAlloc(
74700   sqlcipher3 *db,            /* Handle for sqlcipher3DbMallocZero() (may be null) */
74701   int op,                 /* Expression opcode */
74702   const Token *pToken,    /* Token argument.  Might be NULL */
74703   int dequote             /* True to dequote */
74704 ){
74705   Expr *pNew;
74706   int nExtra = 0;
74707   int iValue = 0;
74708
74709   if( pToken ){
74710     if( op!=TK_INTEGER || pToken->z==0
74711           || sqlcipher3GetInt32(pToken->z, &iValue)==0 ){
74712       nExtra = pToken->n+1;
74713       assert( iValue>=0 );
74714     }
74715   }
74716   pNew = sqlcipher3DbMallocZero(db, sizeof(Expr)+nExtra);
74717   if( pNew ){
74718     pNew->op = (u8)op;
74719     pNew->iAgg = -1;
74720     if( pToken ){
74721       if( nExtra==0 ){
74722         pNew->flags |= EP_IntValue;
74723         pNew->u.iValue = iValue;
74724       }else{
74725         int c;
74726         pNew->u.zToken = (char*)&pNew[1];
74727         assert( pToken->z!=0 || pToken->n==0 );
74728         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
74729         pNew->u.zToken[pToken->n] = 0;
74730         if( dequote && nExtra>=3 
74731              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
74732           sqlcipher3Dequote(pNew->u.zToken);
74733           if( c=='"' ) pNew->flags |= EP_DblQuoted;
74734         }
74735       }
74736     }
74737 #if SQLCIPHER_MAX_EXPR_DEPTH>0
74738     pNew->nHeight = 1;
74739 #endif  
74740   }
74741   return pNew;
74742 }
74743
74744 /*
74745 ** Allocate a new expression node from a zero-terminated token that has
74746 ** already been dequoted.
74747 */
74748 SQLCIPHER_PRIVATE Expr *sqlcipher3Expr(
74749   sqlcipher3 *db,            /* Handle for sqlcipher3DbMallocZero() (may be null) */
74750   int op,                 /* Expression opcode */
74751   const char *zToken      /* Token argument.  Might be NULL */
74752 ){
74753   Token x;
74754   x.z = zToken;
74755   x.n = zToken ? sqlcipher3Strlen30(zToken) : 0;
74756   return sqlcipher3ExprAlloc(db, op, &x, 0);
74757 }
74758
74759 /*
74760 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
74761 **
74762 ** If pRoot==NULL that means that a memory allocation error has occurred.
74763 ** In that case, delete the subtrees pLeft and pRight.
74764 */
74765 SQLCIPHER_PRIVATE void sqlcipher3ExprAttachSubtrees(
74766   sqlcipher3 *db,
74767   Expr *pRoot,
74768   Expr *pLeft,
74769   Expr *pRight
74770 ){
74771   if( pRoot==0 ){
74772     assert( db->mallocFailed );
74773     sqlcipher3ExprDelete(db, pLeft);
74774     sqlcipher3ExprDelete(db, pRight);
74775   }else{
74776     if( pRight ){
74777       pRoot->pRight = pRight;
74778       if( pRight->flags & EP_ExpCollate ){
74779         pRoot->flags |= EP_ExpCollate;
74780         pRoot->pColl = pRight->pColl;
74781       }
74782     }
74783     if( pLeft ){
74784       pRoot->pLeft = pLeft;
74785       if( pLeft->flags & EP_ExpCollate ){
74786         pRoot->flags |= EP_ExpCollate;
74787         pRoot->pColl = pLeft->pColl;
74788       }
74789     }
74790     exprSetHeight(pRoot);
74791   }
74792 }
74793
74794 /*
74795 ** Allocate a Expr node which joins as many as two subtrees.
74796 **
74797 ** One or both of the subtrees can be NULL.  Return a pointer to the new
74798 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
74799 ** free the subtrees and return NULL.
74800 */
74801 SQLCIPHER_PRIVATE Expr *sqlcipher3PExpr(
74802   Parse *pParse,          /* Parsing context */
74803   int op,                 /* Expression opcode */
74804   Expr *pLeft,            /* Left operand */
74805   Expr *pRight,           /* Right operand */
74806   const Token *pToken     /* Argument token */
74807 ){
74808   Expr *p = sqlcipher3ExprAlloc(pParse->db, op, pToken, 1);
74809   sqlcipher3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
74810   if( p ) {
74811     sqlcipher3ExprCheckHeight(pParse, p->nHeight);
74812   }
74813   return p;
74814 }
74815
74816 /*
74817 ** Join two expressions using an AND operator.  If either expression is
74818 ** NULL, then just return the other expression.
74819 */
74820 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprAnd(sqlcipher3 *db, Expr *pLeft, Expr *pRight){
74821   if( pLeft==0 ){
74822     return pRight;
74823   }else if( pRight==0 ){
74824     return pLeft;
74825   }else{
74826     Expr *pNew = sqlcipher3ExprAlloc(db, TK_AND, 0, 0);
74827     sqlcipher3ExprAttachSubtrees(db, pNew, pLeft, pRight);
74828     return pNew;
74829   }
74830 }
74831
74832 /*
74833 ** Construct a new expression node for a function with multiple
74834 ** arguments.
74835 */
74836 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
74837   Expr *pNew;
74838   sqlcipher3 *db = pParse->db;
74839   assert( pToken );
74840   pNew = sqlcipher3ExprAlloc(db, TK_FUNCTION, pToken, 1);
74841   if( pNew==0 ){
74842     sqlcipher3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
74843     return 0;
74844   }
74845   pNew->x.pList = pList;
74846   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
74847   sqlcipher3ExprSetHeight(pParse, pNew);
74848   return pNew;
74849 }
74850
74851 /*
74852 ** Assign a variable number to an expression that encodes a wildcard
74853 ** in the original SQL statement.  
74854 **
74855 ** Wildcards consisting of a single "?" are assigned the next sequential
74856 ** variable number.
74857 **
74858 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
74859 ** sure "nnn" is not too be to avoid a denial of service attack when
74860 ** the SQL statement comes from an external source.
74861 **
74862 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
74863 ** as the previous instance of the same wildcard.  Or if this is the first
74864 ** instance of the wildcard, the next sequenial variable number is
74865 ** assigned.
74866 */
74867 SQLCIPHER_PRIVATE void sqlcipher3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
74868   sqlcipher3 *db = pParse->db;
74869   const char *z;
74870
74871   if( pExpr==0 ) return;
74872   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
74873   z = pExpr->u.zToken;
74874   assert( z!=0 );
74875   assert( z[0]!=0 );
74876   if( z[1]==0 ){
74877     /* Wildcard of the form "?".  Assign the next variable number */
74878     assert( z[0]=='?' );
74879     pExpr->iColumn = (ynVar)(++pParse->nVar);
74880   }else{
74881     ynVar x = 0;
74882     u32 n = sqlcipher3Strlen30(z);
74883     if( z[0]=='?' ){
74884       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
74885       ** use it as the variable number */
74886       i64 i;
74887       int bOk = 0==sqlcipher3Atoi64(&z[1], &i, n-1, SQLCIPHER_UTF8);
74888       pExpr->iColumn = x = (ynVar)i;
74889       testcase( i==0 );
74890       testcase( i==1 );
74891       testcase( i==db->aLimit[SQLCIPHER_LIMIT_VARIABLE_NUMBER]-1 );
74892       testcase( i==db->aLimit[SQLCIPHER_LIMIT_VARIABLE_NUMBER] );
74893       if( bOk==0 || i<1 || i>db->aLimit[SQLCIPHER_LIMIT_VARIABLE_NUMBER] ){
74894         sqlcipher3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
74895             db->aLimit[SQLCIPHER_LIMIT_VARIABLE_NUMBER]);
74896         x = 0;
74897       }
74898       if( i>pParse->nVar ){
74899         pParse->nVar = (int)i;
74900       }
74901     }else{
74902       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
74903       ** number as the prior appearance of the same name, or if the name
74904       ** has never appeared before, reuse the same variable number
74905       */
74906       ynVar i;
74907       for(i=0; i<pParse->nzVar; i++){
74908         if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
74909           pExpr->iColumn = x = (ynVar)i+1;
74910           break;
74911         }
74912       }
74913       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
74914     }
74915     if( x>0 ){
74916       if( x>pParse->nzVar ){
74917         char **a;
74918         a = sqlcipher3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
74919         if( a==0 ) return;  /* Error reported through db->mallocFailed */
74920         pParse->azVar = a;
74921         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
74922         pParse->nzVar = x;
74923       }
74924       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
74925         sqlcipher3DbFree(db, pParse->azVar[x-1]);
74926         pParse->azVar[x-1] = sqlcipher3DbStrNDup(db, z, n);
74927       }
74928     }
74929   } 
74930   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLCIPHER_LIMIT_VARIABLE_NUMBER] ){
74931     sqlcipher3ErrorMsg(pParse, "too many SQL variables");
74932   }
74933 }
74934
74935 /*
74936 ** Recursively delete an expression tree.
74937 */
74938 SQLCIPHER_PRIVATE void sqlcipher3ExprDelete(sqlcipher3 *db, Expr *p){
74939   if( p==0 ) return;
74940   /* Sanity check: Assert that the IntValue is non-negative if it exists */
74941   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
74942   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
74943     sqlcipher3ExprDelete(db, p->pLeft);
74944     sqlcipher3ExprDelete(db, p->pRight);
74945     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
74946       sqlcipher3DbFree(db, p->u.zToken);
74947     }
74948     if( ExprHasProperty(p, EP_xIsSelect) ){
74949       sqlcipher3SelectDelete(db, p->x.pSelect);
74950     }else{
74951       sqlcipher3ExprListDelete(db, p->x.pList);
74952     }
74953   }
74954   if( !ExprHasProperty(p, EP_Static) ){
74955     sqlcipher3DbFree(db, p);
74956   }
74957 }
74958
74959 /*
74960 ** Return the number of bytes allocated for the expression structure 
74961 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
74962 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
74963 */
74964 static int exprStructSize(Expr *p){
74965   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
74966   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
74967   return EXPR_FULLSIZE;
74968 }
74969
74970 /*
74971 ** The dupedExpr*Size() routines each return the number of bytes required
74972 ** to store a copy of an expression or expression tree.  They differ in
74973 ** how much of the tree is measured.
74974 **
74975 **     dupedExprStructSize()     Size of only the Expr structure 
74976 **     dupedExprNodeSize()       Size of Expr + space for token
74977 **     dupedExprSize()           Expr + token + subtree components
74978 **
74979 ***************************************************************************
74980 **
74981 ** The dupedExprStructSize() function returns two values OR-ed together:  
74982 ** (1) the space required for a copy of the Expr structure only and 
74983 ** (2) the EP_xxx flags that indicate what the structure size should be.
74984 ** The return values is always one of:
74985 **
74986 **      EXPR_FULLSIZE
74987 **      EXPR_REDUCEDSIZE   | EP_Reduced
74988 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
74989 **
74990 ** The size of the structure can be found by masking the return value
74991 ** of this routine with 0xfff.  The flags can be found by masking the
74992 ** return value with EP_Reduced|EP_TokenOnly.
74993 **
74994 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
74995 ** (unreduced) Expr objects as they or originally constructed by the parser.
74996 ** During expression analysis, extra information is computed and moved into
74997 ** later parts of teh Expr object and that extra information might get chopped
74998 ** off if the expression is reduced.  Note also that it does not work to
74999 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
75000 ** to reduce a pristine expression tree from the parser.  The implementation
75001 ** of dupedExprStructSize() contain multiple assert() statements that attempt
75002 ** to enforce this constraint.
75003 */
75004 static int dupedExprStructSize(Expr *p, int flags){
75005   int nSize;
75006   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
75007   if( 0==(flags&EXPRDUP_REDUCE) ){
75008     nSize = EXPR_FULLSIZE;
75009   }else{
75010     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
75011     assert( !ExprHasProperty(p, EP_FromJoin) ); 
75012     assert( (p->flags2 & EP2_MallocedToken)==0 );
75013     assert( (p->flags2 & EP2_Irreducible)==0 );
75014     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
75015       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
75016     }else{
75017       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
75018     }
75019   }
75020   return nSize;
75021 }
75022
75023 /*
75024 ** This function returns the space in bytes required to store the copy 
75025 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
75026 ** string is defined.)
75027 */
75028 static int dupedExprNodeSize(Expr *p, int flags){
75029   int nByte = dupedExprStructSize(p, flags) & 0xfff;
75030   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
75031     nByte += sqlcipher3Strlen30(p->u.zToken)+1;
75032   }
75033   return ROUND8(nByte);
75034 }
75035
75036 /*
75037 ** Return the number of bytes required to create a duplicate of the 
75038 ** expression passed as the first argument. The second argument is a
75039 ** mask containing EXPRDUP_XXX flags.
75040 **
75041 ** The value returned includes space to create a copy of the Expr struct
75042 ** itself and the buffer referred to by Expr.u.zToken, if any.
75043 **
75044 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
75045 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
75046 ** and Expr.pRight variables (but not for any structures pointed to or 
75047 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
75048 */
75049 static int dupedExprSize(Expr *p, int flags){
75050   int nByte = 0;
75051   if( p ){
75052     nByte = dupedExprNodeSize(p, flags);
75053     if( flags&EXPRDUP_REDUCE ){
75054       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
75055     }
75056   }
75057   return nByte;
75058 }
75059
75060 /*
75061 ** This function is similar to sqlcipher3ExprDup(), except that if pzBuffer 
75062 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
75063 ** to store the copy of expression p, the copies of p->u.zToken
75064 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
75065 ** if any. Before returning, *pzBuffer is set to the first byte passed the
75066 ** portion of the buffer copied into by this function.
75067 */
75068 static Expr *exprDup(sqlcipher3 *db, Expr *p, int flags, u8 **pzBuffer){
75069   Expr *pNew = 0;                      /* Value to return */
75070   if( p ){
75071     const int isReduced = (flags&EXPRDUP_REDUCE);
75072     u8 *zAlloc;
75073     u32 staticFlag = 0;
75074
75075     assert( pzBuffer==0 || isReduced );
75076
75077     /* Figure out where to write the new Expr structure. */
75078     if( pzBuffer ){
75079       zAlloc = *pzBuffer;
75080       staticFlag = EP_Static;
75081     }else{
75082       zAlloc = sqlcipher3DbMallocRaw(db, dupedExprSize(p, flags));
75083     }
75084     pNew = (Expr *)zAlloc;
75085
75086     if( pNew ){
75087       /* Set nNewSize to the size allocated for the structure pointed to
75088       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
75089       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
75090       ** by the copy of the p->u.zToken string (if any).
75091       */
75092       const unsigned nStructSize = dupedExprStructSize(p, flags);
75093       const int nNewSize = nStructSize & 0xfff;
75094       int nToken;
75095       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
75096         nToken = sqlcipher3Strlen30(p->u.zToken) + 1;
75097       }else{
75098         nToken = 0;
75099       }
75100       if( isReduced ){
75101         assert( ExprHasProperty(p, EP_Reduced)==0 );
75102         memcpy(zAlloc, p, nNewSize);
75103       }else{
75104         int nSize = exprStructSize(p);
75105         memcpy(zAlloc, p, nSize);
75106         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
75107       }
75108
75109       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
75110       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
75111       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
75112       pNew->flags |= staticFlag;
75113
75114       /* Copy the p->u.zToken string, if any. */
75115       if( nToken ){
75116         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
75117         memcpy(zToken, p->u.zToken, nToken);
75118       }
75119
75120       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
75121         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
75122         if( ExprHasProperty(p, EP_xIsSelect) ){
75123           pNew->x.pSelect = sqlcipher3SelectDup(db, p->x.pSelect, isReduced);
75124         }else{
75125           pNew->x.pList = sqlcipher3ExprListDup(db, p->x.pList, isReduced);
75126         }
75127       }
75128
75129       /* Fill in pNew->pLeft and pNew->pRight. */
75130       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
75131         zAlloc += dupedExprNodeSize(p, flags);
75132         if( ExprHasProperty(pNew, EP_Reduced) ){
75133           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
75134           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
75135         }
75136         if( pzBuffer ){
75137           *pzBuffer = zAlloc;
75138         }
75139       }else{
75140         pNew->flags2 = 0;
75141         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
75142           pNew->pLeft = sqlcipher3ExprDup(db, p->pLeft, 0);
75143           pNew->pRight = sqlcipher3ExprDup(db, p->pRight, 0);
75144         }
75145       }
75146
75147     }
75148   }
75149   return pNew;
75150 }
75151
75152 /*
75153 ** The following group of routines make deep copies of expressions,
75154 ** expression lists, ID lists, and select statements.  The copies can
75155 ** be deleted (by being passed to their respective ...Delete() routines)
75156 ** without effecting the originals.
75157 **
75158 ** The expression list, ID, and source lists return by sqlcipher3ExprListDup(),
75159 ** sqlcipher3IdListDup(), and sqlcipher3SrcListDup() can not be further expanded 
75160 ** by subsequent calls to sqlcipher*ListAppend() routines.
75161 **
75162 ** Any tables that the SrcList might point to are not duplicated.
75163 **
75164 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
75165 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
75166 ** truncated version of the usual Expr structure that will be stored as
75167 ** part of the in-memory representation of the database schema.
75168 */
75169 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprDup(sqlcipher3 *db, Expr *p, int flags){
75170   return exprDup(db, p, flags, 0);
75171 }
75172 SQLCIPHER_PRIVATE ExprList *sqlcipher3ExprListDup(sqlcipher3 *db, ExprList *p, int flags){
75173   ExprList *pNew;
75174   struct ExprList_item *pItem, *pOldItem;
75175   int i;
75176   if( p==0 ) return 0;
75177   pNew = sqlcipher3DbMallocRaw(db, sizeof(*pNew) );
75178   if( pNew==0 ) return 0;
75179   pNew->iECursor = 0;
75180   pNew->nExpr = pNew->nAlloc = p->nExpr;
75181   pNew->a = pItem = sqlcipher3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
75182   if( pItem==0 ){
75183     sqlcipher3DbFree(db, pNew);
75184     return 0;
75185   } 
75186   pOldItem = p->a;
75187   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
75188     Expr *pOldExpr = pOldItem->pExpr;
75189     pItem->pExpr = sqlcipher3ExprDup(db, pOldExpr, flags);
75190     pItem->zName = sqlcipher3DbStrDup(db, pOldItem->zName);
75191     pItem->zSpan = sqlcipher3DbStrDup(db, pOldItem->zSpan);
75192     pItem->sortOrder = pOldItem->sortOrder;
75193     pItem->done = 0;
75194     pItem->iCol = pOldItem->iCol;
75195     pItem->iAlias = pOldItem->iAlias;
75196   }
75197   return pNew;
75198 }
75199
75200 /*
75201 ** If cursors, triggers, views and subqueries are all omitted from
75202 ** the build, then none of the following routines, except for 
75203 ** sqlcipher3SelectDup(), can be called. sqlcipher3SelectDup() is sometimes
75204 ** called with a NULL argument.
75205 */
75206 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_TRIGGER) \
75207  || !defined(SQLCIPHER_OMIT_SUBQUERY)
75208 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListDup(sqlcipher3 *db, SrcList *p, int flags){
75209   SrcList *pNew;
75210   int i;
75211   int nByte;
75212   if( p==0 ) return 0;
75213   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
75214   pNew = sqlcipher3DbMallocRaw(db, nByte );
75215   if( pNew==0 ) return 0;
75216   pNew->nSrc = pNew->nAlloc = p->nSrc;
75217   for(i=0; i<p->nSrc; i++){
75218     struct SrcList_item *pNewItem = &pNew->a[i];
75219     struct SrcList_item *pOldItem = &p->a[i];
75220     Table *pTab;
75221     pNewItem->zDatabase = sqlcipher3DbStrDup(db, pOldItem->zDatabase);
75222     pNewItem->zName = sqlcipher3DbStrDup(db, pOldItem->zName);
75223     pNewItem->zAlias = sqlcipher3DbStrDup(db, pOldItem->zAlias);
75224     pNewItem->jointype = pOldItem->jointype;
75225     pNewItem->iCursor = pOldItem->iCursor;
75226     pNewItem->addrFillSub = pOldItem->addrFillSub;
75227     pNewItem->regReturn = pOldItem->regReturn;
75228     pNewItem->isCorrelated = pOldItem->isCorrelated;
75229     pNewItem->zIndex = sqlcipher3DbStrDup(db, pOldItem->zIndex);
75230     pNewItem->notIndexed = pOldItem->notIndexed;
75231     pNewItem->pIndex = pOldItem->pIndex;
75232     pTab = pNewItem->pTab = pOldItem->pTab;
75233     if( pTab ){
75234       pTab->nRef++;
75235     }
75236     pNewItem->pSelect = sqlcipher3SelectDup(db, pOldItem->pSelect, flags);
75237     pNewItem->pOn = sqlcipher3ExprDup(db, pOldItem->pOn, flags);
75238     pNewItem->pUsing = sqlcipher3IdListDup(db, pOldItem->pUsing);
75239     pNewItem->colUsed = pOldItem->colUsed;
75240   }
75241   return pNew;
75242 }
75243 SQLCIPHER_PRIVATE IdList *sqlcipher3IdListDup(sqlcipher3 *db, IdList *p){
75244   IdList *pNew;
75245   int i;
75246   if( p==0 ) return 0;
75247   pNew = sqlcipher3DbMallocRaw(db, sizeof(*pNew) );
75248   if( pNew==0 ) return 0;
75249   pNew->nId = pNew->nAlloc = p->nId;
75250   pNew->a = sqlcipher3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
75251   if( pNew->a==0 ){
75252     sqlcipher3DbFree(db, pNew);
75253     return 0;
75254   }
75255   for(i=0; i<p->nId; i++){
75256     struct IdList_item *pNewItem = &pNew->a[i];
75257     struct IdList_item *pOldItem = &p->a[i];
75258     pNewItem->zName = sqlcipher3DbStrDup(db, pOldItem->zName);
75259     pNewItem->idx = pOldItem->idx;
75260   }
75261   return pNew;
75262 }
75263 SQLCIPHER_PRIVATE Select *sqlcipher3SelectDup(sqlcipher3 *db, Select *p, int flags){
75264   Select *pNew;
75265   if( p==0 ) return 0;
75266   pNew = sqlcipher3DbMallocRaw(db, sizeof(*p) );
75267   if( pNew==0 ) return 0;
75268   pNew->pEList = sqlcipher3ExprListDup(db, p->pEList, flags);
75269   pNew->pSrc = sqlcipher3SrcListDup(db, p->pSrc, flags);
75270   pNew->pWhere = sqlcipher3ExprDup(db, p->pWhere, flags);
75271   pNew->pGroupBy = sqlcipher3ExprListDup(db, p->pGroupBy, flags);
75272   pNew->pHaving = sqlcipher3ExprDup(db, p->pHaving, flags);
75273   pNew->pOrderBy = sqlcipher3ExprListDup(db, p->pOrderBy, flags);
75274   pNew->op = p->op;
75275   pNew->pPrior = sqlcipher3SelectDup(db, p->pPrior, flags);
75276   pNew->pLimit = sqlcipher3ExprDup(db, p->pLimit, flags);
75277   pNew->pOffset = sqlcipher3ExprDup(db, p->pOffset, flags);
75278   pNew->iLimit = 0;
75279   pNew->iOffset = 0;
75280   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
75281   pNew->pRightmost = 0;
75282   pNew->addrOpenEphm[0] = -1;
75283   pNew->addrOpenEphm[1] = -1;
75284   pNew->addrOpenEphm[2] = -1;
75285   return pNew;
75286 }
75287 #else
75288 SQLCIPHER_PRIVATE Select *sqlcipher3SelectDup(sqlcipher3 *db, Select *p, int flags){
75289   assert( p==0 );
75290   return 0;
75291 }
75292 #endif
75293
75294
75295 /*
75296 ** Add a new element to the end of an expression list.  If pList is
75297 ** initially NULL, then create a new expression list.
75298 **
75299 ** If a memory allocation error occurs, the entire list is freed and
75300 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
75301 ** that the new entry was successfully appended.
75302 */
75303 SQLCIPHER_PRIVATE ExprList *sqlcipher3ExprListAppend(
75304   Parse *pParse,          /* Parsing context */
75305   ExprList *pList,        /* List to which to append. Might be NULL */
75306   Expr *pExpr             /* Expression to be appended. Might be NULL */
75307 ){
75308   sqlcipher3 *db = pParse->db;
75309   if( pList==0 ){
75310     pList = sqlcipher3DbMallocZero(db, sizeof(ExprList) );
75311     if( pList==0 ){
75312       goto no_mem;
75313     }
75314     assert( pList->nAlloc==0 );
75315   }
75316   if( pList->nAlloc<=pList->nExpr ){
75317     struct ExprList_item *a;
75318     int n = pList->nAlloc*2 + 4;
75319     a = sqlcipher3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
75320     if( a==0 ){
75321       goto no_mem;
75322     }
75323     pList->a = a;
75324     pList->nAlloc = sqlcipher3DbMallocSize(db, a)/sizeof(a[0]);
75325   }
75326   assert( pList->a!=0 );
75327   if( 1 ){
75328     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
75329     memset(pItem, 0, sizeof(*pItem));
75330     pItem->pExpr = pExpr;
75331   }
75332   return pList;
75333
75334 no_mem:     
75335   /* Avoid leaking memory if malloc has failed. */
75336   sqlcipher3ExprDelete(db, pExpr);
75337   sqlcipher3ExprListDelete(db, pList);
75338   return 0;
75339 }
75340
75341 /*
75342 ** Set the ExprList.a[].zName element of the most recently added item
75343 ** on the expression list.
75344 **
75345 ** pList might be NULL following an OOM error.  But pName should never be
75346 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
75347 ** is set.
75348 */
75349 SQLCIPHER_PRIVATE void sqlcipher3ExprListSetName(
75350   Parse *pParse,          /* Parsing context */
75351   ExprList *pList,        /* List to which to add the span. */
75352   Token *pName,           /* Name to be added */
75353   int dequote             /* True to cause the name to be dequoted */
75354 ){
75355   assert( pList!=0 || pParse->db->mallocFailed!=0 );
75356   if( pList ){
75357     struct ExprList_item *pItem;
75358     assert( pList->nExpr>0 );
75359     pItem = &pList->a[pList->nExpr-1];
75360     assert( pItem->zName==0 );
75361     pItem->zName = sqlcipher3DbStrNDup(pParse->db, pName->z, pName->n);
75362     if( dequote && pItem->zName ) sqlcipher3Dequote(pItem->zName);
75363   }
75364 }
75365
75366 /*
75367 ** Set the ExprList.a[].zSpan element of the most recently added item
75368 ** on the expression list.
75369 **
75370 ** pList might be NULL following an OOM error.  But pSpan should never be
75371 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
75372 ** is set.
75373 */
75374 SQLCIPHER_PRIVATE void sqlcipher3ExprListSetSpan(
75375   Parse *pParse,          /* Parsing context */
75376   ExprList *pList,        /* List to which to add the span. */
75377   ExprSpan *pSpan         /* The span to be added */
75378 ){
75379   sqlcipher3 *db = pParse->db;
75380   assert( pList!=0 || db->mallocFailed!=0 );
75381   if( pList ){
75382     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
75383     assert( pList->nExpr>0 );
75384     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
75385     sqlcipher3DbFree(db, pItem->zSpan);
75386     pItem->zSpan = sqlcipher3DbStrNDup(db, (char*)pSpan->zStart,
75387                                     (int)(pSpan->zEnd - pSpan->zStart));
75388   }
75389 }
75390
75391 /*
75392 ** If the expression list pEList contains more than iLimit elements,
75393 ** leave an error message in pParse.
75394 */
75395 SQLCIPHER_PRIVATE void sqlcipher3ExprListCheckLength(
75396   Parse *pParse,
75397   ExprList *pEList,
75398   const char *zObject
75399 ){
75400   int mx = pParse->db->aLimit[SQLCIPHER_LIMIT_COLUMN];
75401   testcase( pEList && pEList->nExpr==mx );
75402   testcase( pEList && pEList->nExpr==mx+1 );
75403   if( pEList && pEList->nExpr>mx ){
75404     sqlcipher3ErrorMsg(pParse, "too many columns in %s", zObject);
75405   }
75406 }
75407
75408 /*
75409 ** Delete an entire expression list.
75410 */
75411 SQLCIPHER_PRIVATE void sqlcipher3ExprListDelete(sqlcipher3 *db, ExprList *pList){
75412   int i;
75413   struct ExprList_item *pItem;
75414   if( pList==0 ) return;
75415   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
75416   assert( pList->nExpr<=pList->nAlloc );
75417   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
75418     sqlcipher3ExprDelete(db, pItem->pExpr);
75419     sqlcipher3DbFree(db, pItem->zName);
75420     sqlcipher3DbFree(db, pItem->zSpan);
75421   }
75422   sqlcipher3DbFree(db, pList->a);
75423   sqlcipher3DbFree(db, pList);
75424 }
75425
75426 /*
75427 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
75428 ** to an integer.  These routines are checking an expression to see
75429 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
75430 ** not constant.
75431 **
75432 ** These callback routines are used to implement the following:
75433 **
75434 **     sqlcipher3ExprIsConstant()
75435 **     sqlcipher3ExprIsConstantNotJoin()
75436 **     sqlcipher3ExprIsConstantOrFunction()
75437 **
75438 */
75439 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
75440
75441   /* If pWalker->u.i is 3 then any term of the expression that comes from
75442   ** the ON or USING clauses of a join disqualifies the expression
75443   ** from being considered constant. */
75444   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
75445     pWalker->u.i = 0;
75446     return WRC_Abort;
75447   }
75448
75449   switch( pExpr->op ){
75450     /* Consider functions to be constant if all their arguments are constant
75451     ** and pWalker->u.i==2 */
75452     case TK_FUNCTION:
75453       if( pWalker->u.i==2 ) return 0;
75454       /* Fall through */
75455     case TK_ID:
75456     case TK_COLUMN:
75457     case TK_AGG_FUNCTION:
75458     case TK_AGG_COLUMN:
75459       testcase( pExpr->op==TK_ID );
75460       testcase( pExpr->op==TK_COLUMN );
75461       testcase( pExpr->op==TK_AGG_FUNCTION );
75462       testcase( pExpr->op==TK_AGG_COLUMN );
75463       pWalker->u.i = 0;
75464       return WRC_Abort;
75465     default:
75466       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
75467       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
75468       return WRC_Continue;
75469   }
75470 }
75471 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
75472   UNUSED_PARAMETER(NotUsed);
75473   pWalker->u.i = 0;
75474   return WRC_Abort;
75475 }
75476 static int exprIsConst(Expr *p, int initFlag){
75477   Walker w;
75478   w.u.i = initFlag;
75479   w.xExprCallback = exprNodeIsConstant;
75480   w.xSelectCallback = selectNodeIsConstant;
75481   sqlcipher3WalkExpr(&w, p);
75482   return w.u.i;
75483 }
75484
75485 /*
75486 ** Walk an expression tree.  Return 1 if the expression is constant
75487 ** and 0 if it involves variables or function calls.
75488 **
75489 ** For the purposes of this function, a double-quoted string (ex: "abc")
75490 ** is considered a variable but a single-quoted string (ex: 'abc') is
75491 ** a constant.
75492 */
75493 SQLCIPHER_PRIVATE int sqlcipher3ExprIsConstant(Expr *p){
75494   return exprIsConst(p, 1);
75495 }
75496
75497 /*
75498 ** Walk an expression tree.  Return 1 if the expression is constant
75499 ** that does no originate from the ON or USING clauses of a join.
75500 ** Return 0 if it involves variables or function calls or terms from
75501 ** an ON or USING clause.
75502 */
75503 SQLCIPHER_PRIVATE int sqlcipher3ExprIsConstantNotJoin(Expr *p){
75504   return exprIsConst(p, 3);
75505 }
75506
75507 /*
75508 ** Walk an expression tree.  Return 1 if the expression is constant
75509 ** or a function call with constant arguments.  Return and 0 if there
75510 ** are any variables.
75511 **
75512 ** For the purposes of this function, a double-quoted string (ex: "abc")
75513 ** is considered a variable but a single-quoted string (ex: 'abc') is
75514 ** a constant.
75515 */
75516 SQLCIPHER_PRIVATE int sqlcipher3ExprIsConstantOrFunction(Expr *p){
75517   return exprIsConst(p, 2);
75518 }
75519
75520 /*
75521 ** If the expression p codes a constant integer that is small enough
75522 ** to fit in a 32-bit integer, return 1 and put the value of the integer
75523 ** in *pValue.  If the expression is not an integer or if it is too big
75524 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
75525 */
75526 SQLCIPHER_PRIVATE int sqlcipher3ExprIsInteger(Expr *p, int *pValue){
75527   int rc = 0;
75528
75529   /* If an expression is an integer literal that fits in a signed 32-bit
75530   ** integer, then the EP_IntValue flag will have already been set */
75531   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
75532            || sqlcipher3GetInt32(p->u.zToken, &rc)==0 );
75533
75534   if( p->flags & EP_IntValue ){
75535     *pValue = p->u.iValue;
75536     return 1;
75537   }
75538   switch( p->op ){
75539     case TK_UPLUS: {
75540       rc = sqlcipher3ExprIsInteger(p->pLeft, pValue);
75541       break;
75542     }
75543     case TK_UMINUS: {
75544       int v;
75545       if( sqlcipher3ExprIsInteger(p->pLeft, &v) ){
75546         *pValue = -v;
75547         rc = 1;
75548       }
75549       break;
75550     }
75551     default: break;
75552   }
75553   return rc;
75554 }
75555
75556 /*
75557 ** Return FALSE if there is no chance that the expression can be NULL.
75558 **
75559 ** If the expression might be NULL or if the expression is too complex
75560 ** to tell return TRUE.  
75561 **
75562 ** This routine is used as an optimization, to skip OP_IsNull opcodes
75563 ** when we know that a value cannot be NULL.  Hence, a false positive
75564 ** (returning TRUE when in fact the expression can never be NULL) might
75565 ** be a small performance hit but is otherwise harmless.  On the other
75566 ** hand, a false negative (returning FALSE when the result could be NULL)
75567 ** will likely result in an incorrect answer.  So when in doubt, return
75568 ** TRUE.
75569 */
75570 SQLCIPHER_PRIVATE int sqlcipher3ExprCanBeNull(const Expr *p){
75571   u8 op;
75572   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75573   op = p->op;
75574   if( op==TK_REGISTER ) op = p->op2;
75575   switch( op ){
75576     case TK_INTEGER:
75577     case TK_STRING:
75578     case TK_FLOAT:
75579     case TK_BLOB:
75580       return 0;
75581     default:
75582       return 1;
75583   }
75584 }
75585
75586 /*
75587 ** Generate an OP_IsNull instruction that tests register iReg and jumps
75588 ** to location iDest if the value in iReg is NULL.  The value in iReg 
75589 ** was computed by pExpr.  If we can look at pExpr at compile-time and
75590 ** determine that it can never generate a NULL, then the OP_IsNull operation
75591 ** can be omitted.
75592 */
75593 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeIsNullJump(
75594   Vdbe *v,            /* The VDBE under construction */
75595   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
75596   int iReg,           /* Test the value in this register for NULL */
75597   int iDest           /* Jump here if the value is null */
75598 ){
75599   if( sqlcipher3ExprCanBeNull(pExpr) ){
75600     sqlcipher3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
75601   }
75602 }
75603
75604 /*
75605 ** Return TRUE if the given expression is a constant which would be
75606 ** unchanged by OP_Affinity with the affinity given in the second
75607 ** argument.
75608 **
75609 ** This routine is used to determine if the OP_Affinity operation
75610 ** can be omitted.  When in doubt return FALSE.  A false negative
75611 ** is harmless.  A false positive, however, can result in the wrong
75612 ** answer.
75613 */
75614 SQLCIPHER_PRIVATE int sqlcipher3ExprNeedsNoAffinityChange(const Expr *p, char aff){
75615   u8 op;
75616   if( aff==SQLCIPHER_AFF_NONE ) return 1;
75617   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75618   op = p->op;
75619   if( op==TK_REGISTER ) op = p->op2;
75620   switch( op ){
75621     case TK_INTEGER: {
75622       return aff==SQLCIPHER_AFF_INTEGER || aff==SQLCIPHER_AFF_NUMERIC;
75623     }
75624     case TK_FLOAT: {
75625       return aff==SQLCIPHER_AFF_REAL || aff==SQLCIPHER_AFF_NUMERIC;
75626     }
75627     case TK_STRING: {
75628       return aff==SQLCIPHER_AFF_TEXT;
75629     }
75630     case TK_BLOB: {
75631       return 1;
75632     }
75633     case TK_COLUMN: {
75634       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
75635       return p->iColumn<0
75636           && (aff==SQLCIPHER_AFF_INTEGER || aff==SQLCIPHER_AFF_NUMERIC);
75637     }
75638     default: {
75639       return 0;
75640     }
75641   }
75642 }
75643
75644 /*
75645 ** Return TRUE if the given string is a row-id column name.
75646 */
75647 SQLCIPHER_PRIVATE int sqlcipher3IsRowid(const char *z){
75648   if( sqlcipher3StrICmp(z, "_ROWID_")==0 ) return 1;
75649   if( sqlcipher3StrICmp(z, "ROWID")==0 ) return 1;
75650   if( sqlcipher3StrICmp(z, "OID")==0 ) return 1;
75651   return 0;
75652 }
75653
75654 /*
75655 ** Return true if we are able to the IN operator optimization on a
75656 ** query of the form
75657 **
75658 **       x IN (SELECT ...)
75659 **
75660 ** Where the SELECT... clause is as specified by the parameter to this
75661 ** routine.
75662 **
75663 ** The Select object passed in has already been preprocessed and no
75664 ** errors have been found.
75665 */
75666 #ifndef SQLCIPHER_OMIT_SUBQUERY
75667 static int isCandidateForInOpt(Select *p){
75668   SrcList *pSrc;
75669   ExprList *pEList;
75670   Table *pTab;
75671   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
75672   if( p->pPrior ) return 0;              /* Not a compound SELECT */
75673   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
75674     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
75675     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
75676     return 0; /* No DISTINCT keyword and no aggregate functions */
75677   }
75678   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
75679   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
75680   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
75681   if( p->pWhere ) return 0;              /* Has no WHERE clause */
75682   pSrc = p->pSrc;
75683   assert( pSrc!=0 );
75684   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
75685   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
75686   pTab = pSrc->a[0].pTab;
75687   if( NEVER(pTab==0) ) return 0;
75688   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
75689   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
75690   pEList = p->pEList;
75691   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
75692   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
75693   return 1;
75694 }
75695 #endif /* SQLCIPHER_OMIT_SUBQUERY */
75696
75697 /*
75698 ** This function is used by the implementation of the IN (...) operator.
75699 ** It's job is to find or create a b-tree structure that may be used
75700 ** either to test for membership of the (...) set or to iterate through
75701 ** its members, skipping duplicates.
75702 **
75703 ** The index of the cursor opened on the b-tree (database table, database index 
75704 ** or ephermal table) is stored in pX->iTable before this function returns.
75705 ** The returned value of this function indicates the b-tree type, as follows:
75706 **
75707 **   IN_INDEX_ROWID - The cursor was opened on a database table.
75708 **   IN_INDEX_INDEX - The cursor was opened on a database index.
75709 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
75710 **                    populated epheremal table.
75711 **
75712 ** An existing b-tree may only be used if the SELECT is of the simple
75713 ** form:
75714 **
75715 **     SELECT <column> FROM <table>
75716 **
75717 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
75718 ** through the set members, skipping any duplicates. In this case an
75719 ** epheremal table must be used unless the selected <column> is guaranteed
75720 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
75721 ** has a UNIQUE constraint or UNIQUE index.
75722 **
75723 ** If the prNotFound parameter is not 0, then the b-tree will be used 
75724 ** for fast set membership tests. In this case an epheremal table must 
75725 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
75726 ** be found with <column> as its left-most column.
75727 **
75728 ** When the b-tree is being used for membership tests, the calling function
75729 ** needs to know whether or not the structure contains an SQL NULL 
75730 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
75731 ** If there is any chance that the (...) might contain a NULL value at
75732 ** runtime, then a register is allocated and the register number written
75733 ** to *prNotFound. If there is no chance that the (...) contains a
75734 ** NULL value, then *prNotFound is left unchanged.
75735 **
75736 ** If a register is allocated and its location stored in *prNotFound, then
75737 ** its initial value is NULL.  If the (...) does not remain constant
75738 ** for the duration of the query (i.e. the SELECT within the (...)
75739 ** is a correlated subquery) then the value of the allocated register is
75740 ** reset to NULL each time the subquery is rerun. This allows the
75741 ** caller to use vdbe code equivalent to the following:
75742 **
75743 **   if( register==NULL ){
75744 **     has_null = <test if data structure contains null>
75745 **     register = 1
75746 **   }
75747 **
75748 ** in order to avoid running the <test if data structure contains null>
75749 ** test more often than is necessary.
75750 */
75751 #ifndef SQLCIPHER_OMIT_SUBQUERY
75752 SQLCIPHER_PRIVATE int sqlcipher3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
75753   Select *p;                            /* SELECT to the right of IN operator */
75754   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
75755   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
75756   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
75757
75758   assert( pX->op==TK_IN );
75759
75760   /* Check to see if an existing table or index can be used to
75761   ** satisfy the query.  This is preferable to generating a new 
75762   ** ephemeral table.
75763   */
75764   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
75765   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
75766     sqlcipher3 *db = pParse->db;              /* Database connection */
75767     Vdbe *v = sqlcipher3GetVdbe(pParse);      /* Virtual machine being coded */
75768     Table *pTab;                           /* Table <table>. */
75769     Expr *pExpr;                           /* Expression <column> */
75770     int iCol;                              /* Index of column <column> */
75771     int iDb;                               /* Database idx for pTab */
75772
75773     assert( p );                        /* Because of isCandidateForInOpt(p) */
75774     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
75775     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
75776     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
75777     pTab = p->pSrc->a[0].pTab;
75778     pExpr = p->pEList->a[0].pExpr;
75779     iCol = pExpr->iColumn;
75780    
75781     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
75782     iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
75783     sqlcipher3CodeVerifySchema(pParse, iDb);
75784     sqlcipher3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
75785
75786     /* This function is only called from two places. In both cases the vdbe
75787     ** has already been allocated. So assume sqlcipher3GetVdbe() is always
75788     ** successful here.
75789     */
75790     assert(v);
75791     if( iCol<0 ){
75792       int iMem = ++pParse->nMem;
75793       int iAddr;
75794
75795       iAddr = sqlcipher3VdbeAddOp1(v, OP_Once, iMem);
75796
75797       sqlcipher3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
75798       eType = IN_INDEX_ROWID;
75799
75800       sqlcipher3VdbeJumpHere(v, iAddr);
75801     }else{
75802       Index *pIdx;                         /* Iterator variable */
75803
75804       /* The collation sequence used by the comparison. If an index is to
75805       ** be used in place of a temp-table, it must be ordered according
75806       ** to this collation sequence.  */
75807       CollSeq *pReq = sqlcipher3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
75808
75809       /* Check that the affinity that will be used to perform the 
75810       ** comparison is the same as the affinity of the column. If
75811       ** it is not, it is not possible to use any index.
75812       */
75813       char aff = comparisonAffinity(pX);
75814       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLCIPHER_AFF_NONE);
75815
75816       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
75817         if( (pIdx->aiColumn[0]==iCol)
75818          && sqlcipher3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
75819          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
75820         ){
75821           int iMem = ++pParse->nMem;
75822           int iAddr;
75823           char *pKey;
75824   
75825           pKey = (char *)sqlcipher3IndexKeyinfo(pParse, pIdx);
75826           iAddr = sqlcipher3VdbeAddOp1(v, OP_Once, iMem);
75827   
75828           sqlcipher3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
75829                                pKey,P4_KEYINFO_HANDOFF);
75830           VdbeComment((v, "%s", pIdx->zName));
75831           eType = IN_INDEX_INDEX;
75832
75833           sqlcipher3VdbeJumpHere(v, iAddr);
75834           if( prNotFound && !pTab->aCol[iCol].notNull ){
75835             *prNotFound = ++pParse->nMem;
75836           }
75837         }
75838       }
75839     }
75840   }
75841
75842   if( eType==0 ){
75843     /* Could not found an existing table or index to use as the RHS b-tree.
75844     ** We will have to generate an ephemeral table to do the job.
75845     */
75846     double savedNQueryLoop = pParse->nQueryLoop;
75847     int rMayHaveNull = 0;
75848     eType = IN_INDEX_EPH;
75849     if( prNotFound ){
75850       *prNotFound = rMayHaveNull = ++pParse->nMem;
75851     }else{
75852       testcase( pParse->nQueryLoop>(double)1 );
75853       pParse->nQueryLoop = (double)1;
75854       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
75855         eType = IN_INDEX_ROWID;
75856       }
75857     }
75858     sqlcipher3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
75859     pParse->nQueryLoop = savedNQueryLoop;
75860   }else{
75861     pX->iTable = iTab;
75862   }
75863   return eType;
75864 }
75865 #endif
75866
75867 /*
75868 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
75869 ** or IN operators.  Examples:
75870 **
75871 **     (SELECT a FROM b)          -- subquery
75872 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
75873 **     x IN (4,5,11)              -- IN operator with list on right-hand side
75874 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
75875 **
75876 ** The pExpr parameter describes the expression that contains the IN
75877 ** operator or subquery.
75878 **
75879 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
75880 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
75881 ** to some integer key column of a table B-Tree. In this case, use an
75882 ** intkey B-Tree to store the set of IN(...) values instead of the usual
75883 ** (slower) variable length keys B-Tree.
75884 **
75885 ** If rMayHaveNull is non-zero, that means that the operation is an IN
75886 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
75887 ** Furthermore, the IN is in a WHERE clause and that we really want
75888 ** to iterate over the RHS of the IN operator in order to quickly locate
75889 ** all corresponding LHS elements.  All this routine does is initialize
75890 ** the register given by rMayHaveNull to NULL.  Calling routines will take
75891 ** care of changing this register value to non-NULL if the RHS is NULL-free.
75892 **
75893 ** If rMayHaveNull is zero, that means that the subquery is being used
75894 ** for membership testing only.  There is no need to initialize any
75895 ** registers to indicate the presense or absence of NULLs on the RHS.
75896 **
75897 ** For a SELECT or EXISTS operator, return the register that holds the
75898 ** result.  For IN operators or if an error occurs, the return value is 0.
75899 */
75900 #ifndef SQLCIPHER_OMIT_SUBQUERY
75901 SQLCIPHER_PRIVATE int sqlcipher3CodeSubselect(
75902   Parse *pParse,          /* Parsing context */
75903   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
75904   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
75905   int isRowid             /* If true, LHS of IN operator is a rowid */
75906 ){
75907   int testAddr = -1;                      /* One-time test address */
75908   int rReg = 0;                           /* Register storing resulting */
75909   Vdbe *v = sqlcipher3GetVdbe(pParse);
75910   if( NEVER(v==0) ) return 0;
75911   sqlcipher3ExprCachePush(pParse);
75912
75913   /* This code must be run in its entirety every time it is encountered
75914   ** if any of the following is true:
75915   **
75916   **    *  The right-hand side is a correlated subquery
75917   **    *  The right-hand side is an expression list containing variables
75918   **    *  We are inside a trigger
75919   **
75920   ** If all of the above are false, then we can run this code just once
75921   ** save the results, and reuse the same result on subsequent invocations.
75922   */
75923   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
75924     int mem = ++pParse->nMem;
75925     testAddr = sqlcipher3VdbeAddOp1(v, OP_Once, mem);
75926   }
75927
75928 #ifndef SQLCIPHER_OMIT_EXPLAIN
75929   if( pParse->explain==2 ){
75930     char *zMsg = sqlcipher3MPrintf(
75931         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
75932         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
75933     );
75934     sqlcipher3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
75935   }
75936 #endif
75937
75938   switch( pExpr->op ){
75939     case TK_IN: {
75940       char affinity;              /* Affinity of the LHS of the IN */
75941       KeyInfo keyInfo;            /* Keyinfo for the generated table */
75942       int addr;                   /* Address of OP_OpenEphemeral instruction */
75943       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
75944
75945       if( rMayHaveNull ){
75946         sqlcipher3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
75947       }
75948
75949       affinity = sqlcipher3ExprAffinity(pLeft);
75950
75951       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
75952       ** expression it is handled the same way.  An ephemeral table is 
75953       ** filled with single-field index keys representing the results
75954       ** from the SELECT or the <exprlist>.
75955       **
75956       ** If the 'x' expression is a column value, or the SELECT...
75957       ** statement returns a column value, then the affinity of that
75958       ** column is used to build the index keys. If both 'x' and the
75959       ** SELECT... statement are columns, then numeric affinity is used
75960       ** if either column has NUMERIC or INTEGER affinity. If neither
75961       ** 'x' nor the SELECT... statement are columns, then numeric affinity
75962       ** is used.
75963       */
75964       pExpr->iTable = pParse->nTab++;
75965       addr = sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
75966       if( rMayHaveNull==0 ) sqlcipher3VdbeChangeP5(v, BTREE_UNORDERED);
75967       memset(&keyInfo, 0, sizeof(keyInfo));
75968       keyInfo.nField = 1;
75969
75970       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
75971         /* Case 1:     expr IN (SELECT ...)
75972         **
75973         ** Generate code to write the results of the select into the temporary
75974         ** table allocated and opened above.
75975         */
75976         SelectDest dest;
75977         ExprList *pEList;
75978
75979         assert( !isRowid );
75980         sqlcipher3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
75981         dest.affinity = (u8)affinity;
75982         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
75983         pExpr->x.pSelect->iLimit = 0;
75984         if( sqlcipher3Select(pParse, pExpr->x.pSelect, &dest) ){
75985           return 0;
75986         }
75987         pEList = pExpr->x.pSelect->pEList;
75988         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
75989           keyInfo.aColl[0] = sqlcipher3BinaryCompareCollSeq(pParse, pExpr->pLeft,
75990               pEList->a[0].pExpr);
75991         }
75992       }else if( ALWAYS(pExpr->x.pList!=0) ){
75993         /* Case 2:     expr IN (exprlist)
75994         **
75995         ** For each expression, build an index key from the evaluation and
75996         ** store it in the temporary table. If <expr> is a column, then use
75997         ** that columns affinity when building index keys. If <expr> is not
75998         ** a column, use numeric affinity.
75999         */
76000         int i;
76001         ExprList *pList = pExpr->x.pList;
76002         struct ExprList_item *pItem;
76003         int r1, r2, r3;
76004
76005         if( !affinity ){
76006           affinity = SQLCIPHER_AFF_NONE;
76007         }
76008         keyInfo.aColl[0] = sqlcipher3ExprCollSeq(pParse, pExpr->pLeft);
76009
76010         /* Loop through each expression in <exprlist>. */
76011         r1 = sqlcipher3GetTempReg(pParse);
76012         r2 = sqlcipher3GetTempReg(pParse);
76013         sqlcipher3VdbeAddOp2(v, OP_Null, 0, r2);
76014         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
76015           Expr *pE2 = pItem->pExpr;
76016           int iValToIns;
76017
76018           /* If the expression is not constant then we will need to
76019           ** disable the test that was generated above that makes sure
76020           ** this code only executes once.  Because for a non-constant
76021           ** expression we need to rerun this code each time.
76022           */
76023           if( testAddr>=0 && !sqlcipher3ExprIsConstant(pE2) ){
76024             sqlcipher3VdbeChangeToNoop(v, testAddr);
76025             testAddr = -1;
76026           }
76027
76028           /* Evaluate the expression and insert it into the temp table */
76029           if( isRowid && sqlcipher3ExprIsInteger(pE2, &iValToIns) ){
76030             sqlcipher3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
76031           }else{
76032             r3 = sqlcipher3ExprCodeTarget(pParse, pE2, r1);
76033             if( isRowid ){
76034               sqlcipher3VdbeAddOp2(v, OP_MustBeInt, r3,
76035                                 sqlcipher3VdbeCurrentAddr(v)+2);
76036               sqlcipher3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
76037             }else{
76038               sqlcipher3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
76039               sqlcipher3ExprCacheAffinityChange(pParse, r3, 1);
76040               sqlcipher3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
76041             }
76042           }
76043         }
76044         sqlcipher3ReleaseTempReg(pParse, r1);
76045         sqlcipher3ReleaseTempReg(pParse, r2);
76046       }
76047       if( !isRowid ){
76048         sqlcipher3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
76049       }
76050       break;
76051     }
76052
76053     case TK_EXISTS:
76054     case TK_SELECT:
76055     default: {
76056       /* If this has to be a scalar SELECT.  Generate code to put the
76057       ** value of this select in a memory cell and record the number
76058       ** of the memory cell in iColumn.  If this is an EXISTS, write
76059       ** an integer 0 (not exists) or 1 (exists) into a memory cell
76060       ** and record that memory cell in iColumn.
76061       */
76062       Select *pSel;                         /* SELECT statement to encode */
76063       SelectDest dest;                      /* How to deal with SELECt result */
76064
76065       testcase( pExpr->op==TK_EXISTS );
76066       testcase( pExpr->op==TK_SELECT );
76067       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
76068
76069       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
76070       pSel = pExpr->x.pSelect;
76071       sqlcipher3SelectDestInit(&dest, 0, ++pParse->nMem);
76072       if( pExpr->op==TK_SELECT ){
76073         dest.eDest = SRT_Mem;
76074         sqlcipher3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
76075         VdbeComment((v, "Init subquery result"));
76076       }else{
76077         dest.eDest = SRT_Exists;
76078         sqlcipher3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
76079         VdbeComment((v, "Init EXISTS result"));
76080       }
76081       sqlcipher3ExprDelete(pParse->db, pSel->pLimit);
76082       pSel->pLimit = sqlcipher3PExpr(pParse, TK_INTEGER, 0, 0,
76083                                   &sqlcipher3IntTokens[1]);
76084       pSel->iLimit = 0;
76085       if( sqlcipher3Select(pParse, pSel, &dest) ){
76086         return 0;
76087       }
76088       rReg = dest.iParm;
76089       ExprSetIrreducible(pExpr);
76090       break;
76091     }
76092   }
76093
76094   if( testAddr>=0 ){
76095     sqlcipher3VdbeJumpHere(v, testAddr);
76096   }
76097   sqlcipher3ExprCachePop(pParse, 1);
76098
76099   return rReg;
76100 }
76101 #endif /* SQLCIPHER_OMIT_SUBQUERY */
76102
76103 #ifndef SQLCIPHER_OMIT_SUBQUERY
76104 /*
76105 ** Generate code for an IN expression.
76106 **
76107 **      x IN (SELECT ...)
76108 **      x IN (value, value, ...)
76109 **
76110 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
76111 ** is an array of zero or more values.  The expression is true if the LHS is
76112 ** contained within the RHS.  The value of the expression is unknown (NULL)
76113 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
76114 ** RHS contains one or more NULL values.
76115 **
76116 ** This routine generates code will jump to destIfFalse if the LHS is not 
76117 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
76118 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
76119 ** within the RHS then fall through.
76120 */
76121 static void sqlcipher3ExprCodeIN(
76122   Parse *pParse,        /* Parsing and code generating context */
76123   Expr *pExpr,          /* The IN expression */
76124   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
76125   int destIfNull        /* Jump here if the results are unknown due to NULLs */
76126 ){
76127   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
76128   char affinity;        /* Comparison affinity to use */
76129   int eType;            /* Type of the RHS */
76130   int r1;               /* Temporary use register */
76131   Vdbe *v;              /* Statement under construction */
76132
76133   /* Compute the RHS.   After this step, the table with cursor
76134   ** pExpr->iTable will contains the values that make up the RHS.
76135   */
76136   v = pParse->pVdbe;
76137   assert( v!=0 );       /* OOM detected prior to this routine */
76138   VdbeNoopComment((v, "begin IN expr"));
76139   eType = sqlcipher3FindInIndex(pParse, pExpr, &rRhsHasNull);
76140
76141   /* Figure out the affinity to use to create a key from the results
76142   ** of the expression. affinityStr stores a static string suitable for
76143   ** P4 of OP_MakeRecord.
76144   */
76145   affinity = comparisonAffinity(pExpr);
76146
76147   /* Code the LHS, the <expr> from "<expr> IN (...)".
76148   */
76149   sqlcipher3ExprCachePush(pParse);
76150   r1 = sqlcipher3GetTempReg(pParse);
76151   sqlcipher3ExprCode(pParse, pExpr->pLeft, r1);
76152
76153   /* If the LHS is NULL, then the result is either false or NULL depending
76154   ** on whether the RHS is empty or not, respectively.
76155   */
76156   if( destIfNull==destIfFalse ){
76157     /* Shortcut for the common case where the false and NULL outcomes are
76158     ** the same. */
76159     sqlcipher3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
76160   }else{
76161     int addr1 = sqlcipher3VdbeAddOp1(v, OP_NotNull, r1);
76162     sqlcipher3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
76163     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
76164     sqlcipher3VdbeJumpHere(v, addr1);
76165   }
76166
76167   if( eType==IN_INDEX_ROWID ){
76168     /* In this case, the RHS is the ROWID of table b-tree
76169     */
76170     sqlcipher3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
76171     sqlcipher3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
76172   }else{
76173     /* In this case, the RHS is an index b-tree.
76174     */
76175     sqlcipher3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
76176
76177     /* If the set membership test fails, then the result of the 
76178     ** "x IN (...)" expression must be either 0 or NULL. If the set
76179     ** contains no NULL values, then the result is 0. If the set 
76180     ** contains one or more NULL values, then the result of the
76181     ** expression is also NULL.
76182     */
76183     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
76184       /* This branch runs if it is known at compile time that the RHS
76185       ** cannot contain NULL values. This happens as the result
76186       ** of a "NOT NULL" constraint in the database schema.
76187       **
76188       ** Also run this branch if NULL is equivalent to FALSE
76189       ** for this particular IN operator.
76190       */
76191       sqlcipher3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
76192
76193     }else{
76194       /* In this branch, the RHS of the IN might contain a NULL and
76195       ** the presence of a NULL on the RHS makes a difference in the
76196       ** outcome.
76197       */
76198       int j1, j2, j3;
76199
76200       /* First check to see if the LHS is contained in the RHS.  If so,
76201       ** then the presence of NULLs in the RHS does not matter, so jump
76202       ** over all of the code that follows.
76203       */
76204       j1 = sqlcipher3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
76205
76206       /* Here we begin generating code that runs if the LHS is not
76207       ** contained within the RHS.  Generate additional code that
76208       ** tests the RHS for NULLs.  If the RHS contains a NULL then
76209       ** jump to destIfNull.  If there are no NULLs in the RHS then
76210       ** jump to destIfFalse.
76211       */
76212       j2 = sqlcipher3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
76213       j3 = sqlcipher3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
76214       sqlcipher3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
76215       sqlcipher3VdbeJumpHere(v, j3);
76216       sqlcipher3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
76217       sqlcipher3VdbeJumpHere(v, j2);
76218
76219       /* Jump to the appropriate target depending on whether or not
76220       ** the RHS contains a NULL
76221       */
76222       sqlcipher3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
76223       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
76224
76225       /* The OP_Found at the top of this branch jumps here when true, 
76226       ** causing the overall IN expression evaluation to fall through.
76227       */
76228       sqlcipher3VdbeJumpHere(v, j1);
76229     }
76230   }
76231   sqlcipher3ReleaseTempReg(pParse, r1);
76232   sqlcipher3ExprCachePop(pParse, 1);
76233   VdbeComment((v, "end IN expr"));
76234 }
76235 #endif /* SQLCIPHER_OMIT_SUBQUERY */
76236
76237 /*
76238 ** Duplicate an 8-byte value
76239 */
76240 static char *dup8bytes(Vdbe *v, const char *in){
76241   char *out = sqlcipher3DbMallocRaw(sqlcipher3VdbeDb(v), 8);
76242   if( out ){
76243     memcpy(out, in, 8);
76244   }
76245   return out;
76246 }
76247
76248 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
76249 /*
76250 ** Generate an instruction that will put the floating point
76251 ** value described by z[0..n-1] into register iMem.
76252 **
76253 ** The z[] string will probably not be zero-terminated.  But the 
76254 ** z[n] character is guaranteed to be something that does not look
76255 ** like the continuation of the number.
76256 */
76257 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
76258   if( ALWAYS(z!=0) ){
76259     double value;
76260     char *zV;
76261     sqlcipher3AtoF(z, &value, sqlcipher3Strlen30(z), SQLCIPHER_UTF8);
76262     assert( !sqlcipher3IsNaN(value) ); /* The new AtoF never returns NaN */
76263     if( negateFlag ) value = -value;
76264     zV = dup8bytes(v, (char*)&value);
76265     sqlcipher3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
76266   }
76267 }
76268 #endif
76269
76270
76271 /*
76272 ** Generate an instruction that will put the integer describe by
76273 ** text z[0..n-1] into register iMem.
76274 **
76275 ** Expr.u.zToken is always UTF8 and zero-terminated.
76276 */
76277 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
76278   Vdbe *v = pParse->pVdbe;
76279   if( pExpr->flags & EP_IntValue ){
76280     int i = pExpr->u.iValue;
76281     assert( i>=0 );
76282     if( negFlag ) i = -i;
76283     sqlcipher3VdbeAddOp2(v, OP_Integer, i, iMem);
76284   }else{
76285     int c;
76286     i64 value;
76287     const char *z = pExpr->u.zToken;
76288     assert( z!=0 );
76289     c = sqlcipher3Atoi64(z, &value, sqlcipher3Strlen30(z), SQLCIPHER_UTF8);
76290     if( c==0 || (c==2 && negFlag) ){
76291       char *zV;
76292       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
76293       zV = dup8bytes(v, (char*)&value);
76294       sqlcipher3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
76295     }else{
76296 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
76297       sqlcipher3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
76298 #else
76299       codeReal(v, z, negFlag, iMem);
76300 #endif
76301     }
76302   }
76303 }
76304
76305 /*
76306 ** Clear a cache entry.
76307 */
76308 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
76309   if( p->tempReg ){
76310     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
76311       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
76312     }
76313     p->tempReg = 0;
76314   }
76315 }
76316
76317
76318 /*
76319 ** Record in the column cache that a particular column from a
76320 ** particular table is stored in a particular register.
76321 */
76322 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
76323   int i;
76324   int minLru;
76325   int idxLru;
76326   struct yColCache *p;
76327
76328   assert( iReg>0 );  /* Register numbers are always positive */
76329   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
76330
76331   /* The SQLCIPHER_ColumnCache flag disables the column cache.  This is used
76332   ** for testing only - to verify that SQLite always gets the same answer
76333   ** with and without the column cache.
76334   */
76335   if( pParse->db->flags & SQLCIPHER_ColumnCache ) return;
76336
76337   /* First replace any existing entry.
76338   **
76339   ** Actually, the way the column cache is currently used, we are guaranteed
76340   ** that the object will never already be in cache.  Verify this guarantee.
76341   */
76342 #ifndef NDEBUG
76343   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76344 #if 0 /* This code wold remove the entry from the cache if it existed */
76345     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
76346       cacheEntryClear(pParse, p);
76347       p->iLevel = pParse->iCacheLevel;
76348       p->iReg = iReg;
76349       p->lru = pParse->iCacheCnt++;
76350       return;
76351     }
76352 #endif
76353     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
76354   }
76355 #endif
76356
76357   /* Find an empty slot and replace it */
76358   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76359     if( p->iReg==0 ){
76360       p->iLevel = pParse->iCacheLevel;
76361       p->iTable = iTab;
76362       p->iColumn = iCol;
76363       p->iReg = iReg;
76364       p->tempReg = 0;
76365       p->lru = pParse->iCacheCnt++;
76366       return;
76367     }
76368   }
76369
76370   /* Replace the last recently used */
76371   minLru = 0x7fffffff;
76372   idxLru = -1;
76373   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76374     if( p->lru<minLru ){
76375       idxLru = i;
76376       minLru = p->lru;
76377     }
76378   }
76379   if( ALWAYS(idxLru>=0) ){
76380     p = &pParse->aColCache[idxLru];
76381     p->iLevel = pParse->iCacheLevel;
76382     p->iTable = iTab;
76383     p->iColumn = iCol;
76384     p->iReg = iReg;
76385     p->tempReg = 0;
76386     p->lru = pParse->iCacheCnt++;
76387     return;
76388   }
76389 }
76390
76391 /*
76392 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
76393 ** Purge the range of registers from the column cache.
76394 */
76395 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
76396   int i;
76397   int iLast = iReg + nReg - 1;
76398   struct yColCache *p;
76399   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76400     int r = p->iReg;
76401     if( r>=iReg && r<=iLast ){
76402       cacheEntryClear(pParse, p);
76403       p->iReg = 0;
76404     }
76405   }
76406 }
76407
76408 /*
76409 ** Remember the current column cache context.  Any new entries added
76410 ** added to the column cache after this call are removed when the
76411 ** corresponding pop occurs.
76412 */
76413 SQLCIPHER_PRIVATE void sqlcipher3ExprCachePush(Parse *pParse){
76414   pParse->iCacheLevel++;
76415 }
76416
76417 /*
76418 ** Remove from the column cache any entries that were added since the
76419 ** the previous N Push operations.  In other words, restore the cache
76420 ** to the state it was in N Pushes ago.
76421 */
76422 SQLCIPHER_PRIVATE void sqlcipher3ExprCachePop(Parse *pParse, int N){
76423   int i;
76424   struct yColCache *p;
76425   assert( N>0 );
76426   assert( pParse->iCacheLevel>=N );
76427   pParse->iCacheLevel -= N;
76428   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76429     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
76430       cacheEntryClear(pParse, p);
76431       p->iReg = 0;
76432     }
76433   }
76434 }
76435
76436 /*
76437 ** When a cached column is reused, make sure that its register is
76438 ** no longer available as a temp register.  ticket #3879:  that same
76439 ** register might be in the cache in multiple places, so be sure to
76440 ** get them all.
76441 */
76442 static void sqlcipher3ExprCachePinRegister(Parse *pParse, int iReg){
76443   int i;
76444   struct yColCache *p;
76445   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76446     if( p->iReg==iReg ){
76447       p->tempReg = 0;
76448     }
76449   }
76450 }
76451
76452 /*
76453 ** Generate code to extract the value of the iCol-th column of a table.
76454 */
76455 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeGetColumnOfTable(
76456   Vdbe *v,        /* The VDBE under construction */
76457   Table *pTab,    /* The table containing the value */
76458   int iTabCur,    /* The cursor for this table */
76459   int iCol,       /* Index of the column to extract */
76460   int regOut      /* Extract the valud into this register */
76461 ){
76462   if( iCol<0 || iCol==pTab->iPKey ){
76463     sqlcipher3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
76464   }else{
76465     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
76466     sqlcipher3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
76467   }
76468   if( iCol>=0 ){
76469     sqlcipher3ColumnDefault(v, pTab, iCol, regOut);
76470   }
76471 }
76472
76473 /*
76474 ** Generate code that will extract the iColumn-th column from
76475 ** table pTab and store the column value in a register.  An effort
76476 ** is made to store the column value in register iReg, but this is
76477 ** not guaranteed.  The location of the column value is returned.
76478 **
76479 ** There must be an open cursor to pTab in iTable when this routine
76480 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
76481 */
76482 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeGetColumn(
76483   Parse *pParse,   /* Parsing and code generating context */
76484   Table *pTab,     /* Description of the table we are reading from */
76485   int iColumn,     /* Index of the table column */
76486   int iTable,      /* The cursor pointing to the table */
76487   int iReg         /* Store results here */
76488 ){
76489   Vdbe *v = pParse->pVdbe;
76490   int i;
76491   struct yColCache *p;
76492
76493   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76494     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
76495       p->lru = pParse->iCacheCnt++;
76496       sqlcipher3ExprCachePinRegister(pParse, p->iReg);
76497       return p->iReg;
76498     }
76499   }  
76500   assert( v!=0 );
76501   sqlcipher3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
76502   sqlcipher3ExprCacheStore(pParse, iTable, iColumn, iReg);
76503   return iReg;
76504 }
76505
76506 /*
76507 ** Clear all column cache entries.
76508 */
76509 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheClear(Parse *pParse){
76510   int i;
76511   struct yColCache *p;
76512
76513   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76514     if( p->iReg ){
76515       cacheEntryClear(pParse, p);
76516       p->iReg = 0;
76517     }
76518   }
76519 }
76520
76521 /*
76522 ** Record the fact that an affinity change has occurred on iCount
76523 ** registers starting with iStart.
76524 */
76525 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
76526   sqlcipher3ExprCacheRemove(pParse, iStart, iCount);
76527 }
76528
76529 /*
76530 ** Generate code to move content from registers iFrom...iFrom+nReg-1
76531 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
76532 */
76533 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
76534   int i;
76535   struct yColCache *p;
76536   if( NEVER(iFrom==iTo) ) return;
76537   sqlcipher3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
76538   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76539     int x = p->iReg;
76540     if( x>=iFrom && x<iFrom+nReg ){
76541       p->iReg += iTo-iFrom;
76542     }
76543   }
76544 }
76545
76546 /*
76547 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
76548 ** over to iTo..iTo+nReg-1.
76549 */
76550 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
76551   int i;
76552   if( NEVER(iFrom==iTo) ) return;
76553   for(i=0; i<nReg; i++){
76554     sqlcipher3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
76555   }
76556 }
76557
76558 #if defined(SQLCIPHER_DEBUG) || defined(SQLCIPHER_COVERAGE_TEST)
76559 /*
76560 ** Return true if any register in the range iFrom..iTo (inclusive)
76561 ** is used as part of the column cache.
76562 **
76563 ** This routine is used within assert() and testcase() macros only
76564 ** and does not appear in a normal build.
76565 */
76566 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
76567   int i;
76568   struct yColCache *p;
76569   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76570     int r = p->iReg;
76571     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
76572   }
76573   return 0;
76574 }
76575 #endif /* SQLCIPHER_DEBUG || SQLCIPHER_COVERAGE_TEST */
76576
76577 /*
76578 ** Generate code into the current Vdbe to evaluate the given
76579 ** expression.  Attempt to store the results in register "target".
76580 ** Return the register where results are stored.
76581 **
76582 ** With this routine, there is no guarantee that results will
76583 ** be stored in target.  The result might be stored in some other
76584 ** register if it is convenient to do so.  The calling function
76585 ** must check the return code and move the results to the desired
76586 ** register.
76587 */
76588 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
76589   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
76590   int op;                   /* The opcode being coded */
76591   int inReg = target;       /* Results stored in register inReg */
76592   int regFree1 = 0;         /* If non-zero free this temporary register */
76593   int regFree2 = 0;         /* If non-zero free this temporary register */
76594   int r1, r2, r3, r4;       /* Various register numbers */
76595   sqlcipher3 *db = pParse->db; /* The database connection */
76596
76597   assert( target>0 && target<=pParse->nMem );
76598   if( v==0 ){
76599     assert( pParse->db->mallocFailed );
76600     return 0;
76601   }
76602
76603   if( pExpr==0 ){
76604     op = TK_NULL;
76605   }else{
76606     op = pExpr->op;
76607   }
76608   switch( op ){
76609     case TK_AGG_COLUMN: {
76610       AggInfo *pAggInfo = pExpr->pAggInfo;
76611       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
76612       if( !pAggInfo->directMode ){
76613         assert( pCol->iMem>0 );
76614         inReg = pCol->iMem;
76615         break;
76616       }else if( pAggInfo->useSortingIdx ){
76617         sqlcipher3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
76618                               pCol->iSorterColumn, target);
76619         break;
76620       }
76621       /* Otherwise, fall thru into the TK_COLUMN case */
76622     }
76623     case TK_COLUMN: {
76624       if( pExpr->iTable<0 ){
76625         /* This only happens when coding check constraints */
76626         assert( pParse->ckBase>0 );
76627         inReg = pExpr->iColumn + pParse->ckBase;
76628       }else{
76629         inReg = sqlcipher3ExprCodeGetColumn(pParse, pExpr->pTab,
76630                                  pExpr->iColumn, pExpr->iTable, target);
76631       }
76632       break;
76633     }
76634     case TK_INTEGER: {
76635       codeInteger(pParse, pExpr, 0, target);
76636       break;
76637     }
76638 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
76639     case TK_FLOAT: {
76640       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76641       codeReal(v, pExpr->u.zToken, 0, target);
76642       break;
76643     }
76644 #endif
76645     case TK_STRING: {
76646       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76647       sqlcipher3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
76648       break;
76649     }
76650     case TK_NULL: {
76651       sqlcipher3VdbeAddOp2(v, OP_Null, 0, target);
76652       break;
76653     }
76654 #ifndef SQLCIPHER_OMIT_BLOB_LITERAL
76655     case TK_BLOB: {
76656       int n;
76657       const char *z;
76658       char *zBlob;
76659       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76660       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
76661       assert( pExpr->u.zToken[1]=='\'' );
76662       z = &pExpr->u.zToken[2];
76663       n = sqlcipher3Strlen30(z) - 1;
76664       assert( z[n]=='\'' );
76665       zBlob = sqlcipher3HexToBlob(sqlcipher3VdbeDb(v), z, n);
76666       sqlcipher3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
76667       break;
76668     }
76669 #endif
76670     case TK_VARIABLE: {
76671       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76672       assert( pExpr->u.zToken!=0 );
76673       assert( pExpr->u.zToken[0]!=0 );
76674       sqlcipher3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
76675       if( pExpr->u.zToken[1]!=0 ){
76676         assert( pExpr->u.zToken[0]=='?' 
76677              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
76678         sqlcipher3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
76679       }
76680       break;
76681     }
76682     case TK_REGISTER: {
76683       inReg = pExpr->iTable;
76684       break;
76685     }
76686     case TK_AS: {
76687       inReg = sqlcipher3ExprCodeTarget(pParse, pExpr->pLeft, target);
76688       break;
76689     }
76690 #ifndef SQLCIPHER_OMIT_CAST
76691     case TK_CAST: {
76692       /* Expressions of the form:   CAST(pLeft AS token) */
76693       int aff, to_op;
76694       inReg = sqlcipher3ExprCodeTarget(pParse, pExpr->pLeft, target);
76695       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76696       aff = sqlcipher3AffinityType(pExpr->u.zToken);
76697       to_op = aff - SQLCIPHER_AFF_TEXT + OP_ToText;
76698       assert( to_op==OP_ToText    || aff!=SQLCIPHER_AFF_TEXT    );
76699       assert( to_op==OP_ToBlob    || aff!=SQLCIPHER_AFF_NONE    );
76700       assert( to_op==OP_ToNumeric || aff!=SQLCIPHER_AFF_NUMERIC );
76701       assert( to_op==OP_ToInt     || aff!=SQLCIPHER_AFF_INTEGER );
76702       assert( to_op==OP_ToReal    || aff!=SQLCIPHER_AFF_REAL    );
76703       testcase( to_op==OP_ToText );
76704       testcase( to_op==OP_ToBlob );
76705       testcase( to_op==OP_ToNumeric );
76706       testcase( to_op==OP_ToInt );
76707       testcase( to_op==OP_ToReal );
76708       if( inReg!=target ){
76709         sqlcipher3VdbeAddOp2(v, OP_SCopy, inReg, target);
76710         inReg = target;
76711       }
76712       sqlcipher3VdbeAddOp1(v, to_op, inReg);
76713       testcase( usedAsColumnCache(pParse, inReg, inReg) );
76714       sqlcipher3ExprCacheAffinityChange(pParse, inReg, 1);
76715       break;
76716     }
76717 #endif /* SQLCIPHER_OMIT_CAST */
76718     case TK_LT:
76719     case TK_LE:
76720     case TK_GT:
76721     case TK_GE:
76722     case TK_NE:
76723     case TK_EQ: {
76724       assert( TK_LT==OP_Lt );
76725       assert( TK_LE==OP_Le );
76726       assert( TK_GT==OP_Gt );
76727       assert( TK_GE==OP_Ge );
76728       assert( TK_EQ==OP_Eq );
76729       assert( TK_NE==OP_Ne );
76730       testcase( op==TK_LT );
76731       testcase( op==TK_LE );
76732       testcase( op==TK_GT );
76733       testcase( op==TK_GE );
76734       testcase( op==TK_EQ );
76735       testcase( op==TK_NE );
76736       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76737       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76738       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76739                   r1, r2, inReg, SQLCIPHER_STOREP2);
76740       testcase( regFree1==0 );
76741       testcase( regFree2==0 );
76742       break;
76743     }
76744     case TK_IS:
76745     case TK_ISNOT: {
76746       testcase( op==TK_IS );
76747       testcase( op==TK_ISNOT );
76748       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76749       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76750       op = (op==TK_IS) ? TK_EQ : TK_NE;
76751       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76752                   r1, r2, inReg, SQLCIPHER_STOREP2 | SQLCIPHER_NULLEQ);
76753       testcase( regFree1==0 );
76754       testcase( regFree2==0 );
76755       break;
76756     }
76757     case TK_AND:
76758     case TK_OR:
76759     case TK_PLUS:
76760     case TK_STAR:
76761     case TK_MINUS:
76762     case TK_REM:
76763     case TK_BITAND:
76764     case TK_BITOR:
76765     case TK_SLASH:
76766     case TK_LSHIFT:
76767     case TK_RSHIFT: 
76768     case TK_CONCAT: {
76769       assert( TK_AND==OP_And );
76770       assert( TK_OR==OP_Or );
76771       assert( TK_PLUS==OP_Add );
76772       assert( TK_MINUS==OP_Subtract );
76773       assert( TK_REM==OP_Remainder );
76774       assert( TK_BITAND==OP_BitAnd );
76775       assert( TK_BITOR==OP_BitOr );
76776       assert( TK_SLASH==OP_Divide );
76777       assert( TK_LSHIFT==OP_ShiftLeft );
76778       assert( TK_RSHIFT==OP_ShiftRight );
76779       assert( TK_CONCAT==OP_Concat );
76780       testcase( op==TK_AND );
76781       testcase( op==TK_OR );
76782       testcase( op==TK_PLUS );
76783       testcase( op==TK_MINUS );
76784       testcase( op==TK_REM );
76785       testcase( op==TK_BITAND );
76786       testcase( op==TK_BITOR );
76787       testcase( op==TK_SLASH );
76788       testcase( op==TK_LSHIFT );
76789       testcase( op==TK_RSHIFT );
76790       testcase( op==TK_CONCAT );
76791       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76792       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76793       sqlcipher3VdbeAddOp3(v, op, r2, r1, target);
76794       testcase( regFree1==0 );
76795       testcase( regFree2==0 );
76796       break;
76797     }
76798     case TK_UMINUS: {
76799       Expr *pLeft = pExpr->pLeft;
76800       assert( pLeft );
76801       if( pLeft->op==TK_INTEGER ){
76802         codeInteger(pParse, pLeft, 1, target);
76803 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
76804       }else if( pLeft->op==TK_FLOAT ){
76805         assert( !ExprHasProperty(pExpr, EP_IntValue) );
76806         codeReal(v, pLeft->u.zToken, 1, target);
76807 #endif
76808       }else{
76809         regFree1 = r1 = sqlcipher3GetTempReg(pParse);
76810         sqlcipher3VdbeAddOp2(v, OP_Integer, 0, r1);
76811         r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
76812         sqlcipher3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
76813         testcase( regFree2==0 );
76814       }
76815       inReg = target;
76816       break;
76817     }
76818     case TK_BITNOT:
76819     case TK_NOT: {
76820       assert( TK_BITNOT==OP_BitNot );
76821       assert( TK_NOT==OP_Not );
76822       testcase( op==TK_BITNOT );
76823       testcase( op==TK_NOT );
76824       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76825       testcase( regFree1==0 );
76826       inReg = target;
76827       sqlcipher3VdbeAddOp2(v, op, r1, inReg);
76828       break;
76829     }
76830     case TK_ISNULL:
76831     case TK_NOTNULL: {
76832       int addr;
76833       assert( TK_ISNULL==OP_IsNull );
76834       assert( TK_NOTNULL==OP_NotNull );
76835       testcase( op==TK_ISNULL );
76836       testcase( op==TK_NOTNULL );
76837       sqlcipher3VdbeAddOp2(v, OP_Integer, 1, target);
76838       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76839       testcase( regFree1==0 );
76840       addr = sqlcipher3VdbeAddOp1(v, op, r1);
76841       sqlcipher3VdbeAddOp2(v, OP_AddImm, target, -1);
76842       sqlcipher3VdbeJumpHere(v, addr);
76843       break;
76844     }
76845     case TK_AGG_FUNCTION: {
76846       AggInfo *pInfo = pExpr->pAggInfo;
76847       if( pInfo==0 ){
76848         assert( !ExprHasProperty(pExpr, EP_IntValue) );
76849         sqlcipher3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
76850       }else{
76851         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
76852       }
76853       break;
76854     }
76855     case TK_CONST_FUNC:
76856     case TK_FUNCTION: {
76857       ExprList *pFarg;       /* List of function arguments */
76858       int nFarg;             /* Number of function arguments */
76859       FuncDef *pDef;         /* The function definition object */
76860       int nId;               /* Length of the function name in bytes */
76861       const char *zId;       /* The function name */
76862       int constMask = 0;     /* Mask of function arguments that are constant */
76863       int i;                 /* Loop counter */
76864       u8 enc = ENC(db);      /* The text encoding used by this database */
76865       CollSeq *pColl = 0;    /* A collating sequence */
76866
76867       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76868       testcase( op==TK_CONST_FUNC );
76869       testcase( op==TK_FUNCTION );
76870       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
76871         pFarg = 0;
76872       }else{
76873         pFarg = pExpr->x.pList;
76874       }
76875       nFarg = pFarg ? pFarg->nExpr : 0;
76876       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76877       zId = pExpr->u.zToken;
76878       nId = sqlcipher3Strlen30(zId);
76879       pDef = sqlcipher3FindFunction(db, zId, nId, nFarg, enc, 0);
76880       if( pDef==0 ){
76881         sqlcipher3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
76882         break;
76883       }
76884
76885       /* Attempt a direct implementation of the built-in COALESCE() and
76886       ** IFNULL() functions.  This avoids unnecessary evalation of
76887       ** arguments past the first non-NULL argument.
76888       */
76889       if( pDef->flags & SQLCIPHER_FUNC_COALESCE ){
76890         int endCoalesce = sqlcipher3VdbeMakeLabel(v);
76891         assert( nFarg>=2 );
76892         sqlcipher3ExprCode(pParse, pFarg->a[0].pExpr, target);
76893         for(i=1; i<nFarg; i++){
76894           sqlcipher3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
76895           sqlcipher3ExprCacheRemove(pParse, target, 1);
76896           sqlcipher3ExprCachePush(pParse);
76897           sqlcipher3ExprCode(pParse, pFarg->a[i].pExpr, target);
76898           sqlcipher3ExprCachePop(pParse, 1);
76899         }
76900         sqlcipher3VdbeResolveLabel(v, endCoalesce);
76901         break;
76902       }
76903
76904
76905       if( pFarg ){
76906         r1 = sqlcipher3GetTempRange(pParse, nFarg);
76907         sqlcipher3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
76908         sqlcipher3ExprCodeExprList(pParse, pFarg, r1, 1);
76909         sqlcipher3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
76910       }else{
76911         r1 = 0;
76912       }
76913 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
76914       /* Possibly overload the function if the first argument is
76915       ** a virtual table column.
76916       **
76917       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
76918       ** second argument, not the first, as the argument to test to
76919       ** see if it is a column in a virtual table.  This is done because
76920       ** the left operand of infix functions (the operand we want to
76921       ** control overloading) ends up as the second argument to the
76922       ** function.  The expression "A glob B" is equivalent to 
76923       ** "glob(B,A).  We want to use the A in "A glob B" to test
76924       ** for function overloading.  But we use the B term in "glob(B,A)".
76925       */
76926       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
76927         pDef = sqlcipher3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
76928       }else if( nFarg>0 ){
76929         pDef = sqlcipher3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
76930       }
76931 #endif
76932       for(i=0; i<nFarg; i++){
76933         if( i<32 && sqlcipher3ExprIsConstant(pFarg->a[i].pExpr) ){
76934           constMask |= (1<<i);
76935         }
76936         if( (pDef->flags & SQLCIPHER_FUNC_NEEDCOLL)!=0 && !pColl ){
76937           pColl = sqlcipher3ExprCollSeq(pParse, pFarg->a[i].pExpr);
76938         }
76939       }
76940       if( pDef->flags & SQLCIPHER_FUNC_NEEDCOLL ){
76941         if( !pColl ) pColl = db->pDfltColl; 
76942         sqlcipher3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
76943       }
76944       sqlcipher3VdbeAddOp4(v, OP_Function, constMask, r1, target,
76945                         (char*)pDef, P4_FUNCDEF);
76946       sqlcipher3VdbeChangeP5(v, (u8)nFarg);
76947       if( nFarg ){
76948         sqlcipher3ReleaseTempRange(pParse, r1, nFarg);
76949       }
76950       break;
76951     }
76952 #ifndef SQLCIPHER_OMIT_SUBQUERY
76953     case TK_EXISTS:
76954     case TK_SELECT: {
76955       testcase( op==TK_EXISTS );
76956       testcase( op==TK_SELECT );
76957       inReg = sqlcipher3CodeSubselect(pParse, pExpr, 0, 0);
76958       break;
76959     }
76960     case TK_IN: {
76961       int destIfFalse = sqlcipher3VdbeMakeLabel(v);
76962       int destIfNull = sqlcipher3VdbeMakeLabel(v);
76963       sqlcipher3VdbeAddOp2(v, OP_Null, 0, target);
76964       sqlcipher3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
76965       sqlcipher3VdbeAddOp2(v, OP_Integer, 1, target);
76966       sqlcipher3VdbeResolveLabel(v, destIfFalse);
76967       sqlcipher3VdbeAddOp2(v, OP_AddImm, target, 0);
76968       sqlcipher3VdbeResolveLabel(v, destIfNull);
76969       break;
76970     }
76971 #endif /* SQLCIPHER_OMIT_SUBQUERY */
76972
76973
76974     /*
76975     **    x BETWEEN y AND z
76976     **
76977     ** This is equivalent to
76978     **
76979     **    x>=y AND x<=z
76980     **
76981     ** X is stored in pExpr->pLeft.
76982     ** Y is stored in pExpr->pList->a[0].pExpr.
76983     ** Z is stored in pExpr->pList->a[1].pExpr.
76984     */
76985     case TK_BETWEEN: {
76986       Expr *pLeft = pExpr->pLeft;
76987       struct ExprList_item *pLItem = pExpr->x.pList->a;
76988       Expr *pRight = pLItem->pExpr;
76989
76990       r1 = sqlcipher3ExprCodeTemp(pParse, pLeft, &regFree1);
76991       r2 = sqlcipher3ExprCodeTemp(pParse, pRight, &regFree2);
76992       testcase( regFree1==0 );
76993       testcase( regFree2==0 );
76994       r3 = sqlcipher3GetTempReg(pParse);
76995       r4 = sqlcipher3GetTempReg(pParse);
76996       codeCompare(pParse, pLeft, pRight, OP_Ge,
76997                   r1, r2, r3, SQLCIPHER_STOREP2);
76998       pLItem++;
76999       pRight = pLItem->pExpr;
77000       sqlcipher3ReleaseTempReg(pParse, regFree2);
77001       r2 = sqlcipher3ExprCodeTemp(pParse, pRight, &regFree2);
77002       testcase( regFree2==0 );
77003       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLCIPHER_STOREP2);
77004       sqlcipher3VdbeAddOp3(v, OP_And, r3, r4, target);
77005       sqlcipher3ReleaseTempReg(pParse, r3);
77006       sqlcipher3ReleaseTempReg(pParse, r4);
77007       break;
77008     }
77009     case TK_UPLUS: {
77010       inReg = sqlcipher3ExprCodeTarget(pParse, pExpr->pLeft, target);
77011       break;
77012     }
77013
77014     case TK_TRIGGER: {
77015       /* If the opcode is TK_TRIGGER, then the expression is a reference
77016       ** to a column in the new.* or old.* pseudo-tables available to
77017       ** trigger programs. In this case Expr.iTable is set to 1 for the
77018       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
77019       ** is set to the column of the pseudo-table to read, or to -1 to
77020       ** read the rowid field.
77021       **
77022       ** The expression is implemented using an OP_Param opcode. The p1
77023       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
77024       ** to reference another column of the old.* pseudo-table, where 
77025       ** i is the index of the column. For a new.rowid reference, p1 is
77026       ** set to (n+1), where n is the number of columns in each pseudo-table.
77027       ** For a reference to any other column in the new.* pseudo-table, p1
77028       ** is set to (n+2+i), where n and i are as defined previously. For
77029       ** example, if the table on which triggers are being fired is
77030       ** declared as:
77031       **
77032       **   CREATE TABLE t1(a, b);
77033       **
77034       ** Then p1 is interpreted as follows:
77035       **
77036       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
77037       **   p1==1   ->    old.a         p1==4   ->    new.a
77038       **   p1==2   ->    old.b         p1==5   ->    new.b       
77039       */
77040       Table *pTab = pExpr->pTab;
77041       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
77042
77043       assert( pExpr->iTable==0 || pExpr->iTable==1 );
77044       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
77045       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
77046       assert( p1>=0 && p1<(pTab->nCol*2+2) );
77047
77048       sqlcipher3VdbeAddOp2(v, OP_Param, p1, target);
77049       VdbeComment((v, "%s.%s -> $%d",
77050         (pExpr->iTable ? "new" : "old"),
77051         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
77052         target
77053       ));
77054
77055 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
77056       /* If the column has REAL affinity, it may currently be stored as an
77057       ** integer. Use OP_RealAffinity to make sure it is really real.  */
77058       if( pExpr->iColumn>=0 
77059        && pTab->aCol[pExpr->iColumn].affinity==SQLCIPHER_AFF_REAL
77060       ){
77061         sqlcipher3VdbeAddOp1(v, OP_RealAffinity, target);
77062       }
77063 #endif
77064       break;
77065     }
77066
77067
77068     /*
77069     ** Form A:
77070     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
77071     **
77072     ** Form B:
77073     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
77074     **
77075     ** Form A is can be transformed into the equivalent form B as follows:
77076     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
77077     **        WHEN x=eN THEN rN ELSE y END
77078     **
77079     ** X (if it exists) is in pExpr->pLeft.
77080     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
77081     ** ELSE clause and no other term matches, then the result of the
77082     ** exprssion is NULL.
77083     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
77084     **
77085     ** The result of the expression is the Ri for the first matching Ei,
77086     ** or if there is no matching Ei, the ELSE term Y, or if there is
77087     ** no ELSE term, NULL.
77088     */
77089     default: assert( op==TK_CASE ); {
77090       int endLabel;                     /* GOTO label for end of CASE stmt */
77091       int nextCase;                     /* GOTO label for next WHEN clause */
77092       int nExpr;                        /* 2x number of WHEN terms */
77093       int i;                            /* Loop counter */
77094       ExprList *pEList;                 /* List of WHEN terms */
77095       struct ExprList_item *aListelem;  /* Array of WHEN terms */
77096       Expr opCompare;                   /* The X==Ei expression */
77097       Expr cacheX;                      /* Cached expression X */
77098       Expr *pX;                         /* The X expression */
77099       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
77100       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
77101
77102       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
77103       assert((pExpr->x.pList->nExpr % 2) == 0);
77104       assert(pExpr->x.pList->nExpr > 0);
77105       pEList = pExpr->x.pList;
77106       aListelem = pEList->a;
77107       nExpr = pEList->nExpr;
77108       endLabel = sqlcipher3VdbeMakeLabel(v);
77109       if( (pX = pExpr->pLeft)!=0 ){
77110         cacheX = *pX;
77111         testcase( pX->op==TK_COLUMN );
77112         testcase( pX->op==TK_REGISTER );
77113         cacheX.iTable = sqlcipher3ExprCodeTemp(pParse, pX, &regFree1);
77114         testcase( regFree1==0 );
77115         cacheX.op = TK_REGISTER;
77116         opCompare.op = TK_EQ;
77117         opCompare.pLeft = &cacheX;
77118         pTest = &opCompare;
77119         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
77120         ** The value in regFree1 might get SCopy-ed into the file result.
77121         ** So make sure that the regFree1 register is not reused for other
77122         ** purposes and possibly overwritten.  */
77123         regFree1 = 0;
77124       }
77125       for(i=0; i<nExpr; i=i+2){
77126         sqlcipher3ExprCachePush(pParse);
77127         if( pX ){
77128           assert( pTest!=0 );
77129           opCompare.pRight = aListelem[i].pExpr;
77130         }else{
77131           pTest = aListelem[i].pExpr;
77132         }
77133         nextCase = sqlcipher3VdbeMakeLabel(v);
77134         testcase( pTest->op==TK_COLUMN );
77135         sqlcipher3ExprIfFalse(pParse, pTest, nextCase, SQLCIPHER_JUMPIFNULL);
77136         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
77137         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
77138         sqlcipher3ExprCode(pParse, aListelem[i+1].pExpr, target);
77139         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, endLabel);
77140         sqlcipher3ExprCachePop(pParse, 1);
77141         sqlcipher3VdbeResolveLabel(v, nextCase);
77142       }
77143       if( pExpr->pRight ){
77144         sqlcipher3ExprCachePush(pParse);
77145         sqlcipher3ExprCode(pParse, pExpr->pRight, target);
77146         sqlcipher3ExprCachePop(pParse, 1);
77147       }else{
77148         sqlcipher3VdbeAddOp2(v, OP_Null, 0, target);
77149       }
77150       assert( db->mallocFailed || pParse->nErr>0 
77151            || pParse->iCacheLevel==iCacheLevel );
77152       sqlcipher3VdbeResolveLabel(v, endLabel);
77153       break;
77154     }
77155 #ifndef SQLCIPHER_OMIT_TRIGGER
77156     case TK_RAISE: {
77157       assert( pExpr->affinity==OE_Rollback 
77158            || pExpr->affinity==OE_Abort
77159            || pExpr->affinity==OE_Fail
77160            || pExpr->affinity==OE_Ignore
77161       );
77162       if( !pParse->pTriggerTab ){
77163         sqlcipher3ErrorMsg(pParse,
77164                        "RAISE() may only be used within a trigger-program");
77165         return 0;
77166       }
77167       if( pExpr->affinity==OE_Abort ){
77168         sqlcipher3MayAbort(pParse);
77169       }
77170       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77171       if( pExpr->affinity==OE_Ignore ){
77172         sqlcipher3VdbeAddOp4(
77173             v, OP_Halt, SQLCIPHER_OK, OE_Ignore, 0, pExpr->u.zToken,0);
77174       }else{
77175         sqlcipher3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
77176       }
77177
77178       break;
77179     }
77180 #endif
77181   }
77182   sqlcipher3ReleaseTempReg(pParse, regFree1);
77183   sqlcipher3ReleaseTempReg(pParse, regFree2);
77184   return inReg;
77185 }
77186
77187 /*
77188 ** Generate code to evaluate an expression and store the results
77189 ** into a register.  Return the register number where the results
77190 ** are stored.
77191 **
77192 ** If the register is a temporary register that can be deallocated,
77193 ** then write its number into *pReg.  If the result register is not
77194 ** a temporary, then set *pReg to zero.
77195 */
77196 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
77197   int r1 = sqlcipher3GetTempReg(pParse);
77198   int r2 = sqlcipher3ExprCodeTarget(pParse, pExpr, r1);
77199   if( r2==r1 ){
77200     *pReg = r1;
77201   }else{
77202     sqlcipher3ReleaseTempReg(pParse, r1);
77203     *pReg = 0;
77204   }
77205   return r2;
77206 }
77207
77208 /*
77209 ** Generate code that will evaluate expression pExpr and store the
77210 ** results in register target.  The results are guaranteed to appear
77211 ** in register target.
77212 */
77213 SQLCIPHER_PRIVATE int sqlcipher3ExprCode(Parse *pParse, Expr *pExpr, int target){
77214   int inReg;
77215
77216   assert( target>0 && target<=pParse->nMem );
77217   if( pExpr && pExpr->op==TK_REGISTER ){
77218     sqlcipher3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
77219   }else{
77220     inReg = sqlcipher3ExprCodeTarget(pParse, pExpr, target);
77221     assert( pParse->pVdbe || pParse->db->mallocFailed );
77222     if( inReg!=target && pParse->pVdbe ){
77223       sqlcipher3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
77224     }
77225   }
77226   return target;
77227 }
77228
77229 /*
77230 ** Generate code that evalutes the given expression and puts the result
77231 ** in register target.
77232 **
77233 ** Also make a copy of the expression results into another "cache" register
77234 ** and modify the expression so that the next time it is evaluated,
77235 ** the result is a copy of the cache register.
77236 **
77237 ** This routine is used for expressions that are used multiple 
77238 ** times.  They are evaluated once and the results of the expression
77239 ** are reused.
77240 */
77241 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
77242   Vdbe *v = pParse->pVdbe;
77243   int inReg;
77244   inReg = sqlcipher3ExprCode(pParse, pExpr, target);
77245   assert( target>0 );
77246   /* This routine is called for terms to INSERT or UPDATE.  And the only
77247   ** other place where expressions can be converted into TK_REGISTER is
77248   ** in WHERE clause processing.  So as currently implemented, there is
77249   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
77250   ** keep the ALWAYS() in case the conditions above change with future
77251   ** modifications or enhancements. */
77252   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
77253     int iMem;
77254     iMem = ++pParse->nMem;
77255     sqlcipher3VdbeAddOp2(v, OP_Copy, inReg, iMem);
77256     pExpr->iTable = iMem;
77257     pExpr->op2 = pExpr->op;
77258     pExpr->op = TK_REGISTER;
77259   }
77260   return inReg;
77261 }
77262
77263 /*
77264 ** Return TRUE if pExpr is an constant expression that is appropriate
77265 ** for factoring out of a loop.  Appropriate expressions are:
77266 **
77267 **    *  Any expression that evaluates to two or more opcodes.
77268 **
77269 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
77270 **       or OP_Variable that does not need to be placed in a 
77271 **       specific register.
77272 **
77273 ** There is no point in factoring out single-instruction constant
77274 ** expressions that need to be placed in a particular register.  
77275 ** We could factor them out, but then we would end up adding an
77276 ** OP_SCopy instruction to move the value into the correct register
77277 ** later.  We might as well just use the original instruction and
77278 ** avoid the OP_SCopy.
77279 */
77280 static int isAppropriateForFactoring(Expr *p){
77281   if( !sqlcipher3ExprIsConstantNotJoin(p) ){
77282     return 0;  /* Only constant expressions are appropriate for factoring */
77283   }
77284   if( (p->flags & EP_FixedDest)==0 ){
77285     return 1;  /* Any constant without a fixed destination is appropriate */
77286   }
77287   while( p->op==TK_UPLUS ) p = p->pLeft;
77288   switch( p->op ){
77289 #ifndef SQLCIPHER_OMIT_BLOB_LITERAL
77290     case TK_BLOB:
77291 #endif
77292     case TK_VARIABLE:
77293     case TK_INTEGER:
77294     case TK_FLOAT:
77295     case TK_NULL:
77296     case TK_STRING: {
77297       testcase( p->op==TK_BLOB );
77298       testcase( p->op==TK_VARIABLE );
77299       testcase( p->op==TK_INTEGER );
77300       testcase( p->op==TK_FLOAT );
77301       testcase( p->op==TK_NULL );
77302       testcase( p->op==TK_STRING );
77303       /* Single-instruction constants with a fixed destination are
77304       ** better done in-line.  If we factor them, they will just end
77305       ** up generating an OP_SCopy to move the value to the destination
77306       ** register. */
77307       return 0;
77308     }
77309     case TK_UMINUS: {
77310       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
77311         return 0;
77312       }
77313       break;
77314     }
77315     default: {
77316       break;
77317     }
77318   }
77319   return 1;
77320 }
77321
77322 /*
77323 ** If pExpr is a constant expression that is appropriate for
77324 ** factoring out of a loop, then evaluate the expression
77325 ** into a register and convert the expression into a TK_REGISTER
77326 ** expression.
77327 */
77328 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
77329   Parse *pParse = pWalker->pParse;
77330   switch( pExpr->op ){
77331     case TK_IN:
77332     case TK_REGISTER: {
77333       return WRC_Prune;
77334     }
77335     case TK_FUNCTION:
77336     case TK_AGG_FUNCTION:
77337     case TK_CONST_FUNC: {
77338       /* The arguments to a function have a fixed destination.
77339       ** Mark them this way to avoid generated unneeded OP_SCopy
77340       ** instructions. 
77341       */
77342       ExprList *pList = pExpr->x.pList;
77343       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77344       if( pList ){
77345         int i = pList->nExpr;
77346         struct ExprList_item *pItem = pList->a;
77347         for(; i>0; i--, pItem++){
77348           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
77349         }
77350       }
77351       break;
77352     }
77353   }
77354   if( isAppropriateForFactoring(pExpr) ){
77355     int r1 = ++pParse->nMem;
77356     int r2;
77357     r2 = sqlcipher3ExprCodeTarget(pParse, pExpr, r1);
77358     if( NEVER(r1!=r2) ) sqlcipher3ReleaseTempReg(pParse, r1);
77359     pExpr->op2 = pExpr->op;
77360     pExpr->op = TK_REGISTER;
77361     pExpr->iTable = r2;
77362     return WRC_Prune;
77363   }
77364   return WRC_Continue;
77365 }
77366
77367 /*
77368 ** Preevaluate constant subexpressions within pExpr and store the
77369 ** results in registers.  Modify pExpr so that the constant subexpresions
77370 ** are TK_REGISTER opcodes that refer to the precomputed values.
77371 **
77372 ** This routine is a no-op if the jump to the cookie-check code has
77373 ** already occur.  Since the cookie-check jump is generated prior to
77374 ** any other serious processing, this check ensures that there is no
77375 ** way to accidently bypass the constant initializations.
77376 **
77377 ** This routine is also a no-op if the SQLCIPHER_FactorOutConst optimization
77378 ** is disabled via the sqlcipher3_test_control(SQLCIPHER_TESTCTRL_OPTIMIZATIONS)
77379 ** interface.  This allows test logic to verify that the same answer is
77380 ** obtained for queries regardless of whether or not constants are
77381 ** precomputed into registers or if they are inserted in-line.
77382 */
77383 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeConstants(Parse *pParse, Expr *pExpr){
77384   Walker w;
77385   if( pParse->cookieGoto ) return;
77386   if( (pParse->db->flags & SQLCIPHER_FactorOutConst)!=0 ) return;
77387   w.xExprCallback = evalConstExpr;
77388   w.xSelectCallback = 0;
77389   w.pParse = pParse;
77390   sqlcipher3WalkExpr(&w, pExpr);
77391 }
77392
77393
77394 /*
77395 ** Generate code that pushes the value of every element of the given
77396 ** expression list into a sequence of registers beginning at target.
77397 **
77398 ** Return the number of elements evaluated.
77399 */
77400 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeExprList(
77401   Parse *pParse,     /* Parsing context */
77402   ExprList *pList,   /* The expression list to be coded */
77403   int target,        /* Where to write results */
77404   int doHardCopy     /* Make a hard copy of every element */
77405 ){
77406   struct ExprList_item *pItem;
77407   int i, n;
77408   assert( pList!=0 );
77409   assert( target>0 );
77410   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
77411   n = pList->nExpr;
77412   for(pItem=pList->a, i=0; i<n; i++, pItem++){
77413     Expr *pExpr = pItem->pExpr;
77414     int inReg = sqlcipher3ExprCodeTarget(pParse, pExpr, target+i);
77415     if( inReg!=target+i ){
77416       sqlcipher3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
77417                         inReg, target+i);
77418     }
77419   }
77420   return n;
77421 }
77422
77423 /*
77424 ** Generate code for a BETWEEN operator.
77425 **
77426 **    x BETWEEN y AND z
77427 **
77428 ** The above is equivalent to 
77429 **
77430 **    x>=y AND x<=z
77431 **
77432 ** Code it as such, taking care to do the common subexpression
77433 ** elementation of x.
77434 */
77435 static void exprCodeBetween(
77436   Parse *pParse,    /* Parsing and code generating context */
77437   Expr *pExpr,      /* The BETWEEN expression */
77438   int dest,         /* Jump here if the jump is taken */
77439   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
77440   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
77441 ){
77442   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
77443   Expr compLeft;    /* The  x>=y  term */
77444   Expr compRight;   /* The  x<=z  term */
77445   Expr exprX;       /* The  x  subexpression */
77446   int regFree1 = 0; /* Temporary use register */
77447
77448   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77449   exprX = *pExpr->pLeft;
77450   exprAnd.op = TK_AND;
77451   exprAnd.pLeft = &compLeft;
77452   exprAnd.pRight = &compRight;
77453   compLeft.op = TK_GE;
77454   compLeft.pLeft = &exprX;
77455   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
77456   compRight.op = TK_LE;
77457   compRight.pLeft = &exprX;
77458   compRight.pRight = pExpr->x.pList->a[1].pExpr;
77459   exprX.iTable = sqlcipher3ExprCodeTemp(pParse, &exprX, &regFree1);
77460   exprX.op = TK_REGISTER;
77461   if( jumpIfTrue ){
77462     sqlcipher3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
77463   }else{
77464     sqlcipher3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
77465   }
77466   sqlcipher3ReleaseTempReg(pParse, regFree1);
77467
77468   /* Ensure adequate test coverage */
77469   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
77470   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
77471   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
77472   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
77473   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
77474   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
77475   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
77476   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
77477 }
77478
77479 /*
77480 ** Generate code for a boolean expression such that a jump is made
77481 ** to the label "dest" if the expression is true but execution
77482 ** continues straight thru if the expression is false.
77483 **
77484 ** If the expression evaluates to NULL (neither true nor false), then
77485 ** take the jump if the jumpIfNull flag is SQLCIPHER_JUMPIFNULL.
77486 **
77487 ** This code depends on the fact that certain token values (ex: TK_EQ)
77488 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
77489 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
77490 ** the make process cause these values to align.  Assert()s in the code
77491 ** below verify that the numbers are aligned correctly.
77492 */
77493 SQLCIPHER_PRIVATE void sqlcipher3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77494   Vdbe *v = pParse->pVdbe;
77495   int op = 0;
77496   int regFree1 = 0;
77497   int regFree2 = 0;
77498   int r1, r2;
77499
77500   assert( jumpIfNull==SQLCIPHER_JUMPIFNULL || jumpIfNull==0 );
77501   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
77502   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
77503   op = pExpr->op;
77504   switch( op ){
77505     case TK_AND: {
77506       int d2 = sqlcipher3VdbeMakeLabel(v);
77507       testcase( jumpIfNull==0 );
77508       sqlcipher3ExprCachePush(pParse);
77509       sqlcipher3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLCIPHER_JUMPIFNULL);
77510       sqlcipher3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77511       sqlcipher3VdbeResolveLabel(v, d2);
77512       sqlcipher3ExprCachePop(pParse, 1);
77513       break;
77514     }
77515     case TK_OR: {
77516       testcase( jumpIfNull==0 );
77517       sqlcipher3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
77518       sqlcipher3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77519       break;
77520     }
77521     case TK_NOT: {
77522       testcase( jumpIfNull==0 );
77523       sqlcipher3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
77524       break;
77525     }
77526     case TK_LT:
77527     case TK_LE:
77528     case TK_GT:
77529     case TK_GE:
77530     case TK_NE:
77531     case TK_EQ: {
77532       assert( TK_LT==OP_Lt );
77533       assert( TK_LE==OP_Le );
77534       assert( TK_GT==OP_Gt );
77535       assert( TK_GE==OP_Ge );
77536       assert( TK_EQ==OP_Eq );
77537       assert( TK_NE==OP_Ne );
77538       testcase( op==TK_LT );
77539       testcase( op==TK_LE );
77540       testcase( op==TK_GT );
77541       testcase( op==TK_GE );
77542       testcase( op==TK_EQ );
77543       testcase( op==TK_NE );
77544       testcase( jumpIfNull==0 );
77545       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77546       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77547       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77548                   r1, r2, dest, jumpIfNull);
77549       testcase( regFree1==0 );
77550       testcase( regFree2==0 );
77551       break;
77552     }
77553     case TK_IS:
77554     case TK_ISNOT: {
77555       testcase( op==TK_IS );
77556       testcase( op==TK_ISNOT );
77557       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77558       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77559       op = (op==TK_IS) ? TK_EQ : TK_NE;
77560       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77561                   r1, r2, dest, SQLCIPHER_NULLEQ);
77562       testcase( regFree1==0 );
77563       testcase( regFree2==0 );
77564       break;
77565     }
77566     case TK_ISNULL:
77567     case TK_NOTNULL: {
77568       assert( TK_ISNULL==OP_IsNull );
77569       assert( TK_NOTNULL==OP_NotNull );
77570       testcase( op==TK_ISNULL );
77571       testcase( op==TK_NOTNULL );
77572       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77573       sqlcipher3VdbeAddOp2(v, op, r1, dest);
77574       testcase( regFree1==0 );
77575       break;
77576     }
77577     case TK_BETWEEN: {
77578       testcase( jumpIfNull==0 );
77579       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
77580       break;
77581     }
77582 #ifndef SQLCIPHER_OMIT_SUBQUERY
77583     case TK_IN: {
77584       int destIfFalse = sqlcipher3VdbeMakeLabel(v);
77585       int destIfNull = jumpIfNull ? dest : destIfFalse;
77586       sqlcipher3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
77587       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, dest);
77588       sqlcipher3VdbeResolveLabel(v, destIfFalse);
77589       break;
77590     }
77591 #endif
77592     default: {
77593       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr, &regFree1);
77594       sqlcipher3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
77595       testcase( regFree1==0 );
77596       testcase( jumpIfNull==0 );
77597       break;
77598     }
77599   }
77600   sqlcipher3ReleaseTempReg(pParse, regFree1);
77601   sqlcipher3ReleaseTempReg(pParse, regFree2);  
77602 }
77603
77604 /*
77605 ** Generate code for a boolean expression such that a jump is made
77606 ** to the label "dest" if the expression is false but execution
77607 ** continues straight thru if the expression is true.
77608 **
77609 ** If the expression evaluates to NULL (neither true nor false) then
77610 ** jump if jumpIfNull is SQLCIPHER_JUMPIFNULL or fall through if jumpIfNull
77611 ** is 0.
77612 */
77613 SQLCIPHER_PRIVATE void sqlcipher3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77614   Vdbe *v = pParse->pVdbe;
77615   int op = 0;
77616   int regFree1 = 0;
77617   int regFree2 = 0;
77618   int r1, r2;
77619
77620   assert( jumpIfNull==SQLCIPHER_JUMPIFNULL || jumpIfNull==0 );
77621   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
77622   if( pExpr==0 )    return;
77623
77624   /* The value of pExpr->op and op are related as follows:
77625   **
77626   **       pExpr->op            op
77627   **       ---------          ----------
77628   **       TK_ISNULL          OP_NotNull
77629   **       TK_NOTNULL         OP_IsNull
77630   **       TK_NE              OP_Eq
77631   **       TK_EQ              OP_Ne
77632   **       TK_GT              OP_Le
77633   **       TK_LE              OP_Gt
77634   **       TK_GE              OP_Lt
77635   **       TK_LT              OP_Ge
77636   **
77637   ** For other values of pExpr->op, op is undefined and unused.
77638   ** The value of TK_ and OP_ constants are arranged such that we
77639   ** can compute the mapping above using the following expression.
77640   ** Assert()s verify that the computation is correct.
77641   */
77642   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
77643
77644   /* Verify correct alignment of TK_ and OP_ constants
77645   */
77646   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
77647   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
77648   assert( pExpr->op!=TK_NE || op==OP_Eq );
77649   assert( pExpr->op!=TK_EQ || op==OP_Ne );
77650   assert( pExpr->op!=TK_LT || op==OP_Ge );
77651   assert( pExpr->op!=TK_LE || op==OP_Gt );
77652   assert( pExpr->op!=TK_GT || op==OP_Le );
77653   assert( pExpr->op!=TK_GE || op==OP_Lt );
77654
77655   switch( pExpr->op ){
77656     case TK_AND: {
77657       testcase( jumpIfNull==0 );
77658       sqlcipher3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
77659       sqlcipher3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
77660       break;
77661     }
77662     case TK_OR: {
77663       int d2 = sqlcipher3VdbeMakeLabel(v);
77664       testcase( jumpIfNull==0 );
77665       sqlcipher3ExprCachePush(pParse);
77666       sqlcipher3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLCIPHER_JUMPIFNULL);
77667       sqlcipher3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
77668       sqlcipher3VdbeResolveLabel(v, d2);
77669       sqlcipher3ExprCachePop(pParse, 1);
77670       break;
77671     }
77672     case TK_NOT: {
77673       testcase( jumpIfNull==0 );
77674       sqlcipher3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
77675       break;
77676     }
77677     case TK_LT:
77678     case TK_LE:
77679     case TK_GT:
77680     case TK_GE:
77681     case TK_NE:
77682     case TK_EQ: {
77683       testcase( op==TK_LT );
77684       testcase( op==TK_LE );
77685       testcase( op==TK_GT );
77686       testcase( op==TK_GE );
77687       testcase( op==TK_EQ );
77688       testcase( op==TK_NE );
77689       testcase( jumpIfNull==0 );
77690       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77691       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77692       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77693                   r1, r2, dest, jumpIfNull);
77694       testcase( regFree1==0 );
77695       testcase( regFree2==0 );
77696       break;
77697     }
77698     case TK_IS:
77699     case TK_ISNOT: {
77700       testcase( pExpr->op==TK_IS );
77701       testcase( pExpr->op==TK_ISNOT );
77702       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77703       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77704       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
77705       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77706                   r1, r2, dest, SQLCIPHER_NULLEQ);
77707       testcase( regFree1==0 );
77708       testcase( regFree2==0 );
77709       break;
77710     }
77711     case TK_ISNULL:
77712     case TK_NOTNULL: {
77713       testcase( op==TK_ISNULL );
77714       testcase( op==TK_NOTNULL );
77715       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77716       sqlcipher3VdbeAddOp2(v, op, r1, dest);
77717       testcase( regFree1==0 );
77718       break;
77719     }
77720     case TK_BETWEEN: {
77721       testcase( jumpIfNull==0 );
77722       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
77723       break;
77724     }
77725 #ifndef SQLCIPHER_OMIT_SUBQUERY
77726     case TK_IN: {
77727       if( jumpIfNull ){
77728         sqlcipher3ExprCodeIN(pParse, pExpr, dest, dest);
77729       }else{
77730         int destIfNull = sqlcipher3VdbeMakeLabel(v);
77731         sqlcipher3ExprCodeIN(pParse, pExpr, dest, destIfNull);
77732         sqlcipher3VdbeResolveLabel(v, destIfNull);
77733       }
77734       break;
77735     }
77736 #endif
77737     default: {
77738       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr, &regFree1);
77739       sqlcipher3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
77740       testcase( regFree1==0 );
77741       testcase( jumpIfNull==0 );
77742       break;
77743     }
77744   }
77745   sqlcipher3ReleaseTempReg(pParse, regFree1);
77746   sqlcipher3ReleaseTempReg(pParse, regFree2);
77747 }
77748
77749 /*
77750 ** Do a deep comparison of two expression trees.  Return 0 if the two
77751 ** expressions are completely identical.  Return 1 if they differ only
77752 ** by a COLLATE operator at the top level.  Return 2 if there are differences
77753 ** other than the top-level COLLATE operator.
77754 **
77755 ** Sometimes this routine will return 2 even if the two expressions
77756 ** really are equivalent.  If we cannot prove that the expressions are
77757 ** identical, we return 2 just to be safe.  So if this routine
77758 ** returns 2, then you do not really know for certain if the two
77759 ** expressions are the same.  But if you get a 0 or 1 return, then you
77760 ** can be sure the expressions are the same.  In the places where
77761 ** this routine is used, it does not hurt to get an extra 2 - that
77762 ** just might result in some slightly slower code.  But returning
77763 ** an incorrect 0 or 1 could lead to a malfunction.
77764 */
77765 SQLCIPHER_PRIVATE int sqlcipher3ExprCompare(Expr *pA, Expr *pB){
77766   if( pA==0||pB==0 ){
77767     return pB==pA ? 0 : 2;
77768   }
77769   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
77770   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
77771   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
77772     return 2;
77773   }
77774   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
77775   if( pA->op!=pB->op ) return 2;
77776   if( sqlcipher3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
77777   if( sqlcipher3ExprCompare(pA->pRight, pB->pRight) ) return 2;
77778   if( sqlcipher3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
77779   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
77780   if( ExprHasProperty(pA, EP_IntValue) ){
77781     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
77782       return 2;
77783     }
77784   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
77785     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
77786     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
77787       return 2;
77788     }
77789   }
77790   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
77791   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
77792   return 0;
77793 }
77794
77795 /*
77796 ** Compare two ExprList objects.  Return 0 if they are identical and 
77797 ** non-zero if they differ in any way.
77798 **
77799 ** This routine might return non-zero for equivalent ExprLists.  The
77800 ** only consequence will be disabled optimizations.  But this routine
77801 ** must never return 0 if the two ExprList objects are different, or
77802 ** a malfunction will result.
77803 **
77804 ** Two NULL pointers are considered to be the same.  But a NULL pointer
77805 ** always differs from a non-NULL pointer.
77806 */
77807 SQLCIPHER_PRIVATE int sqlcipher3ExprListCompare(ExprList *pA, ExprList *pB){
77808   int i;
77809   if( pA==0 && pB==0 ) return 0;
77810   if( pA==0 || pB==0 ) return 1;
77811   if( pA->nExpr!=pB->nExpr ) return 1;
77812   for(i=0; i<pA->nExpr; i++){
77813     Expr *pExprA = pA->a[i].pExpr;
77814     Expr *pExprB = pB->a[i].pExpr;
77815     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
77816     if( sqlcipher3ExprCompare(pExprA, pExprB) ) return 1;
77817   }
77818   return 0;
77819 }
77820
77821 /*
77822 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
77823 ** the new element.  Return a negative number if malloc fails.
77824 */
77825 static int addAggInfoColumn(sqlcipher3 *db, AggInfo *pInfo){
77826   int i;
77827   pInfo->aCol = sqlcipher3ArrayAllocate(
77828        db,
77829        pInfo->aCol,
77830        sizeof(pInfo->aCol[0]),
77831        3,
77832        &pInfo->nColumn,
77833        &pInfo->nColumnAlloc,
77834        &i
77835   );
77836   return i;
77837 }    
77838
77839 /*
77840 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
77841 ** the new element.  Return a negative number if malloc fails.
77842 */
77843 static int addAggInfoFunc(sqlcipher3 *db, AggInfo *pInfo){
77844   int i;
77845   pInfo->aFunc = sqlcipher3ArrayAllocate(
77846        db, 
77847        pInfo->aFunc,
77848        sizeof(pInfo->aFunc[0]),
77849        3,
77850        &pInfo->nFunc,
77851        &pInfo->nFuncAlloc,
77852        &i
77853   );
77854   return i;
77855 }    
77856
77857 /*
77858 ** This is the xExprCallback for a tree walker.  It is used to
77859 ** implement sqlcipher3ExprAnalyzeAggregates().  See sqlcipher3ExprAnalyzeAggregates
77860 ** for additional information.
77861 */
77862 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
77863   int i;
77864   NameContext *pNC = pWalker->u.pNC;
77865   Parse *pParse = pNC->pParse;
77866   SrcList *pSrcList = pNC->pSrcList;
77867   AggInfo *pAggInfo = pNC->pAggInfo;
77868
77869   switch( pExpr->op ){
77870     case TK_AGG_COLUMN:
77871     case TK_COLUMN: {
77872       testcase( pExpr->op==TK_AGG_COLUMN );
77873       testcase( pExpr->op==TK_COLUMN );
77874       /* Check to see if the column is in one of the tables in the FROM
77875       ** clause of the aggregate query */
77876       if( ALWAYS(pSrcList!=0) ){
77877         struct SrcList_item *pItem = pSrcList->a;
77878         for(i=0; i<pSrcList->nSrc; i++, pItem++){
77879           struct AggInfo_col *pCol;
77880           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
77881           if( pExpr->iTable==pItem->iCursor ){
77882             /* If we reach this point, it means that pExpr refers to a table
77883             ** that is in the FROM clause of the aggregate query.  
77884             **
77885             ** Make an entry for the column in pAggInfo->aCol[] if there
77886             ** is not an entry there already.
77887             */
77888             int k;
77889             pCol = pAggInfo->aCol;
77890             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
77891               if( pCol->iTable==pExpr->iTable &&
77892                   pCol->iColumn==pExpr->iColumn ){
77893                 break;
77894               }
77895             }
77896             if( (k>=pAggInfo->nColumn)
77897              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
77898             ){
77899               pCol = &pAggInfo->aCol[k];
77900               pCol->pTab = pExpr->pTab;
77901               pCol->iTable = pExpr->iTable;
77902               pCol->iColumn = pExpr->iColumn;
77903               pCol->iMem = ++pParse->nMem;
77904               pCol->iSorterColumn = -1;
77905               pCol->pExpr = pExpr;
77906               if( pAggInfo->pGroupBy ){
77907                 int j, n;
77908                 ExprList *pGB = pAggInfo->pGroupBy;
77909                 struct ExprList_item *pTerm = pGB->a;
77910                 n = pGB->nExpr;
77911                 for(j=0; j<n; j++, pTerm++){
77912                   Expr *pE = pTerm->pExpr;
77913                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
77914                       pE->iColumn==pExpr->iColumn ){
77915                     pCol->iSorterColumn = j;
77916                     break;
77917                   }
77918                 }
77919               }
77920               if( pCol->iSorterColumn<0 ){
77921                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
77922               }
77923             }
77924             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
77925             ** because it was there before or because we just created it).
77926             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
77927             ** pAggInfo->aCol[] entry.
77928             */
77929             ExprSetIrreducible(pExpr);
77930             pExpr->pAggInfo = pAggInfo;
77931             pExpr->op = TK_AGG_COLUMN;
77932             pExpr->iAgg = (i16)k;
77933             break;
77934           } /* endif pExpr->iTable==pItem->iCursor */
77935         } /* end loop over pSrcList */
77936       }
77937       return WRC_Prune;
77938     }
77939     case TK_AGG_FUNCTION: {
77940       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
77941       ** to be ignored */
77942       if( pNC->nDepth==0 ){
77943         /* Check to see if pExpr is a duplicate of another aggregate 
77944         ** function that is already in the pAggInfo structure
77945         */
77946         struct AggInfo_func *pItem = pAggInfo->aFunc;
77947         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
77948           if( sqlcipher3ExprCompare(pItem->pExpr, pExpr)==0 ){
77949             break;
77950           }
77951         }
77952         if( i>=pAggInfo->nFunc ){
77953           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
77954           */
77955           u8 enc = ENC(pParse->db);
77956           i = addAggInfoFunc(pParse->db, pAggInfo);
77957           if( i>=0 ){
77958             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77959             pItem = &pAggInfo->aFunc[i];
77960             pItem->pExpr = pExpr;
77961             pItem->iMem = ++pParse->nMem;
77962             assert( !ExprHasProperty(pExpr, EP_IntValue) );
77963             pItem->pFunc = sqlcipher3FindFunction(pParse->db,
77964                    pExpr->u.zToken, sqlcipher3Strlen30(pExpr->u.zToken),
77965                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
77966             if( pExpr->flags & EP_Distinct ){
77967               pItem->iDistinct = pParse->nTab++;
77968             }else{
77969               pItem->iDistinct = -1;
77970             }
77971           }
77972         }
77973         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
77974         */
77975         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
77976         ExprSetIrreducible(pExpr);
77977         pExpr->iAgg = (i16)i;
77978         pExpr->pAggInfo = pAggInfo;
77979         return WRC_Prune;
77980       }
77981     }
77982   }
77983   return WRC_Continue;
77984 }
77985 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
77986   NameContext *pNC = pWalker->u.pNC;
77987   if( pNC->nDepth==0 ){
77988     pNC->nDepth++;
77989     sqlcipher3WalkSelect(pWalker, pSelect);
77990     pNC->nDepth--;
77991     return WRC_Prune;
77992   }else{
77993     return WRC_Continue;
77994   }
77995 }
77996
77997 /*
77998 ** Analyze the given expression looking for aggregate functions and
77999 ** for variables that need to be added to the pParse->aAgg[] array.
78000 ** Make additional entries to the pParse->aAgg[] array as necessary.
78001 **
78002 ** This routine should only be called after the expression has been
78003 ** analyzed by sqlcipher3ResolveExprNames().
78004 */
78005 SQLCIPHER_PRIVATE void sqlcipher3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
78006   Walker w;
78007   w.xExprCallback = analyzeAggregate;
78008   w.xSelectCallback = analyzeAggregatesInSelect;
78009   w.u.pNC = pNC;
78010   assert( pNC->pSrcList!=0 );
78011   sqlcipher3WalkExpr(&w, pExpr);
78012 }
78013
78014 /*
78015 ** Call sqlcipher3ExprAnalyzeAggregates() for every expression in an
78016 ** expression list.  Return the number of errors.
78017 **
78018 ** If an error is found, the analysis is cut short.
78019 */
78020 SQLCIPHER_PRIVATE void sqlcipher3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
78021   struct ExprList_item *pItem;
78022   int i;
78023   if( pList ){
78024     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
78025       sqlcipher3ExprAnalyzeAggregates(pNC, pItem->pExpr);
78026     }
78027   }
78028 }
78029
78030 /*
78031 ** Allocate a single new register for use to hold some intermediate result.
78032 */
78033 SQLCIPHER_PRIVATE int sqlcipher3GetTempReg(Parse *pParse){
78034   if( pParse->nTempReg==0 ){
78035     return ++pParse->nMem;
78036   }
78037   return pParse->aTempReg[--pParse->nTempReg];
78038 }
78039
78040 /*
78041 ** Deallocate a register, making available for reuse for some other
78042 ** purpose.
78043 **
78044 ** If a register is currently being used by the column cache, then
78045 ** the dallocation is deferred until the column cache line that uses
78046 ** the register becomes stale.
78047 */
78048 SQLCIPHER_PRIVATE void sqlcipher3ReleaseTempReg(Parse *pParse, int iReg){
78049   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
78050     int i;
78051     struct yColCache *p;
78052     for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
78053       if( p->iReg==iReg ){
78054         p->tempReg = 1;
78055         return;
78056       }
78057     }
78058     pParse->aTempReg[pParse->nTempReg++] = iReg;
78059   }
78060 }
78061
78062 /*
78063 ** Allocate or deallocate a block of nReg consecutive registers
78064 */
78065 SQLCIPHER_PRIVATE int sqlcipher3GetTempRange(Parse *pParse, int nReg){
78066   int i, n;
78067   i = pParse->iRangeReg;
78068   n = pParse->nRangeReg;
78069   if( nReg<=n ){
78070     assert( !usedAsColumnCache(pParse, i, i+n-1) );
78071     pParse->iRangeReg += nReg;
78072     pParse->nRangeReg -= nReg;
78073   }else{
78074     i = pParse->nMem+1;
78075     pParse->nMem += nReg;
78076   }
78077   return i;
78078 }
78079 SQLCIPHER_PRIVATE void sqlcipher3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
78080   sqlcipher3ExprCacheRemove(pParse, iReg, nReg);
78081   if( nReg>pParse->nRangeReg ){
78082     pParse->nRangeReg = nReg;
78083     pParse->iRangeReg = iReg;
78084   }
78085 }
78086
78087 /************** End of expr.c ************************************************/
78088 /************** Begin file alter.c *******************************************/
78089 /*
78090 ** 2005 February 15
78091 **
78092 ** The author disclaims copyright to this source code.  In place of
78093 ** a legal notice, here is a blessing:
78094 **
78095 **    May you do good and not evil.
78096 **    May you find forgiveness for yourself and forgive others.
78097 **    May you share freely, never taking more than you give.
78098 **
78099 *************************************************************************
78100 ** This file contains C code routines that used to generate VDBE code
78101 ** that implements the ALTER TABLE command.
78102 */
78103
78104 /*
78105 ** The code in this file only exists if we are not omitting the
78106 ** ALTER TABLE logic from the build.
78107 */
78108 #ifndef SQLCIPHER_OMIT_ALTERTABLE
78109
78110
78111 /*
78112 ** This function is used by SQL generated to implement the 
78113 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
78114 ** CREATE INDEX command. The second is a table name. The table name in 
78115 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
78116 ** argument and the result returned. Examples:
78117 **
78118 ** sqlcipher_rename_table('CREATE TABLE abc(a, b, c)', 'def')
78119 **     -> 'CREATE TABLE def(a, b, c)'
78120 **
78121 ** sqlcipher_rename_table('CREATE INDEX i ON abc(a)', 'def')
78122 **     -> 'CREATE INDEX i ON def(a, b, c)'
78123 */
78124 static void renameTableFunc(
78125   sqlcipher3_context *context,
78126   int NotUsed,
78127   sqlcipher3_value **argv
78128 ){
78129   unsigned char const *zSql = sqlcipher3_value_text(argv[0]);
78130   unsigned char const *zTableName = sqlcipher3_value_text(argv[1]);
78131
78132   int token;
78133   Token tname;
78134   unsigned char const *zCsr = zSql;
78135   int len = 0;
78136   char *zRet;
78137
78138   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
78139
78140   UNUSED_PARAMETER(NotUsed);
78141
78142   /* The principle used to locate the table name in the CREATE TABLE 
78143   ** statement is that the table name is the first non-space token that
78144   ** is immediately followed by a TK_LP or TK_USING token.
78145   */
78146   if( zSql ){
78147     do {
78148       if( !*zCsr ){
78149         /* Ran out of input before finding an opening bracket. Return NULL. */
78150         return;
78151       }
78152
78153       /* Store the token that zCsr points to in tname. */
78154       tname.z = (char*)zCsr;
78155       tname.n = len;
78156
78157       /* Advance zCsr to the next token. Store that token type in 'token',
78158       ** and its length in 'len' (to be used next iteration of this loop).
78159       */
78160       do {
78161         zCsr += len;
78162         len = sqlcipher3GetToken(zCsr, &token);
78163       } while( token==TK_SPACE );
78164       assert( len>0 );
78165     } while( token!=TK_LP && token!=TK_USING );
78166
78167     zRet = sqlcipher3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
78168        zTableName, tname.z+tname.n);
78169     sqlcipher3_result_text(context, zRet, -1, SQLCIPHER_DYNAMIC);
78170   }
78171 }
78172
78173 /*
78174 ** This C function implements an SQL user function that is used by SQL code
78175 ** generated by the ALTER TABLE ... RENAME command to modify the definition
78176 ** of any foreign key constraints that use the table being renamed as the 
78177 ** parent table. It is passed three arguments:
78178 **
78179 **   1) The complete text of the CREATE TABLE statement being modified,
78180 **   2) The old name of the table being renamed, and
78181 **   3) The new name of the table being renamed.
78182 **
78183 ** It returns the new CREATE TABLE statement. For example:
78184 **
78185 **   sqlcipher_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
78186 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
78187 */
78188 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
78189 static void renameParentFunc(
78190   sqlcipher3_context *context,
78191   int NotUsed,
78192   sqlcipher3_value **argv
78193 ){
78194   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
78195   char *zOutput = 0;
78196   char *zResult;
78197   unsigned char const *zInput = sqlcipher3_value_text(argv[0]);
78198   unsigned char const *zOld = sqlcipher3_value_text(argv[1]);
78199   unsigned char const *zNew = sqlcipher3_value_text(argv[2]);
78200
78201   unsigned const char *z;         /* Pointer to token */
78202   int n;                          /* Length of token z */
78203   int token;                      /* Type of token */
78204
78205   UNUSED_PARAMETER(NotUsed);
78206   for(z=zInput; *z; z=z+n){
78207     n = sqlcipher3GetToken(z, &token);
78208     if( token==TK_REFERENCES ){
78209       char *zParent;
78210       do {
78211         z += n;
78212         n = sqlcipher3GetToken(z, &token);
78213       }while( token==TK_SPACE );
78214
78215       zParent = sqlcipher3DbStrNDup(db, (const char *)z, n);
78216       if( zParent==0 ) break;
78217       sqlcipher3Dequote(zParent);
78218       if( 0==sqlcipher3StrICmp((const char *)zOld, zParent) ){
78219         char *zOut = sqlcipher3MPrintf(db, "%s%.*s\"%w\"", 
78220             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
78221         );
78222         sqlcipher3DbFree(db, zOutput);
78223         zOutput = zOut;
78224         zInput = &z[n];
78225       }
78226       sqlcipher3DbFree(db, zParent);
78227     }
78228   }
78229
78230   zResult = sqlcipher3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
78231   sqlcipher3_result_text(context, zResult, -1, SQLCIPHER_DYNAMIC);
78232   sqlcipher3DbFree(db, zOutput);
78233 }
78234 #endif
78235
78236 #ifndef SQLCIPHER_OMIT_TRIGGER
78237 /* This function is used by SQL generated to implement the
78238 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
78239 ** statement. The second is a table name. The table name in the CREATE 
78240 ** TRIGGER statement is replaced with the third argument and the result 
78241 ** returned. This is analagous to renameTableFunc() above, except for CREATE
78242 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
78243 */
78244 static void renameTriggerFunc(
78245   sqlcipher3_context *context,
78246   int NotUsed,
78247   sqlcipher3_value **argv
78248 ){
78249   unsigned char const *zSql = sqlcipher3_value_text(argv[0]);
78250   unsigned char const *zTableName = sqlcipher3_value_text(argv[1]);
78251
78252   int token;
78253   Token tname;
78254   int dist = 3;
78255   unsigned char const *zCsr = zSql;
78256   int len = 0;
78257   char *zRet;
78258   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
78259
78260   UNUSED_PARAMETER(NotUsed);
78261
78262   /* The principle used to locate the table name in the CREATE TRIGGER 
78263   ** statement is that the table name is the first token that is immediatedly
78264   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
78265   ** of TK_WHEN, TK_BEGIN or TK_FOR.
78266   */
78267   if( zSql ){
78268     do {
78269
78270       if( !*zCsr ){
78271         /* Ran out of input before finding the table name. Return NULL. */
78272         return;
78273       }
78274
78275       /* Store the token that zCsr points to in tname. */
78276       tname.z = (char*)zCsr;
78277       tname.n = len;
78278
78279       /* Advance zCsr to the next token. Store that token type in 'token',
78280       ** and its length in 'len' (to be used next iteration of this loop).
78281       */
78282       do {
78283         zCsr += len;
78284         len = sqlcipher3GetToken(zCsr, &token);
78285       }while( token==TK_SPACE );
78286       assert( len>0 );
78287
78288       /* Variable 'dist' stores the number of tokens read since the most
78289       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
78290       ** token is read and 'dist' equals 2, the condition stated above
78291       ** to be met.
78292       **
78293       ** Note that ON cannot be a database, table or column name, so
78294       ** there is no need to worry about syntax like 
78295       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
78296       */
78297       dist++;
78298       if( token==TK_DOT || token==TK_ON ){
78299         dist = 0;
78300       }
78301     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
78302
78303     /* Variable tname now contains the token that is the old table-name
78304     ** in the CREATE TRIGGER statement.
78305     */
78306     zRet = sqlcipher3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
78307        zTableName, tname.z+tname.n);
78308     sqlcipher3_result_text(context, zRet, -1, SQLCIPHER_DYNAMIC);
78309   }
78310 }
78311 #endif   /* !SQLCIPHER_OMIT_TRIGGER */
78312
78313 /*
78314 ** Register built-in functions used to help implement ALTER TABLE
78315 */
78316 SQLCIPHER_PRIVATE void sqlcipher3AlterFunctions(void){
78317   static SQLCIPHER_WSD FuncDef aAlterTableFuncs[] = {
78318     FUNCTION(sqlcipher_rename_table,   2, 0, 0, renameTableFunc),
78319 #ifndef SQLCIPHER_OMIT_TRIGGER
78320     FUNCTION(sqlcipher_rename_trigger, 2, 0, 0, renameTriggerFunc),
78321 #endif
78322 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
78323     FUNCTION(sqlcipher_rename_parent,  3, 0, 0, renameParentFunc),
78324 #endif
78325   };
78326   int i;
78327   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlcipher3GlobalFunctions);
78328   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
78329
78330   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
78331     sqlcipher3FuncDefInsert(pHash, &aFunc[i]);
78332   }
78333 }
78334
78335 /*
78336 ** This function is used to create the text of expressions of the form:
78337 **
78338 **   name=<constant1> OR name=<constant2> OR ...
78339 **
78340 ** If argument zWhere is NULL, then a pointer string containing the text 
78341 ** "name=<constant>" is returned, where <constant> is the quoted version
78342 ** of the string passed as argument zConstant. The returned buffer is
78343 ** allocated using sqlcipher3DbMalloc(). It is the responsibility of the
78344 ** caller to ensure that it is eventually freed.
78345 **
78346 ** If argument zWhere is not NULL, then the string returned is 
78347 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
78348 ** In this case zWhere is passed to sqlcipher3DbFree() before returning.
78349 ** 
78350 */
78351 static char *whereOrName(sqlcipher3 *db, char *zWhere, char *zConstant){
78352   char *zNew;
78353   if( !zWhere ){
78354     zNew = sqlcipher3MPrintf(db, "name=%Q", zConstant);
78355   }else{
78356     zNew = sqlcipher3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
78357     sqlcipher3DbFree(db, zWhere);
78358   }
78359   return zNew;
78360 }
78361
78362 #if !defined(SQLCIPHER_OMIT_FOREIGN_KEY) && !defined(SQLCIPHER_OMIT_TRIGGER)
78363 /*
78364 ** Generate the text of a WHERE expression which can be used to select all
78365 ** tables that have foreign key constraints that refer to table pTab (i.e.
78366 ** constraints for which pTab is the parent table) from the sqlcipher_master
78367 ** table.
78368 */
78369 static char *whereForeignKeys(Parse *pParse, Table *pTab){
78370   FKey *p;
78371   char *zWhere = 0;
78372   for(p=sqlcipher3FkReferences(pTab); p; p=p->pNextTo){
78373     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
78374   }
78375   return zWhere;
78376 }
78377 #endif
78378
78379 /*
78380 ** Generate the text of a WHERE expression which can be used to select all
78381 ** temporary triggers on table pTab from the sqlcipher_temp_master table. If
78382 ** table pTab has no temporary triggers, or is itself stored in the 
78383 ** temporary database, NULL is returned.
78384 */
78385 static char *whereTempTriggers(Parse *pParse, Table *pTab){
78386   Trigger *pTrig;
78387   char *zWhere = 0;
78388   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
78389
78390   /* If the table is not located in the temp-db (in which case NULL is 
78391   ** returned, loop through the tables list of triggers. For each trigger
78392   ** that is not part of the temp-db schema, add a clause to the WHERE 
78393   ** expression being built up in zWhere.
78394   */
78395   if( pTab->pSchema!=pTempSchema ){
78396     sqlcipher3 *db = pParse->db;
78397     for(pTrig=sqlcipher3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78398       if( pTrig->pSchema==pTempSchema ){
78399         zWhere = whereOrName(db, zWhere, pTrig->zName);
78400       }
78401     }
78402   }
78403   if( zWhere ){
78404     char *zNew = sqlcipher3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
78405     sqlcipher3DbFree(pParse->db, zWhere);
78406     zWhere = zNew;
78407   }
78408   return zWhere;
78409 }
78410
78411 /*
78412 ** Generate code to drop and reload the internal representation of table
78413 ** pTab from the database, including triggers and temporary triggers.
78414 ** Argument zName is the name of the table in the database schema at
78415 ** the time the generated code is executed. This can be different from
78416 ** pTab->zName if this function is being called to code part of an 
78417 ** "ALTER TABLE RENAME TO" statement.
78418 */
78419 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
78420   Vdbe *v;
78421   char *zWhere;
78422   int iDb;                   /* Index of database containing pTab */
78423 #ifndef SQLCIPHER_OMIT_TRIGGER
78424   Trigger *pTrig;
78425 #endif
78426
78427   v = sqlcipher3GetVdbe(pParse);
78428   if( NEVER(v==0) ) return;
78429   assert( sqlcipher3BtreeHoldsAllMutexes(pParse->db) );
78430   iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
78431   assert( iDb>=0 );
78432
78433 #ifndef SQLCIPHER_OMIT_TRIGGER
78434   /* Drop any table triggers from the internal schema. */
78435   for(pTrig=sqlcipher3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78436     int iTrigDb = sqlcipher3SchemaToIndex(pParse->db, pTrig->pSchema);
78437     assert( iTrigDb==iDb || iTrigDb==1 );
78438     sqlcipher3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
78439   }
78440 #endif
78441
78442   /* Drop the table and index from the internal schema.  */
78443   sqlcipher3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
78444
78445   /* Reload the table, index and permanent trigger schemas. */
78446   zWhere = sqlcipher3MPrintf(pParse->db, "tbl_name=%Q", zName);
78447   if( !zWhere ) return;
78448   sqlcipher3VdbeAddParseSchemaOp(v, iDb, zWhere);
78449
78450 #ifndef SQLCIPHER_OMIT_TRIGGER
78451   /* Now, if the table is not stored in the temp database, reload any temp 
78452   ** triggers. Don't use IN(...) in case SQLCIPHER_OMIT_SUBQUERY is defined. 
78453   */
78454   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
78455     sqlcipher3VdbeAddParseSchemaOp(v, 1, zWhere);
78456   }
78457 #endif
78458 }
78459
78460 /*
78461 ** Parameter zName is the name of a table that is about to be altered
78462 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
78463 ** If the table is a system table, this function leaves an error message
78464 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
78465 **
78466 ** Or, if zName is not a system table, zero is returned.
78467 */
78468 static int isSystemTable(Parse *pParse, const char *zName){
78469   if( sqlcipher3Strlen30(zName)>6 && 0==sqlcipher3StrNICmp(zName, "sqlcipher_", 7) ){
78470     sqlcipher3ErrorMsg(pParse, "table %s may not be altered", zName);
78471     return 1;
78472   }
78473   return 0;
78474 }
78475
78476 /*
78477 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
78478 ** command. 
78479 */
78480 SQLCIPHER_PRIVATE void sqlcipher3AlterRenameTable(
78481   Parse *pParse,            /* Parser context. */
78482   SrcList *pSrc,            /* The table to rename. */
78483   Token *pName              /* The new table name. */
78484 ){
78485   int iDb;                  /* Database that contains the table */
78486   char *zDb;                /* Name of database iDb */
78487   Table *pTab;              /* Table being renamed */
78488   char *zName = 0;          /* NULL-terminated version of pName */ 
78489   sqlcipher3 *db = pParse->db; /* Database connection */
78490   int nTabName;             /* Number of UTF-8 characters in zTabName */
78491   const char *zTabName;     /* Original name of the table */
78492   Vdbe *v;
78493 #ifndef SQLCIPHER_OMIT_TRIGGER
78494   char *zWhere = 0;         /* Where clause to locate temp triggers */
78495 #endif
78496   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
78497   int savedDbFlags;         /* Saved value of db->flags */
78498
78499   savedDbFlags = db->flags;  
78500   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
78501   assert( pSrc->nSrc==1 );
78502   assert( sqlcipher3BtreeHoldsAllMutexes(pParse->db) );
78503
78504   pTab = sqlcipher3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
78505   if( !pTab ) goto exit_rename_table;
78506   iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
78507   zDb = db->aDb[iDb].zName;
78508   db->flags |= SQLCIPHER_PreferBuiltin;
78509
78510   /* Get a NULL terminated version of the new table name. */
78511   zName = sqlcipher3NameFromToken(db, pName);
78512   if( !zName ) goto exit_rename_table;
78513
78514   /* Check that a table or index named 'zName' does not already exist
78515   ** in database iDb. If so, this is an error.
78516   */
78517   if( sqlcipher3FindTable(db, zName, zDb) || sqlcipher3FindIndex(db, zName, zDb) ){
78518     sqlcipher3ErrorMsg(pParse, 
78519         "there is already another table or index with this name: %s", zName);
78520     goto exit_rename_table;
78521   }
78522
78523   /* Make sure it is not a system table being altered, or a reserved name
78524   ** that the table is being renamed to.
78525   */
78526   if( SQLCIPHER_OK!=isSystemTable(pParse, pTab->zName) ){
78527     goto exit_rename_table;
78528   }
78529   if( SQLCIPHER_OK!=sqlcipher3CheckObjectName(pParse, zName) ){ goto
78530     exit_rename_table;
78531   }
78532
78533 #ifndef SQLCIPHER_OMIT_VIEW
78534   if( pTab->pSelect ){
78535     sqlcipher3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
78536     goto exit_rename_table;
78537   }
78538 #endif
78539
78540 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
78541   /* Invoke the authorization callback. */
78542   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_ALTER_TABLE, zDb, pTab->zName, 0) ){
78543     goto exit_rename_table;
78544   }
78545 #endif
78546
78547 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
78548   if( sqlcipher3ViewGetColumnNames(pParse, pTab) ){
78549     goto exit_rename_table;
78550   }
78551   if( IsVirtual(pTab) ){
78552     pVTab = sqlcipher3GetVTable(db, pTab);
78553     if( pVTab->pVtab->pModule->xRename==0 ){
78554       pVTab = 0;
78555     }
78556   }
78557 #endif
78558
78559   /* Begin a transaction and code the VerifyCookie for database iDb. 
78560   ** Then modify the schema cookie (since the ALTER TABLE modifies the
78561   ** schema). Open a statement transaction if the table is a virtual
78562   ** table.
78563   */
78564   v = sqlcipher3GetVdbe(pParse);
78565   if( v==0 ){
78566     goto exit_rename_table;
78567   }
78568   sqlcipher3BeginWriteOperation(pParse, pVTab!=0, iDb);
78569   sqlcipher3ChangeCookie(pParse, iDb);
78570
78571   /* If this is a virtual table, invoke the xRename() function if
78572   ** one is defined. The xRename() callback will modify the names
78573   ** of any resources used by the v-table implementation (including other
78574   ** SQLite tables) that are identified by the name of the virtual table.
78575   */
78576 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
78577   if( pVTab ){
78578     int i = ++pParse->nMem;
78579     sqlcipher3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
78580     sqlcipher3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
78581     sqlcipher3MayAbort(pParse);
78582   }
78583 #endif
78584
78585   /* figure out how many UTF-8 characters are in zName */
78586   zTabName = pTab->zName;
78587   nTabName = sqlcipher3Utf8CharLen(zTabName, -1);
78588
78589 #if !defined(SQLCIPHER_OMIT_FOREIGN_KEY) && !defined(SQLCIPHER_OMIT_TRIGGER)
78590   if( db->flags&SQLCIPHER_ForeignKeys ){
78591     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
78592     ** statements corresponding to all child tables of foreign key constraints
78593     ** for which the renamed table is the parent table.  */
78594     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
78595       sqlcipher3NestedParse(pParse, 
78596           "UPDATE \"%w\".%s SET "
78597               "sql = sqlcipher_rename_parent(sql, %Q, %Q) "
78598               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
78599       sqlcipher3DbFree(db, zWhere);
78600     }
78601   }
78602 #endif
78603
78604   /* Modify the sqlcipher_master table to use the new table name. */
78605   sqlcipher3NestedParse(pParse,
78606       "UPDATE %Q.%s SET "
78607 #ifdef SQLCIPHER_OMIT_TRIGGER
78608           "sql = sqlcipher_rename_table(sql, %Q), "
78609 #else
78610           "sql = CASE "
78611             "WHEN type = 'trigger' THEN sqlcipher_rename_trigger(sql, %Q)"
78612             "ELSE sqlcipher_rename_table(sql, %Q) END, "
78613 #endif
78614           "tbl_name = %Q, "
78615           "name = CASE "
78616             "WHEN type='table' THEN %Q "
78617             "WHEN name LIKE 'sqlcipher_autoindex%%' AND type='index' THEN "
78618              "'sqlcipher_autoindex_' || %Q || substr(name,%d+18) "
78619             "ELSE name END "
78620       "WHERE tbl_name=%Q AND "
78621           "(type='table' OR type='index' OR type='trigger');", 
78622       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
78623 #ifndef SQLCIPHER_OMIT_TRIGGER
78624       zName,
78625 #endif
78626       zName, nTabName, zTabName
78627   );
78628
78629 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
78630   /* If the sqlcipher_sequence table exists in this database, then update 
78631   ** it with the new table name.
78632   */
78633   if( sqlcipher3FindTable(db, "sqlcipher_sequence", zDb) ){
78634     sqlcipher3NestedParse(pParse,
78635         "UPDATE \"%w\".sqlcipher_sequence set name = %Q WHERE name = %Q",
78636         zDb, zName, pTab->zName);
78637   }
78638 #endif
78639
78640 #ifndef SQLCIPHER_OMIT_TRIGGER
78641   /* If there are TEMP triggers on this table, modify the sqlcipher_temp_master
78642   ** table. Don't do this if the table being ALTERed is itself located in
78643   ** the temp database.
78644   */
78645   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
78646     sqlcipher3NestedParse(pParse, 
78647         "UPDATE sqlcipher_temp_master SET "
78648             "sql = sqlcipher_rename_trigger(sql, %Q), "
78649             "tbl_name = %Q "
78650             "WHERE %s;", zName, zName, zWhere);
78651     sqlcipher3DbFree(db, zWhere);
78652   }
78653 #endif
78654
78655 #if !defined(SQLCIPHER_OMIT_FOREIGN_KEY) && !defined(SQLCIPHER_OMIT_TRIGGER)
78656   if( db->flags&SQLCIPHER_ForeignKeys ){
78657     FKey *p;
78658     for(p=sqlcipher3FkReferences(pTab); p; p=p->pNextTo){
78659       Table *pFrom = p->pFrom;
78660       if( pFrom!=pTab ){
78661         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
78662       }
78663     }
78664   }
78665 #endif
78666
78667   /* Drop and reload the internal table schema. */
78668   reloadTableSchema(pParse, pTab, zName);
78669
78670 exit_rename_table:
78671   sqlcipher3SrcListDelete(db, pSrc);
78672   sqlcipher3DbFree(db, zName);
78673   db->flags = savedDbFlags;
78674 }
78675
78676
78677 /*
78678 ** Generate code to make sure the file format number is at least minFormat.
78679 ** The generated code will increase the file format number if necessary.
78680 */
78681 SQLCIPHER_PRIVATE void sqlcipher3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
78682   Vdbe *v;
78683   v = sqlcipher3GetVdbe(pParse);
78684   /* The VDBE should have been allocated before this routine is called.
78685   ** If that allocation failed, we would have quit before reaching this
78686   ** point */
78687   if( ALWAYS(v) ){
78688     int r1 = sqlcipher3GetTempReg(pParse);
78689     int r2 = sqlcipher3GetTempReg(pParse);
78690     int j1;
78691     sqlcipher3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
78692     sqlcipher3VdbeUsesBtree(v, iDb);
78693     sqlcipher3VdbeAddOp2(v, OP_Integer, minFormat, r2);
78694     j1 = sqlcipher3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
78695     sqlcipher3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
78696     sqlcipher3VdbeJumpHere(v, j1);
78697     sqlcipher3ReleaseTempReg(pParse, r1);
78698     sqlcipher3ReleaseTempReg(pParse, r2);
78699   }
78700 }
78701
78702 /*
78703 ** This function is called after an "ALTER TABLE ... ADD" statement
78704 ** has been parsed. Argument pColDef contains the text of the new
78705 ** column definition.
78706 **
78707 ** The Table structure pParse->pNewTable was extended to include
78708 ** the new column during parsing.
78709 */
78710 SQLCIPHER_PRIVATE void sqlcipher3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
78711   Table *pNew;              /* Copy of pParse->pNewTable */
78712   Table *pTab;              /* Table being altered */
78713   int iDb;                  /* Database number */
78714   const char *zDb;          /* Database name */
78715   const char *zTab;         /* Table name */
78716   char *zCol;               /* Null-terminated column definition */
78717   Column *pCol;             /* The new column */
78718   Expr *pDflt;              /* Default value for the new column */
78719   sqlcipher3 *db;              /* The database connection; */
78720
78721   db = pParse->db;
78722   if( pParse->nErr || db->mallocFailed ) return;
78723   pNew = pParse->pNewTable;
78724   assert( pNew );
78725
78726   assert( sqlcipher3BtreeHoldsAllMutexes(db) );
78727   iDb = sqlcipher3SchemaToIndex(db, pNew->pSchema);
78728   zDb = db->aDb[iDb].zName;
78729   zTab = &pNew->zName[19];  /* Skip the "sqlcipher_altertab_" prefix on the name */
78730   pCol = &pNew->aCol[pNew->nCol-1];
78731   pDflt = pCol->pDflt;
78732   pTab = sqlcipher3FindTable(db, zTab, zDb);
78733   assert( pTab );
78734
78735 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
78736   /* Invoke the authorization callback. */
78737   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_ALTER_TABLE, zDb, pTab->zName, 0) ){
78738     return;
78739   }
78740 #endif
78741
78742   /* If the default value for the new column was specified with a 
78743   ** literal NULL, then set pDflt to 0. This simplifies checking
78744   ** for an SQL NULL default below.
78745   */
78746   if( pDflt && pDflt->op==TK_NULL ){
78747     pDflt = 0;
78748   }
78749
78750   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
78751   ** If there is a NOT NULL constraint, then the default value for the
78752   ** column must not be NULL.
78753   */
78754   if( pCol->isPrimKey ){
78755     sqlcipher3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
78756     return;
78757   }
78758   if( pNew->pIndex ){
78759     sqlcipher3ErrorMsg(pParse, "Cannot add a UNIQUE column");
78760     return;
78761   }
78762   if( (db->flags&SQLCIPHER_ForeignKeys) && pNew->pFKey && pDflt ){
78763     sqlcipher3ErrorMsg(pParse, 
78764         "Cannot add a REFERENCES column with non-NULL default value");
78765     return;
78766   }
78767   if( pCol->notNull && !pDflt ){
78768     sqlcipher3ErrorMsg(pParse, 
78769         "Cannot add a NOT NULL column with default value NULL");
78770     return;
78771   }
78772
78773   /* Ensure the default expression is something that sqlcipher3ValueFromExpr()
78774   ** can handle (i.e. not CURRENT_TIME etc.)
78775   */
78776   if( pDflt ){
78777     sqlcipher3_value *pVal;
78778     if( sqlcipher3ValueFromExpr(db, pDflt, SQLCIPHER_UTF8, SQLCIPHER_AFF_NONE, &pVal) ){
78779       db->mallocFailed = 1;
78780       return;
78781     }
78782     if( !pVal ){
78783       sqlcipher3ErrorMsg(pParse, "Cannot add a column with non-constant default");
78784       return;
78785     }
78786     sqlcipher3ValueFree(pVal);
78787   }
78788
78789   /* Modify the CREATE TABLE statement. */
78790   zCol = sqlcipher3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
78791   if( zCol ){
78792     char *zEnd = &zCol[pColDef->n-1];
78793     int savedDbFlags = db->flags;
78794     while( zEnd>zCol && (*zEnd==';' || sqlcipher3Isspace(*zEnd)) ){
78795       *zEnd-- = '\0';
78796     }
78797     db->flags |= SQLCIPHER_PreferBuiltin;
78798     sqlcipher3NestedParse(pParse, 
78799         "UPDATE \"%w\".%s SET "
78800           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
78801         "WHERE type = 'table' AND name = %Q", 
78802       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
78803       zTab
78804     );
78805     sqlcipher3DbFree(db, zCol);
78806     db->flags = savedDbFlags;
78807   }
78808
78809   /* If the default value of the new column is NULL, then set the file
78810   ** format to 2. If the default value of the new column is not NULL,
78811   ** the file format becomes 3.
78812   */
78813   sqlcipher3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
78814
78815   /* Reload the schema of the modified table. */
78816   reloadTableSchema(pParse, pTab, pTab->zName);
78817 }
78818
78819 /*
78820 ** This function is called by the parser after the table-name in
78821 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
78822 ** pSrc is the full-name of the table being altered.
78823 **
78824 ** This routine makes a (partial) copy of the Table structure
78825 ** for the table being altered and sets Parse.pNewTable to point
78826 ** to it. Routines called by the parser as the column definition
78827 ** is parsed (i.e. sqlcipher3AddColumn()) add the new Column data to 
78828 ** the copy. The copy of the Table structure is deleted by tokenize.c 
78829 ** after parsing is finished.
78830 **
78831 ** Routine sqlcipher3AlterFinishAddColumn() will be called to complete
78832 ** coding the "ALTER TABLE ... ADD" statement.
78833 */
78834 SQLCIPHER_PRIVATE void sqlcipher3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
78835   Table *pNew;
78836   Table *pTab;
78837   Vdbe *v;
78838   int iDb;
78839   int i;
78840   int nAlloc;
78841   sqlcipher3 *db = pParse->db;
78842
78843   /* Look up the table being altered. */
78844   assert( pParse->pNewTable==0 );
78845   assert( sqlcipher3BtreeHoldsAllMutexes(db) );
78846   if( db->mallocFailed ) goto exit_begin_add_column;
78847   pTab = sqlcipher3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
78848   if( !pTab ) goto exit_begin_add_column;
78849
78850 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
78851   if( IsVirtual(pTab) ){
78852     sqlcipher3ErrorMsg(pParse, "virtual tables may not be altered");
78853     goto exit_begin_add_column;
78854   }
78855 #endif
78856
78857   /* Make sure this is not an attempt to ALTER a view. */
78858   if( pTab->pSelect ){
78859     sqlcipher3ErrorMsg(pParse, "Cannot add a column to a view");
78860     goto exit_begin_add_column;
78861   }
78862   if( SQLCIPHER_OK!=isSystemTable(pParse, pTab->zName) ){
78863     goto exit_begin_add_column;
78864   }
78865
78866   assert( pTab->addColOffset>0 );
78867   iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
78868
78869   /* Put a copy of the Table struct in Parse.pNewTable for the
78870   ** sqlcipher3AddColumn() function and friends to modify.  But modify
78871   ** the name by adding an "sqlcipher_altertab_" prefix.  By adding this
78872   ** prefix, we insure that the name will not collide with an existing
78873   ** table because user table are not allowed to have the "sqlcipher_"
78874   ** prefix on their name.
78875   */
78876   pNew = (Table*)sqlcipher3DbMallocZero(db, sizeof(Table));
78877   if( !pNew ) goto exit_begin_add_column;
78878   pParse->pNewTable = pNew;
78879   pNew->nRef = 1;
78880   pNew->nCol = pTab->nCol;
78881   assert( pNew->nCol>0 );
78882   nAlloc = (((pNew->nCol-1)/8)*8)+8;
78883   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
78884   pNew->aCol = (Column*)sqlcipher3DbMallocZero(db, sizeof(Column)*nAlloc);
78885   pNew->zName = sqlcipher3MPrintf(db, "sqlcipher_altertab_%s", pTab->zName);
78886   if( !pNew->aCol || !pNew->zName ){
78887     db->mallocFailed = 1;
78888     goto exit_begin_add_column;
78889   }
78890   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
78891   for(i=0; i<pNew->nCol; i++){
78892     Column *pCol = &pNew->aCol[i];
78893     pCol->zName = sqlcipher3DbStrDup(db, pCol->zName);
78894     pCol->zColl = 0;
78895     pCol->zType = 0;
78896     pCol->pDflt = 0;
78897     pCol->zDflt = 0;
78898   }
78899   pNew->pSchema = db->aDb[iDb].pSchema;
78900   pNew->addColOffset = pTab->addColOffset;
78901   pNew->nRef = 1;
78902
78903   /* Begin a transaction and increment the schema cookie.  */
78904   sqlcipher3BeginWriteOperation(pParse, 0, iDb);
78905   v = sqlcipher3GetVdbe(pParse);
78906   if( !v ) goto exit_begin_add_column;
78907   sqlcipher3ChangeCookie(pParse, iDb);
78908
78909 exit_begin_add_column:
78910   sqlcipher3SrcListDelete(db, pSrc);
78911   return;
78912 }
78913 #endif  /* SQLCIPHER_ALTER_TABLE */
78914
78915 /************** End of alter.c ***********************************************/
78916 /************** Begin file analyze.c *****************************************/
78917 /*
78918 ** 2005 July 8
78919 **
78920 ** The author disclaims copyright to this source code.  In place of
78921 ** a legal notice, here is a blessing:
78922 **
78923 **    May you do good and not evil.
78924 **    May you find forgiveness for yourself and forgive others.
78925 **    May you share freely, never taking more than you give.
78926 **
78927 *************************************************************************
78928 ** This file contains code associated with the ANALYZE command.
78929 **
78930 ** The ANALYZE command gather statistics about the content of tables
78931 ** and indices.  These statistics are made available to the query planner
78932 ** to help it make better decisions about how to perform queries.
78933 **
78934 ** The following system tables are or have been supported:
78935 **
78936 **    CREATE TABLE sqlcipher_stat1(tbl, idx, stat);
78937 **    CREATE TABLE sqlcipher_stat2(tbl, idx, sampleno, sample);
78938 **    CREATE TABLE sqlcipher_stat3(tbl, idx, nEq, nLt, nDLt, sample);
78939 **
78940 ** Additional tables might be added in future releases of SQLite.
78941 ** The sqlcipher_stat2 table is not created or used unless the SQLite version
78942 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
78943 ** with SQLCIPHER_ENABLE_STAT2.  The sqlcipher_stat2 table is deprecated.
78944 ** The sqlcipher_stat2 table is superceded by sqlcipher_stat3, which is only
78945 ** created and used by SQLite versions 3.7.9 and later and with
78946 ** SQLCIPHER_ENABLE_STAT3 defined.  The fucntionality of sqlcipher_stat3
78947 ** is a superset of sqlcipher_stat2.  
78948 **
78949 ** Format of sqlcipher_stat1:
78950 **
78951 ** There is normally one row per index, with the index identified by the
78952 ** name in the idx column.  The tbl column is the name of the table to
78953 ** which the index belongs.  In each such row, the stat column will be
78954 ** a string consisting of a list of integers.  The first integer in this
78955 ** list is the number of rows in the index and in the table.  The second
78956 ** integer is the average number of rows in the index that have the same
78957 ** value in the first column of the index.  The third integer is the average
78958 ** number of rows in the index that have the same value for the first two
78959 ** columns.  The N-th integer (for N>1) is the average number of rows in 
78960 ** the index which have the same value for the first N-1 columns.  For
78961 ** a K-column index, there will be K+1 integers in the stat column.  If
78962 ** the index is unique, then the last integer will be 1.
78963 **
78964 ** The list of integers in the stat column can optionally be followed
78965 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
78966 ** must be separated from the last integer by a single space.  If the
78967 ** "unordered" keyword is present, then the query planner assumes that
78968 ** the index is unordered and will not use the index for a range query.
78969 ** 
78970 ** If the sqlcipher_stat1.idx column is NULL, then the sqlcipher_stat1.stat
78971 ** column contains a single integer which is the (estimated) number of
78972 ** rows in the table identified by sqlcipher_stat1.tbl.
78973 **
78974 ** Format of sqlcipher_stat2:
78975 **
78976 ** The sqlcipher_stat2 is only created and is only used if SQLite is compiled
78977 ** with SQLCIPHER_ENABLE_STAT2 and if the SQLite version number is between
78978 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
78979 ** about the distribution of keys within an index.  The index is identified by
78980 ** the "idx" column and the "tbl" column is the name of the table to which
78981 ** the index belongs.  There are usually 10 rows in the sqlcipher_stat2
78982 ** table for each index.
78983 **
78984 ** The sqlcipher_stat2 entries for an index that have sampleno between 0 and 9
78985 ** inclusive are samples of the left-most key value in the index taken at
78986 ** evenly spaced points along the index.  Let the number of samples be S
78987 ** (10 in the standard build) and let C be the number of rows in the index.
78988 ** Then the sampled rows are given by:
78989 **
78990 **     rownumber = (i*C*2 + C)/(S*2)
78991 **
78992 ** For i between 0 and S-1.  Conceptually, the index space is divided into
78993 ** S uniform buckets and the samples are the middle row from each bucket.
78994 **
78995 ** The format for sqlcipher_stat2 is recorded here for legacy reference.  This
78996 ** version of SQLite does not support sqlcipher_stat2.  It neither reads nor
78997 ** writes the sqlcipher_stat2 table.  This version of SQLite only supports
78998 ** sqlcipher_stat3.
78999 **
79000 ** Format for sqlcipher_stat3:
79001 **
79002 ** The sqlcipher_stat3 is an enhancement to sqlcipher_stat2.  A new name is
79003 ** used to avoid compatibility problems.  
79004 **
79005 ** The format of the sqlcipher_stat3 table is similar to the format of
79006 ** the sqlcipher_stat2 table.  There are multiple entries for each index.
79007 ** The idx column names the index and the tbl column is the table of the
79008 ** index.  If the idx and tbl columns are the same, then the sample is
79009 ** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
79010 ** the left-most column of the index.  The nEq column is the approximate
79011 ** number of entires in the index whose left-most column exactly matches
79012 ** the sample.  nLt is the approximate number of entires whose left-most
79013 ** column is less than the sample.  The nDLt column is the approximate
79014 ** number of distinct left-most entries in the index that are less than
79015 ** the sample.
79016 **
79017 ** Future versions of SQLite might change to store a string containing
79018 ** multiple integers values in the nDLt column of sqlcipher_stat3.  The first
79019 ** integer will be the number of prior index entires that are distinct in
79020 ** the left-most column.  The second integer will be the number of prior index
79021 ** entries that are distinct in the first two columns.  The third integer
79022 ** will be the number of prior index entries that are distinct in the first
79023 ** three columns.  And so forth.  With that extension, the nDLt field is
79024 ** similar in function to the sqlcipher_stat1.stat field.
79025 **
79026 ** There can be an arbitrary number of sqlcipher_stat3 entries per index.
79027 ** The ANALYZE command will typically generate sqlcipher_stat3 tables
79028 ** that contain between 10 and 40 samples which are distributed across
79029 ** the key space, though not uniformly, and which include samples with
79030 ** largest possible nEq values.
79031 */
79032 #ifndef SQLCIPHER_OMIT_ANALYZE
79033
79034 /*
79035 ** This routine generates code that opens the sqlcipher_stat1 table for
79036 ** writing with cursor iStatCur. If the library was built with the
79037 ** SQLCIPHER_ENABLE_STAT3 macro defined, then the sqlcipher_stat3 table is
79038 ** opened for writing using cursor (iStatCur+1)
79039 **
79040 ** If the sqlcipher_stat1 tables does not previously exist, it is created.
79041 ** Similarly, if the sqlcipher_stat3 table does not exist and the library
79042 ** is compiled with SQLCIPHER_ENABLE_STAT3 defined, it is created. 
79043 **
79044 ** Argument zWhere may be a pointer to a buffer containing a table name,
79045 ** or it may be a NULL pointer. If it is not NULL, then all entries in
79046 ** the sqlcipher_stat1 and (if applicable) sqlcipher_stat3 tables associated
79047 ** with the named table are deleted. If zWhere==0, then code is generated
79048 ** to delete all stat table entries.
79049 */
79050 static void openStatTable(
79051   Parse *pParse,          /* Parsing context */
79052   int iDb,                /* The database we are looking in */
79053   int iStatCur,           /* Open the sqlcipher_stat1 table on this cursor */
79054   const char *zWhere,     /* Delete entries for this table or index */
79055   const char *zWhereType  /* Either "tbl" or "idx" */
79056 ){
79057   static const struct {
79058     const char *zName;
79059     const char *zCols;
79060   } aTable[] = {
79061     { "sqlcipher_stat1", "tbl,idx,stat" },
79062 #ifdef SQLCIPHER_ENABLE_STAT3
79063     { "sqlcipher_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
79064 #endif
79065   };
79066
79067   int aRoot[] = {0, 0};
79068   u8 aCreateTbl[] = {0, 0};
79069
79070   int i;
79071   sqlcipher3 *db = pParse->db;
79072   Db *pDb;
79073   Vdbe *v = sqlcipher3GetVdbe(pParse);
79074   if( v==0 ) return;
79075   assert( sqlcipher3BtreeHoldsAllMutexes(db) );
79076   assert( sqlcipher3VdbeDb(v)==db );
79077   pDb = &db->aDb[iDb];
79078
79079   /* Create new statistic tables if they do not exist, or clear them
79080   ** if they do already exist.
79081   */
79082   for(i=0; i<ArraySize(aTable); i++){
79083     const char *zTab = aTable[i].zName;
79084     Table *pStat;
79085     if( (pStat = sqlcipher3FindTable(db, zTab, pDb->zName))==0 ){
79086       /* The sqlcipher_stat[12] table does not exist. Create it. Note that a 
79087       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
79088       ** of the new table in register pParse->regRoot. This is important 
79089       ** because the OpenWrite opcode below will be needing it. */
79090       sqlcipher3NestedParse(pParse,
79091           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
79092       );
79093       aRoot[i] = pParse->regRoot;
79094       aCreateTbl[i] = 1;
79095     }else{
79096       /* The table already exists. If zWhere is not NULL, delete all entries 
79097       ** associated with the table zWhere. If zWhere is NULL, delete the
79098       ** entire contents of the table. */
79099       aRoot[i] = pStat->tnum;
79100       sqlcipher3TableLock(pParse, iDb, aRoot[i], 1, zTab);
79101       if( zWhere ){
79102         sqlcipher3NestedParse(pParse,
79103            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
79104         );
79105       }else{
79106         /* The sqlcipher_stat[12] table already exists.  Delete all rows. */
79107         sqlcipher3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
79108       }
79109     }
79110   }
79111
79112   /* Open the sqlcipher_stat[13] tables for writing. */
79113   for(i=0; i<ArraySize(aTable); i++){
79114     sqlcipher3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
79115     sqlcipher3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
79116     sqlcipher3VdbeChangeP5(v, aCreateTbl[i]);
79117   }
79118 }
79119
79120 /*
79121 ** Recommended number of samples for sqlcipher_stat3
79122 */
79123 #ifndef SQLCIPHER_STAT3_SAMPLES
79124 # define SQLCIPHER_STAT3_SAMPLES 24
79125 #endif
79126
79127 /*
79128 ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
79129 ** share an instance of the following structure to hold their state
79130 ** information.
79131 */
79132 typedef struct Stat3Accum Stat3Accum;
79133 struct Stat3Accum {
79134   tRowcnt nRow;             /* Number of rows in the entire table */
79135   tRowcnt nPSample;         /* How often to do a periodic sample */
79136   int iMin;                 /* Index of entry with minimum nEq and hash */
79137   int mxSample;             /* Maximum number of samples to accumulate */
79138   int nSample;              /* Current number of samples */
79139   u32 iPrn;                 /* Pseudo-random number used for sampling */
79140   struct Stat3Sample {
79141     i64 iRowid;                /* Rowid in main table of the key */
79142     tRowcnt nEq;               /* sqlcipher_stat3.nEq */
79143     tRowcnt nLt;               /* sqlcipher_stat3.nLt */
79144     tRowcnt nDLt;              /* sqlcipher_stat3.nDLt */
79145     u8 isPSample;              /* True if a periodic sample */
79146     u32 iHash;                 /* Tiebreaker hash */
79147   } *a;                     /* An array of samples */
79148 };
79149
79150 #ifdef SQLCIPHER_ENABLE_STAT3
79151 /*
79152 ** Implementation of the stat3_init(C,S) SQL function.  The two parameters
79153 ** are the number of rows in the table or index (C) and the number of samples
79154 ** to accumulate (S).
79155 **
79156 ** This routine allocates the Stat3Accum object.
79157 **
79158 ** The return value is the Stat3Accum object (P).
79159 */
79160 static void stat3Init(
79161   sqlcipher3_context *context,
79162   int argc,
79163   sqlcipher3_value **argv
79164 ){
79165   Stat3Accum *p;
79166   tRowcnt nRow;
79167   int mxSample;
79168   int n;
79169
79170   UNUSED_PARAMETER(argc);
79171   nRow = (tRowcnt)sqlcipher3_value_int64(argv[0]);
79172   mxSample = sqlcipher3_value_int(argv[1]);
79173   n = sizeof(*p) + sizeof(p->a[0])*mxSample;
79174   p = sqlcipher3_malloc( n );
79175   if( p==0 ){
79176     sqlcipher3_result_error_nomem(context);
79177     return;
79178   }
79179   memset(p, 0, n);
79180   p->a = (struct Stat3Sample*)&p[1];
79181   p->nRow = nRow;
79182   p->mxSample = mxSample;
79183   p->nPSample = p->nRow/(mxSample/3+1) + 1;
79184   sqlcipher3_randomness(sizeof(p->iPrn), &p->iPrn);
79185   sqlcipher3_result_blob(context, p, sizeof(p), sqlcipher3_free);
79186 }
79187 static const FuncDef stat3InitFuncdef = {
79188   2,                /* nArg */
79189   SQLCIPHER_UTF8,      /* iPrefEnc */
79190   0,                /* flags */
79191   0,                /* pUserData */
79192   0,                /* pNext */
79193   stat3Init,        /* xFunc */
79194   0,                /* xStep */
79195   0,                /* xFinalize */
79196   "stat3_init",     /* zName */
79197   0,                /* pHash */
79198   0                 /* pDestructor */
79199 };
79200
79201
79202 /*
79203 ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
79204 ** arguments describe a single key instance.  This routine makes the 
79205 ** decision about whether or not to retain this key for the sqlcipher_stat3
79206 ** table.
79207 **
79208 ** The return value is NULL.
79209 */
79210 static void stat3Push(
79211   sqlcipher3_context *context,
79212   int argc,
79213   sqlcipher3_value **argv
79214 ){
79215   Stat3Accum *p = (Stat3Accum*)sqlcipher3_value_blob(argv[4]);
79216   tRowcnt nEq = sqlcipher3_value_int64(argv[0]);
79217   tRowcnt nLt = sqlcipher3_value_int64(argv[1]);
79218   tRowcnt nDLt = sqlcipher3_value_int64(argv[2]);
79219   i64 rowid = sqlcipher3_value_int64(argv[3]);
79220   u8 isPSample = 0;
79221   u8 doInsert = 0;
79222   int iMin = p->iMin;
79223   struct Stat3Sample *pSample;
79224   int i;
79225   u32 h;
79226
79227   UNUSED_PARAMETER(context);
79228   UNUSED_PARAMETER(argc);
79229   if( nEq==0 ) return;
79230   h = p->iPrn = p->iPrn*1103515245 + 12345;
79231   if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
79232     doInsert = isPSample = 1;
79233   }else if( p->nSample<p->mxSample ){
79234     doInsert = 1;
79235   }else{
79236     if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
79237       doInsert = 1;
79238     }
79239   }
79240   if( !doInsert ) return;
79241   if( p->nSample==p->mxSample ){
79242     assert( p->nSample - iMin - 1 >= 0 );
79243     memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
79244     pSample = &p->a[p->nSample-1];
79245   }else{
79246     pSample = &p->a[p->nSample++];
79247   }
79248   pSample->iRowid = rowid;
79249   pSample->nEq = nEq;
79250   pSample->nLt = nLt;
79251   pSample->nDLt = nDLt;
79252   pSample->iHash = h;
79253   pSample->isPSample = isPSample;
79254
79255   /* Find the new minimum */
79256   if( p->nSample==p->mxSample ){
79257     pSample = p->a;
79258     i = 0;
79259     while( pSample->isPSample ){
79260       i++;
79261       pSample++;
79262       assert( i<p->nSample );
79263     }
79264     nEq = pSample->nEq;
79265     h = pSample->iHash;
79266     iMin = i;
79267     for(i++, pSample++; i<p->nSample; i++, pSample++){
79268       if( pSample->isPSample ) continue;
79269       if( pSample->nEq<nEq
79270        || (pSample->nEq==nEq && pSample->iHash<h)
79271       ){
79272         iMin = i;
79273         nEq = pSample->nEq;
79274         h = pSample->iHash;
79275       }
79276     }
79277     p->iMin = iMin;
79278   }
79279 }
79280 static const FuncDef stat3PushFuncdef = {
79281   5,                /* nArg */
79282   SQLCIPHER_UTF8,      /* iPrefEnc */
79283   0,                /* flags */
79284   0,                /* pUserData */
79285   0,                /* pNext */
79286   stat3Push,        /* xFunc */
79287   0,                /* xStep */
79288   0,                /* xFinalize */
79289   "stat3_push",     /* zName */
79290   0,                /* pHash */
79291   0                 /* pDestructor */
79292 };
79293
79294 /*
79295 ** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
79296 ** used to query the results.  Content is returned for the Nth sqlcipher_stat3
79297 ** row where N is between 0 and S-1 and S is the number of samples.  The
79298 ** value returned depends on the number of arguments.
79299 **
79300 **   argc==2    result:  rowid
79301 **   argc==3    result:  nEq
79302 **   argc==4    result:  nLt
79303 **   argc==5    result:  nDLt
79304 */
79305 static void stat3Get(
79306   sqlcipher3_context *context,
79307   int argc,
79308   sqlcipher3_value **argv
79309 ){
79310   int n = sqlcipher3_value_int(argv[1]);
79311   Stat3Accum *p = (Stat3Accum*)sqlcipher3_value_blob(argv[0]);
79312
79313   assert( p!=0 );
79314   if( p->nSample<=n ) return;
79315   switch( argc ){
79316     case 2:  sqlcipher3_result_int64(context, p->a[n].iRowid); break;
79317     case 3:  sqlcipher3_result_int64(context, p->a[n].nEq);    break;
79318     case 4:  sqlcipher3_result_int64(context, p->a[n].nLt);    break;
79319     default: sqlcipher3_result_int64(context, p->a[n].nDLt);   break;
79320   }
79321 }
79322 static const FuncDef stat3GetFuncdef = {
79323   -1,               /* nArg */
79324   SQLCIPHER_UTF8,      /* iPrefEnc */
79325   0,                /* flags */
79326   0,                /* pUserData */
79327   0,                /* pNext */
79328   stat3Get,         /* xFunc */
79329   0,                /* xStep */
79330   0,                /* xFinalize */
79331   "stat3_get",     /* zName */
79332   0,                /* pHash */
79333   0                 /* pDestructor */
79334 };
79335 #endif /* SQLCIPHER_ENABLE_STAT3 */
79336
79337
79338
79339
79340 /*
79341 ** Generate code to do an analysis of all indices associated with
79342 ** a single table.
79343 */
79344 static void analyzeOneTable(
79345   Parse *pParse,   /* Parser context */
79346   Table *pTab,     /* Table whose indices are to be analyzed */
79347   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
79348   int iStatCur,    /* Index of VdbeCursor that writes the sqlcipher_stat1 table */
79349   int iMem         /* Available memory locations begin here */
79350 ){
79351   sqlcipher3 *db = pParse->db;    /* Database handle */
79352   Index *pIdx;                 /* An index to being analyzed */
79353   int iIdxCur;                 /* Cursor open on index being analyzed */
79354   Vdbe *v;                     /* The virtual machine being built up */
79355   int i;                       /* Loop counter */
79356   int topOfLoop;               /* The top of the loop */
79357   int endOfLoop;               /* The end of the loop */
79358   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
79359   int iDb;                     /* Index of database containing pTab */
79360   int regTabname = iMem++;     /* Register containing table name */
79361   int regIdxname = iMem++;     /* Register containing index name */
79362   int regStat1 = iMem++;       /* The stat column of sqlcipher_stat1 */
79363 #ifdef SQLCIPHER_ENABLE_STAT3
79364   int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
79365   int regNumLt = iMem++;       /* Number of keys less than regSample */
79366   int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
79367   int regSample = iMem++;      /* The next sample value */
79368   int regRowid = regSample;    /* Rowid of a sample */
79369   int regAccum = iMem++;       /* Register to hold Stat3Accum object */
79370   int regLoop = iMem++;        /* Loop counter */
79371   int regCount = iMem++;       /* Number of rows in the table or index */
79372   int regTemp1 = iMem++;       /* Intermediate register */
79373   int regTemp2 = iMem++;       /* Intermediate register */
79374   int once = 1;                /* One-time initialization */
79375   int shortJump = 0;           /* Instruction address */
79376   int iTabCur = pParse->nTab++; /* Table cursor */
79377 #endif
79378   int regCol = iMem++;         /* Content of a column in analyzed table */
79379   int regRec = iMem++;         /* Register holding completed record */
79380   int regTemp = iMem++;        /* Temporary use register */
79381   int regNewRowid = iMem++;    /* Rowid for the inserted record */
79382
79383
79384   v = sqlcipher3GetVdbe(pParse);
79385   if( v==0 || NEVER(pTab==0) ){
79386     return;
79387   }
79388   if( pTab->tnum==0 ){
79389     /* Do not gather statistics on views or virtual tables */
79390     return;
79391   }
79392   if( memcmp(pTab->zName, "sqlcipher_", 7)==0 ){
79393     /* Do not gather statistics on system tables */
79394     return;
79395   }
79396   assert( sqlcipher3BtreeHoldsAllMutexes(db) );
79397   iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
79398   assert( iDb>=0 );
79399   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
79400 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
79401   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_ANALYZE, pTab->zName, 0,
79402       db->aDb[iDb].zName ) ){
79403     return;
79404   }
79405 #endif
79406
79407   /* Establish a read-lock on the table at the shared-cache level. */
79408   sqlcipher3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
79409
79410   iIdxCur = pParse->nTab++;
79411   sqlcipher3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
79412   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79413     int nCol;
79414     KeyInfo *pKey;
79415     int addrIfNot = 0;           /* address of OP_IfNot */
79416     int *aChngAddr;              /* Array of jump instruction addresses */
79417
79418     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
79419     VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
79420     nCol = pIdx->nColumn;
79421     aChngAddr = sqlcipher3DbMallocRaw(db, sizeof(int)*nCol);
79422     if( aChngAddr==0 ) continue;
79423     pKey = sqlcipher3IndexKeyinfo(pParse, pIdx);
79424     if( iMem+1+(nCol*2)>pParse->nMem ){
79425       pParse->nMem = iMem+1+(nCol*2);
79426     }
79427
79428     /* Open a cursor to the index to be analyzed. */
79429     assert( iDb==sqlcipher3SchemaToIndex(db, pIdx->pSchema) );
79430     sqlcipher3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
79431         (char *)pKey, P4_KEYINFO_HANDOFF);
79432     VdbeComment((v, "%s", pIdx->zName));
79433
79434     /* Populate the register containing the index name. */
79435     sqlcipher3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
79436
79437 #ifdef SQLCIPHER_ENABLE_STAT3
79438     if( once ){
79439       once = 0;
79440       sqlcipher3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
79441     }
79442     sqlcipher3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
79443     sqlcipher3VdbeAddOp2(v, OP_Integer, SQLCIPHER_STAT3_SAMPLES, regTemp1);
79444     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
79445     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
79446     sqlcipher3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
79447     sqlcipher3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
79448                       (char*)&stat3InitFuncdef, P4_FUNCDEF);
79449     sqlcipher3VdbeChangeP5(v, 2);
79450 #endif /* SQLCIPHER_ENABLE_STAT3 */
79451
79452     /* The block of memory cells initialized here is used as follows.
79453     **
79454     **    iMem:                
79455     **        The total number of rows in the table.
79456     **
79457     **    iMem+1 .. iMem+nCol: 
79458     **        Number of distinct entries in index considering the 
79459     **        left-most N columns only, where N is between 1 and nCol, 
79460     **        inclusive.
79461     **
79462     **    iMem+nCol+1 .. Mem+2*nCol:  
79463     **        Previous value of indexed columns, from left to right.
79464     **
79465     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
79466     ** initialized to contain an SQL NULL.
79467     */
79468     for(i=0; i<=nCol; i++){
79469       sqlcipher3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
79470     }
79471     for(i=0; i<nCol; i++){
79472       sqlcipher3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
79473     }
79474
79475     /* Start the analysis loop. This loop runs through all the entries in
79476     ** the index b-tree.  */
79477     endOfLoop = sqlcipher3VdbeMakeLabel(v);
79478     sqlcipher3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
79479     topOfLoop = sqlcipher3VdbeCurrentAddr(v);
79480     sqlcipher3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
79481
79482     for(i=0; i<nCol; i++){
79483       CollSeq *pColl;
79484       sqlcipher3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
79485       if( i==0 ){
79486         /* Always record the very first row */
79487         addrIfNot = sqlcipher3VdbeAddOp1(v, OP_IfNot, iMem+1);
79488       }
79489       assert( pIdx->azColl!=0 );
79490       assert( pIdx->azColl[i]!=0 );
79491       pColl = sqlcipher3LocateCollSeq(pParse, pIdx->azColl[i]);
79492       aChngAddr[i] = sqlcipher3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
79493                                       (char*)pColl, P4_COLLSEQ);
79494       sqlcipher3VdbeChangeP5(v, SQLCIPHER_NULLEQ);
79495       VdbeComment((v, "jump if column %d changed", i));
79496 #ifdef SQLCIPHER_ENABLE_STAT3
79497       if( i==0 ){
79498         sqlcipher3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
79499         VdbeComment((v, "incr repeat count"));
79500       }
79501 #endif
79502     }
79503     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
79504     for(i=0; i<nCol; i++){
79505       sqlcipher3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
79506       if( i==0 ){
79507         sqlcipher3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
79508 #ifdef SQLCIPHER_ENABLE_STAT3
79509         sqlcipher3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79510                           (char*)&stat3PushFuncdef, P4_FUNCDEF);
79511         sqlcipher3VdbeChangeP5(v, 5);
79512         sqlcipher3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
79513         sqlcipher3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
79514         sqlcipher3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
79515         sqlcipher3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
79516 #endif        
79517       }
79518       sqlcipher3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
79519       sqlcipher3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
79520     }
79521     sqlcipher3DbFree(db, aChngAddr);
79522
79523     /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
79524     sqlcipher3VdbeResolveLabel(v, endOfLoop);
79525
79526     sqlcipher3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
79527     sqlcipher3VdbeAddOp1(v, OP_Close, iIdxCur);
79528 #ifdef SQLCIPHER_ENABLE_STAT3
79529     sqlcipher3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79530                       (char*)&stat3PushFuncdef, P4_FUNCDEF);
79531     sqlcipher3VdbeChangeP5(v, 5);
79532     sqlcipher3VdbeAddOp2(v, OP_Integer, -1, regLoop);
79533     shortJump = 
79534     sqlcipher3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
79535     sqlcipher3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
79536                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79537     sqlcipher3VdbeChangeP5(v, 2);
79538     sqlcipher3VdbeAddOp1(v, OP_IsNull, regTemp1);
79539     sqlcipher3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
79540     sqlcipher3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
79541     sqlcipher3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
79542     sqlcipher3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
79543                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79544     sqlcipher3VdbeChangeP5(v, 3);
79545     sqlcipher3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
79546                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79547     sqlcipher3VdbeChangeP5(v, 4);
79548     sqlcipher3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
79549                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79550     sqlcipher3VdbeChangeP5(v, 5);
79551     sqlcipher3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
79552     sqlcipher3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
79553     sqlcipher3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
79554     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, shortJump);
79555     sqlcipher3VdbeJumpHere(v, shortJump+2);
79556 #endif        
79557
79558     /* Store the results in sqlcipher_stat1.
79559     **
79560     ** The result is a single row of the sqlcipher_stat1 table.  The first
79561     ** two columns are the names of the table and index.  The third column
79562     ** is a string composed of a list of integer statistics about the
79563     ** index.  The first integer in the list is the total number of entries
79564     ** in the index.  There is one additional integer in the list for each
79565     ** column of the table.  This additional integer is a guess of how many
79566     ** rows of the table the index will select.  If D is the count of distinct
79567     ** values and K is the total number of rows, then the integer is computed
79568     ** as:
79569     **
79570     **        I = (K+D-1)/D
79571     **
79572     ** If K==0 then no entry is made into the sqlcipher_stat1 table.  
79573     ** If K>0 then it is always the case the D>0 so division by zero
79574     ** is never possible.
79575     */
79576     sqlcipher3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
79577     if( jZeroRows<0 ){
79578       jZeroRows = sqlcipher3VdbeAddOp1(v, OP_IfNot, iMem);
79579     }
79580     for(i=0; i<nCol; i++){
79581       sqlcipher3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
79582       sqlcipher3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79583       sqlcipher3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
79584       sqlcipher3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
79585       sqlcipher3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
79586       sqlcipher3VdbeAddOp1(v, OP_ToInt, regTemp);
79587       sqlcipher3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79588     }
79589     sqlcipher3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79590     sqlcipher3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79591     sqlcipher3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79592     sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
79593   }
79594
79595   /* If the table has no indices, create a single sqlcipher_stat1 entry
79596   ** containing NULL as the index name and the row count as the content.
79597   */
79598   if( pTab->pIndex==0 ){
79599     sqlcipher3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
79600     VdbeComment((v, "%s", pTab->zName));
79601     sqlcipher3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
79602     sqlcipher3VdbeAddOp1(v, OP_Close, iIdxCur);
79603     jZeroRows = sqlcipher3VdbeAddOp1(v, OP_IfNot, regStat1);
79604   }else{
79605     sqlcipher3VdbeJumpHere(v, jZeroRows);
79606     jZeroRows = sqlcipher3VdbeAddOp0(v, OP_Goto);
79607   }
79608   sqlcipher3VdbeAddOp2(v, OP_Null, 0, regIdxname);
79609   sqlcipher3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79610   sqlcipher3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79611   sqlcipher3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79612   sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
79613   if( pParse->nMem<regRec ) pParse->nMem = regRec;
79614   sqlcipher3VdbeJumpHere(v, jZeroRows);
79615 }
79616
79617
79618 /*
79619 ** Generate code that will cause the most recent index analysis to
79620 ** be loaded into internal hash tables where is can be used.
79621 */
79622 static void loadAnalysis(Parse *pParse, int iDb){
79623   Vdbe *v = sqlcipher3GetVdbe(pParse);
79624   if( v ){
79625     sqlcipher3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
79626   }
79627 }
79628
79629 /*
79630 ** Generate code that will do an analysis of an entire database
79631 */
79632 static void analyzeDatabase(Parse *pParse, int iDb){
79633   sqlcipher3 *db = pParse->db;
79634   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
79635   HashElem *k;
79636   int iStatCur;
79637   int iMem;
79638
79639   sqlcipher3BeginWriteOperation(pParse, 0, iDb);
79640   iStatCur = pParse->nTab;
79641   pParse->nTab += 3;
79642   openStatTable(pParse, iDb, iStatCur, 0, 0);
79643   iMem = pParse->nMem+1;
79644   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
79645   for(k=sqlcipherHashFirst(&pSchema->tblHash); k; k=sqlcipherHashNext(k)){
79646     Table *pTab = (Table*)sqlcipherHashData(k);
79647     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
79648   }
79649   loadAnalysis(pParse, iDb);
79650 }
79651
79652 /*
79653 ** Generate code that will do an analysis of a single table in
79654 ** a database.  If pOnlyIdx is not NULL then it is a single index
79655 ** in pTab that should be analyzed.
79656 */
79657 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
79658   int iDb;
79659   int iStatCur;
79660
79661   assert( pTab!=0 );
79662   assert( sqlcipher3BtreeHoldsAllMutexes(pParse->db) );
79663   iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
79664   sqlcipher3BeginWriteOperation(pParse, 0, iDb);
79665   iStatCur = pParse->nTab;
79666   pParse->nTab += 3;
79667   if( pOnlyIdx ){
79668     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
79669   }else{
79670     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
79671   }
79672   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
79673   loadAnalysis(pParse, iDb);
79674 }
79675
79676 /*
79677 ** Generate code for the ANALYZE command.  The parser calls this routine
79678 ** when it recognizes an ANALYZE command.
79679 **
79680 **        ANALYZE                            -- 1
79681 **        ANALYZE  <database>                -- 2
79682 **        ANALYZE  ?<database>.?<tablename>  -- 3
79683 **
79684 ** Form 1 causes all indices in all attached databases to be analyzed.
79685 ** Form 2 analyzes all indices the single database named.
79686 ** Form 3 analyzes all indices associated with the named table.
79687 */
79688 SQLCIPHER_PRIVATE void sqlcipher3Analyze(Parse *pParse, Token *pName1, Token *pName2){
79689   sqlcipher3 *db = pParse->db;
79690   int iDb;
79691   int i;
79692   char *z, *zDb;
79693   Table *pTab;
79694   Index *pIdx;
79695   Token *pTableName;
79696
79697   /* Read the database schema. If an error occurs, leave an error message
79698   ** and code in pParse and return NULL. */
79699   assert( sqlcipher3BtreeHoldsAllMutexes(pParse->db) );
79700   if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
79701     return;
79702   }
79703
79704   assert( pName2!=0 || pName1==0 );
79705   if( pName1==0 ){
79706     /* Form 1:  Analyze everything */
79707     for(i=0; i<db->nDb; i++){
79708       if( i==1 ) continue;  /* Do not analyze the TEMP database */
79709       analyzeDatabase(pParse, i);
79710     }
79711   }else if( pName2->n==0 ){
79712     /* Form 2:  Analyze the database or table named */
79713     iDb = sqlcipher3FindDb(db, pName1);
79714     if( iDb>=0 ){
79715       analyzeDatabase(pParse, iDb);
79716     }else{
79717       z = sqlcipher3NameFromToken(db, pName1);
79718       if( z ){
79719         if( (pIdx = sqlcipher3FindIndex(db, z, 0))!=0 ){
79720           analyzeTable(pParse, pIdx->pTable, pIdx);
79721         }else if( (pTab = sqlcipher3LocateTable(pParse, 0, z, 0))!=0 ){
79722           analyzeTable(pParse, pTab, 0);
79723         }
79724         sqlcipher3DbFree(db, z);
79725       }
79726     }
79727   }else{
79728     /* Form 3: Analyze the fully qualified table name */
79729     iDb = sqlcipher3TwoPartName(pParse, pName1, pName2, &pTableName);
79730     if( iDb>=0 ){
79731       zDb = db->aDb[iDb].zName;
79732       z = sqlcipher3NameFromToken(db, pTableName);
79733       if( z ){
79734         if( (pIdx = sqlcipher3FindIndex(db, z, zDb))!=0 ){
79735           analyzeTable(pParse, pIdx->pTable, pIdx);
79736         }else if( (pTab = sqlcipher3LocateTable(pParse, 0, z, zDb))!=0 ){
79737           analyzeTable(pParse, pTab, 0);
79738         }
79739         sqlcipher3DbFree(db, z);
79740       }
79741     }   
79742   }
79743 }
79744
79745 /*
79746 ** Used to pass information from the analyzer reader through to the
79747 ** callback routine.
79748 */
79749 typedef struct analysisInfo analysisInfo;
79750 struct analysisInfo {
79751   sqlcipher3 *db;
79752   const char *zDatabase;
79753 };
79754
79755 /*
79756 ** This callback is invoked once for each index when reading the
79757 ** sqlcipher_stat1 table.  
79758 **
79759 **     argv[0] = name of the table
79760 **     argv[1] = name of the index (might be NULL)
79761 **     argv[2] = results of analysis - on integer for each column
79762 **
79763 ** Entries for which argv[1]==NULL simply record the number of rows in
79764 ** the table.
79765 */
79766 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
79767   analysisInfo *pInfo = (analysisInfo*)pData;
79768   Index *pIndex;
79769   Table *pTable;
79770   int i, c, n;
79771   tRowcnt v;
79772   const char *z;
79773
79774   assert( argc==3 );
79775   UNUSED_PARAMETER2(NotUsed, argc);
79776
79777   if( argv==0 || argv[0]==0 || argv[2]==0 ){
79778     return 0;
79779   }
79780   pTable = sqlcipher3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
79781   if( pTable==0 ){
79782     return 0;
79783   }
79784   if( argv[1] ){
79785     pIndex = sqlcipher3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
79786   }else{
79787     pIndex = 0;
79788   }
79789   n = pIndex ? pIndex->nColumn : 0;
79790   z = argv[2];
79791   for(i=0; *z && i<=n; i++){
79792     v = 0;
79793     while( (c=z[0])>='0' && c<='9' ){
79794       v = v*10 + c - '0';
79795       z++;
79796     }
79797     if( i==0 ) pTable->nRowEst = v;
79798     if( pIndex==0 ) break;
79799     pIndex->aiRowEst[i] = v;
79800     if( *z==' ' ) z++;
79801     if( memcmp(z, "unordered", 10)==0 ){
79802       pIndex->bUnordered = 1;
79803       break;
79804     }
79805   }
79806   return 0;
79807 }
79808
79809 /*
79810 ** If the Index.aSample variable is not NULL, delete the aSample[] array
79811 ** and its contents.
79812 */
79813 SQLCIPHER_PRIVATE void sqlcipher3DeleteIndexSamples(sqlcipher3 *db, Index *pIdx){
79814 #ifdef SQLCIPHER_ENABLE_STAT3
79815   if( pIdx->aSample ){
79816     int j;
79817     for(j=0; j<pIdx->nSample; j++){
79818       IndexSample *p = &pIdx->aSample[j];
79819       if( p->eType==SQLCIPHER_TEXT || p->eType==SQLCIPHER_BLOB ){
79820         sqlcipher3DbFree(db, p->u.z);
79821       }
79822     }
79823     sqlcipher3DbFree(db, pIdx->aSample);
79824   }
79825   if( db && db->pnBytesFreed==0 ){
79826     pIdx->nSample = 0;
79827     pIdx->aSample = 0;
79828   }
79829 #else
79830   UNUSED_PARAMETER(db);
79831   UNUSED_PARAMETER(pIdx);
79832 #endif
79833 }
79834
79835 #ifdef SQLCIPHER_ENABLE_STAT3
79836 /*
79837 ** Load content from the sqlcipher_stat3 table into the Index.aSample[]
79838 ** arrays of all indices.
79839 */
79840 static int loadStat3(sqlcipher3 *db, const char *zDb){
79841   int rc;                       /* Result codes from subroutines */
79842   sqlcipher3_stmt *pStmt = 0;      /* An SQL statement being run */
79843   char *zSql;                   /* Text of the SQL statement */
79844   Index *pPrevIdx = 0;          /* Previous index in the loop */
79845   int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
79846   int eType;                    /* Datatype of a sample */
79847   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
79848
79849   if( !sqlcipher3FindTable(db, "sqlcipher_stat3", zDb) ){
79850     return SQLCIPHER_OK;
79851   }
79852
79853   zSql = sqlcipher3MPrintf(db, 
79854       "SELECT idx,count(*) FROM %Q.sqlcipher_stat3"
79855       " GROUP BY idx", zDb);
79856   if( !zSql ){
79857     return SQLCIPHER_NOMEM;
79858   }
79859   rc = sqlcipher3_prepare(db, zSql, -1, &pStmt, 0);
79860   sqlcipher3DbFree(db, zSql);
79861   if( rc ) return rc;
79862
79863   while( sqlcipher3_step(pStmt)==SQLCIPHER_ROW ){
79864     char *zIndex;   /* Index name */
79865     Index *pIdx;    /* Pointer to the index object */
79866     int nSample;    /* Number of samples */
79867
79868     zIndex = (char *)sqlcipher3_column_text(pStmt, 0);
79869     if( zIndex==0 ) continue;
79870     nSample = sqlcipher3_column_int(pStmt, 1);
79871     pIdx = sqlcipher3FindIndex(db, zIndex, zDb);
79872     if( pIdx==0 ) continue;
79873     assert( pIdx->nSample==0 );
79874     pIdx->nSample = nSample;
79875     pIdx->aSample = sqlcipher3MallocZero( nSample*sizeof(IndexSample) );
79876     pIdx->avgEq = pIdx->aiRowEst[1];
79877     if( pIdx->aSample==0 ){
79878       db->mallocFailed = 1;
79879       sqlcipher3_finalize(pStmt);
79880       return SQLCIPHER_NOMEM;
79881     }
79882   }
79883   rc = sqlcipher3_finalize(pStmt);
79884   if( rc ) return rc;
79885
79886   zSql = sqlcipher3MPrintf(db, 
79887       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlcipher_stat3", zDb);
79888   if( !zSql ){
79889     return SQLCIPHER_NOMEM;
79890   }
79891   rc = sqlcipher3_prepare(db, zSql, -1, &pStmt, 0);
79892   sqlcipher3DbFree(db, zSql);
79893   if( rc ) return rc;
79894
79895   while( sqlcipher3_step(pStmt)==SQLCIPHER_ROW ){
79896     char *zIndex;   /* Index name */
79897     Index *pIdx;    /* Pointer to the index object */
79898     int i;          /* Loop counter */
79899     tRowcnt sumEq;  /* Sum of the nEq values */
79900
79901     zIndex = (char *)sqlcipher3_column_text(pStmt, 0);
79902     if( zIndex==0 ) continue;
79903     pIdx = sqlcipher3FindIndex(db, zIndex, zDb);
79904     if( pIdx==0 ) continue;
79905     if( pIdx==pPrevIdx ){
79906       idx++;
79907     }else{
79908       pPrevIdx = pIdx;
79909       idx = 0;
79910     }
79911     assert( idx<pIdx->nSample );
79912     pSample = &pIdx->aSample[idx];
79913     pSample->nEq = (tRowcnt)sqlcipher3_column_int64(pStmt, 1);
79914     pSample->nLt = (tRowcnt)sqlcipher3_column_int64(pStmt, 2);
79915     pSample->nDLt = (tRowcnt)sqlcipher3_column_int64(pStmt, 3);
79916     if( idx==pIdx->nSample-1 ){
79917       if( pSample->nDLt>0 ){
79918         for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
79919         pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
79920       }
79921       if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
79922     }
79923     eType = sqlcipher3_column_type(pStmt, 4);
79924     pSample->eType = (u8)eType;
79925     switch( eType ){
79926       case SQLCIPHER_INTEGER: {
79927         pSample->u.i = sqlcipher3_column_int64(pStmt, 4);
79928         break;
79929       }
79930       case SQLCIPHER_FLOAT: {
79931         pSample->u.r = sqlcipher3_column_double(pStmt, 4);
79932         break;
79933       }
79934       case SQLCIPHER_NULL: {
79935         break;
79936       }
79937       default: assert( eType==SQLCIPHER_TEXT || eType==SQLCIPHER_BLOB ); {
79938         const char *z = (const char *)(
79939               (eType==SQLCIPHER_BLOB) ?
79940               sqlcipher3_column_blob(pStmt, 4):
79941               sqlcipher3_column_text(pStmt, 4)
79942            );
79943         int n = z ? sqlcipher3_column_bytes(pStmt, 4) : 0;
79944         pSample->nByte = n;
79945         if( n < 1){
79946           pSample->u.z = 0;
79947         }else{
79948           pSample->u.z = sqlcipher3Malloc(n);
79949           if( pSample->u.z==0 ){
79950             db->mallocFailed = 1;
79951             sqlcipher3_finalize(pStmt);
79952             return SQLCIPHER_NOMEM;
79953           }
79954           memcpy(pSample->u.z, z, n);
79955         }
79956       }
79957     }
79958   }
79959   return sqlcipher3_finalize(pStmt);
79960 }
79961 #endif /* SQLCIPHER_ENABLE_STAT3 */
79962
79963 /*
79964 ** Load the content of the sqlcipher_stat1 and sqlcipher_stat3 tables. The
79965 ** contents of sqlcipher_stat1 are used to populate the Index.aiRowEst[]
79966 ** arrays. The contents of sqlcipher_stat3 are used to populate the
79967 ** Index.aSample[] arrays.
79968 **
79969 ** If the sqlcipher_stat1 table is not present in the database, SQLCIPHER_ERROR
79970 ** is returned. In this case, even if SQLCIPHER_ENABLE_STAT3 was defined 
79971 ** during compilation and the sqlcipher_stat3 table is present, no data is 
79972 ** read from it.
79973 **
79974 ** If SQLCIPHER_ENABLE_STAT3 was defined during compilation and the 
79975 ** sqlcipher_stat3 table is not present in the database, SQLCIPHER_ERROR is
79976 ** returned. However, in this case, data is read from the sqlcipher_stat1
79977 ** table (if it is present) before returning.
79978 **
79979 ** If an OOM error occurs, this function always sets db->mallocFailed.
79980 ** This means if the caller does not care about other errors, the return
79981 ** code may be ignored.
79982 */
79983 SQLCIPHER_PRIVATE int sqlcipher3AnalysisLoad(sqlcipher3 *db, int iDb){
79984   analysisInfo sInfo;
79985   HashElem *i;
79986   char *zSql;
79987   int rc;
79988
79989   assert( iDb>=0 && iDb<db->nDb );
79990   assert( db->aDb[iDb].pBt!=0 );
79991
79992   /* Clear any prior statistics */
79993   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
79994   for(i=sqlcipherHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqlcipherHashNext(i)){
79995     Index *pIdx = sqlcipherHashData(i);
79996     sqlcipher3DefaultRowEst(pIdx);
79997 #ifdef SQLCIPHER_ENABLE_STAT3
79998     sqlcipher3DeleteIndexSamples(db, pIdx);
79999     pIdx->aSample = 0;
80000 #endif
80001   }
80002
80003   /* Check to make sure the sqlcipher_stat1 table exists */
80004   sInfo.db = db;
80005   sInfo.zDatabase = db->aDb[iDb].zName;
80006   if( sqlcipher3FindTable(db, "sqlcipher_stat1", sInfo.zDatabase)==0 ){
80007     return SQLCIPHER_ERROR;
80008   }
80009
80010   /* Load new statistics out of the sqlcipher_stat1 table */
80011   zSql = sqlcipher3MPrintf(db, 
80012       "SELECT tbl,idx,stat FROM %Q.sqlcipher_stat1", sInfo.zDatabase);
80013   if( zSql==0 ){
80014     rc = SQLCIPHER_NOMEM;
80015   }else{
80016     rc = sqlcipher3_exec(db, zSql, analysisLoader, &sInfo, 0);
80017     sqlcipher3DbFree(db, zSql);
80018   }
80019
80020
80021   /* Load the statistics from the sqlcipher_stat3 table. */
80022 #ifdef SQLCIPHER_ENABLE_STAT3
80023   if( rc==SQLCIPHER_OK ){
80024     rc = loadStat3(db, sInfo.zDatabase);
80025   }
80026 #endif
80027
80028   if( rc==SQLCIPHER_NOMEM ){
80029     db->mallocFailed = 1;
80030   }
80031   return rc;
80032 }
80033
80034
80035 #endif /* SQLCIPHER_OMIT_ANALYZE */
80036
80037 /************** End of analyze.c *********************************************/
80038 /************** Begin file attach.c ******************************************/
80039 /*
80040 ** 2003 April 6
80041 **
80042 ** The author disclaims copyright to this source code.  In place of
80043 ** a legal notice, here is a blessing:
80044 **
80045 **    May you do good and not evil.
80046 **    May you find forgiveness for yourself and forgive others.
80047 **    May you share freely, never taking more than you give.
80048 **
80049 *************************************************************************
80050 ** This file contains code used to implement the ATTACH and DETACH commands.
80051 */
80052
80053 #ifndef SQLCIPHER_OMIT_ATTACH
80054 /*
80055 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
80056 ** is slightly different from resolving a normal SQL expression, because simple
80057 ** identifiers are treated as strings, not possible column names or aliases.
80058 **
80059 ** i.e. if the parser sees:
80060 **
80061 **     ATTACH DATABASE abc AS def
80062 **
80063 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
80064 ** looking for columns of the same name.
80065 **
80066 ** This only applies to the root node of pExpr, so the statement:
80067 **
80068 **     ATTACH DATABASE abc||def AS 'db2'
80069 **
80070 ** will fail because neither abc or def can be resolved.
80071 */
80072 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
80073 {
80074   int rc = SQLCIPHER_OK;
80075   if( pExpr ){
80076     if( pExpr->op!=TK_ID ){
80077       rc = sqlcipher3ResolveExprNames(pName, pExpr);
80078       if( rc==SQLCIPHER_OK && !sqlcipher3ExprIsConstant(pExpr) ){
80079         sqlcipher3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
80080         return SQLCIPHER_ERROR;
80081       }
80082     }else{
80083       pExpr->op = TK_STRING;
80084     }
80085   }
80086   return rc;
80087 }
80088
80089 /*
80090 ** An SQL user-function registered to do the work of an ATTACH statement. The
80091 ** three arguments to the function come directly from an attach statement:
80092 **
80093 **     ATTACH DATABASE x AS y KEY z
80094 **
80095 **     SELECT sqlcipher_attach(x, y, z)
80096 **
80097 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
80098 ** third argument.
80099 */
80100 static void attachFunc(
80101   sqlcipher3_context *context,
80102   int NotUsed,
80103   sqlcipher3_value **argv
80104 ){
80105   int i;
80106   int rc = 0;
80107   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
80108   const char *zName;
80109   const char *zFile;
80110   char *zPath = 0;
80111   char *zErr = 0;
80112   unsigned int flags;
80113   Db *aNew;
80114   char *zErrDyn = 0;
80115   sqlcipher3_vfs *pVfs;
80116
80117   UNUSED_PARAMETER(NotUsed);
80118
80119   zFile = (const char *)sqlcipher3_value_text(argv[0]);
80120   zName = (const char *)sqlcipher3_value_text(argv[1]);
80121   if( zFile==0 ) zFile = "";
80122   if( zName==0 ) zName = "";
80123
80124   /* Check for the following errors:
80125   **
80126   **     * Too many attached databases,
80127   **     * Transaction currently open
80128   **     * Specified database name already being used.
80129   */
80130   if( db->nDb>=db->aLimit[SQLCIPHER_LIMIT_ATTACHED]+2 ){
80131     zErrDyn = sqlcipher3MPrintf(db, "too many attached databases - max %d", 
80132       db->aLimit[SQLCIPHER_LIMIT_ATTACHED]
80133     );
80134     goto attach_error;
80135   }
80136   if( !db->autoCommit ){
80137     zErrDyn = sqlcipher3MPrintf(db, "cannot ATTACH database within transaction");
80138     goto attach_error;
80139   }
80140   for(i=0; i<db->nDb; i++){
80141     char *z = db->aDb[i].zName;
80142     assert( z && zName );
80143     if( sqlcipher3StrICmp(z, zName)==0 ){
80144       zErrDyn = sqlcipher3MPrintf(db, "database %s is already in use", zName);
80145       goto attach_error;
80146     }
80147   }
80148
80149   /* Allocate the new entry in the db->aDb[] array and initialise the schema
80150   ** hash tables.
80151   */
80152   if( db->aDb==db->aDbStatic ){
80153     aNew = sqlcipher3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
80154     if( aNew==0 ) return;
80155     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
80156   }else{
80157     aNew = sqlcipher3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
80158     if( aNew==0 ) return;
80159   }
80160   db->aDb = aNew;
80161   aNew = &db->aDb[db->nDb];
80162   memset(aNew, 0, sizeof(*aNew));
80163
80164   /* Open the database file. If the btree is successfully opened, use
80165   ** it to obtain the database schema. At this point the schema may
80166   ** or may not be initialised.
80167   */
80168   flags = db->openFlags;
80169   rc = sqlcipher3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
80170   if( rc!=SQLCIPHER_OK ){
80171     if( rc==SQLCIPHER_NOMEM ) db->mallocFailed = 1;
80172     sqlcipher3_result_error(context, zErr, -1);
80173     sqlcipher3_free(zErr);
80174     return;
80175   }
80176   assert( pVfs );
80177   flags |= SQLCIPHER_OPEN_MAIN_DB;
80178   rc = sqlcipher3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
80179   sqlcipher3_free( zPath );
80180   db->nDb++;
80181   if( rc==SQLCIPHER_CONSTRAINT ){
80182     rc = SQLCIPHER_ERROR;
80183     zErrDyn = sqlcipher3MPrintf(db, "database is already attached");
80184   }else if( rc==SQLCIPHER_OK ){
80185     Pager *pPager;
80186     aNew->pSchema = sqlcipher3SchemaGet(db, aNew->pBt);
80187     if( !aNew->pSchema ){
80188       rc = SQLCIPHER_NOMEM;
80189     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
80190       zErrDyn = sqlcipher3MPrintf(db, 
80191         "attached databases must use the same text encoding as main database");
80192       rc = SQLCIPHER_ERROR;
80193     }
80194     pPager = sqlcipher3BtreePager(aNew->pBt);
80195     sqlcipher3PagerLockingMode(pPager, db->dfltLockMode);
80196     sqlcipher3BtreeSecureDelete(aNew->pBt,
80197                              sqlcipher3BtreeSecureDelete(db->aDb[0].pBt,-1) );
80198   }
80199   aNew->safety_level = 3;
80200   aNew->zName = sqlcipher3DbStrDup(db, zName);
80201   if( rc==SQLCIPHER_OK && aNew->zName==0 ){
80202     rc = SQLCIPHER_NOMEM;
80203   }
80204
80205
80206 #ifdef SQLCIPHER_HAS_CODEC
80207   if( rc==SQLCIPHER_OK ){
80208     extern int sqlcipher3CodecAttach(sqlcipher3*, int, const void*, int);
80209     extern void sqlcipher3CodecGetKey(sqlcipher3*, int, void**, int*);
80210     int nKey = 0;
80211     char *zKey = NULL;
80212     int t = sqlcipher3_value_type(argv[2]);
80213     switch( t ){
80214       case SQLCIPHER_INTEGER:
80215       case SQLCIPHER_FLOAT:
80216         zErrDyn = sqlcipher3DbStrDup(db, "Invalid key value");
80217         rc = SQLCIPHER_ERROR;
80218         break;
80219         
80220       case SQLCIPHER_TEXT:
80221       case SQLCIPHER_BLOB:
80222         nKey = sqlcipher3_value_bytes(argv[2]);
80223         zKey = (char *)sqlcipher3_value_blob(argv[2]);
80224         rc = sqlcipher3CodecAttach(db, db->nDb-1, zKey, nKey);
80225         break;
80226
80227       case SQLCIPHER_NULL:
80228         /* No key specified.  Use the key from the main database */
80229         sqlcipher3CodecGetKey(db, 0, (void**)&zKey, &nKey);
80230         if( nKey>0 || sqlcipher3BtreeGetReserve(db->aDb[0].pBt)>0 ){
80231           rc = sqlcipher3CodecAttach(db, db->nDb-1, zKey, nKey);
80232         }
80233         break;
80234     }
80235   }
80236 #endif
80237
80238   /* If the file was opened successfully, read the schema for the new database.
80239   ** If this fails, or if opening the file failed, then close the file and 
80240   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
80241   ** we found it.
80242   */
80243   if( rc==SQLCIPHER_OK ){
80244     sqlcipher3BtreeEnterAll(db);
80245     rc = sqlcipher3Init(db, &zErrDyn);
80246     sqlcipher3BtreeLeaveAll(db);
80247   }
80248   if( rc ){
80249     int iDb = db->nDb - 1;
80250     assert( iDb>=2 );
80251     if( db->aDb[iDb].pBt ){
80252       sqlcipher3BtreeClose(db->aDb[iDb].pBt);
80253       db->aDb[iDb].pBt = 0;
80254       db->aDb[iDb].pSchema = 0;
80255     }
80256     sqlcipher3ResetInternalSchema(db, -1);
80257     db->nDb = iDb;
80258     if( rc==SQLCIPHER_NOMEM || rc==SQLCIPHER_IOERR_NOMEM ){
80259       db->mallocFailed = 1;
80260       sqlcipher3DbFree(db, zErrDyn);
80261       zErrDyn = sqlcipher3MPrintf(db, "out of memory");
80262     }else if( zErrDyn==0 ){
80263       zErrDyn = sqlcipher3MPrintf(db, "unable to open database: %s", zFile);
80264     }
80265     goto attach_error;
80266   }
80267   
80268   return;
80269
80270 attach_error:
80271   /* Return an error if we get here */
80272   if( zErrDyn ){
80273     sqlcipher3_result_error(context, zErrDyn, -1);
80274     sqlcipher3DbFree(db, zErrDyn);
80275   }
80276   if( rc ) sqlcipher3_result_error_code(context, rc);
80277 }
80278
80279 /*
80280 ** An SQL user-function registered to do the work of an DETACH statement. The
80281 ** three arguments to the function come directly from a detach statement:
80282 **
80283 **     DETACH DATABASE x
80284 **
80285 **     SELECT sqlcipher_detach(x)
80286 */
80287 static void detachFunc(
80288   sqlcipher3_context *context,
80289   int NotUsed,
80290   sqlcipher3_value **argv
80291 ){
80292   const char *zName = (const char *)sqlcipher3_value_text(argv[0]);
80293   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
80294   int i;
80295   Db *pDb = 0;
80296   char zErr[128];
80297
80298   UNUSED_PARAMETER(NotUsed);
80299
80300   if( zName==0 ) zName = "";
80301   for(i=0; i<db->nDb; i++){
80302     pDb = &db->aDb[i];
80303     if( pDb->pBt==0 ) continue;
80304     if( sqlcipher3StrICmp(pDb->zName, zName)==0 ) break;
80305   }
80306
80307   if( i>=db->nDb ){
80308     sqlcipher3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
80309     goto detach_error;
80310   }
80311   if( i<2 ){
80312     sqlcipher3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
80313     goto detach_error;
80314   }
80315   if( !db->autoCommit ){
80316     sqlcipher3_snprintf(sizeof(zErr), zErr,
80317                      "cannot DETACH database within transaction");
80318     goto detach_error;
80319   }
80320   if( sqlcipher3BtreeIsInReadTrans(pDb->pBt) || sqlcipher3BtreeIsInBackup(pDb->pBt) ){
80321     sqlcipher3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
80322     goto detach_error;
80323   }
80324
80325   sqlcipher3BtreeClose(pDb->pBt);
80326   pDb->pBt = 0;
80327   pDb->pSchema = 0;
80328   sqlcipher3ResetInternalSchema(db, -1);
80329   return;
80330
80331 detach_error:
80332   sqlcipher3_result_error(context, zErr, -1);
80333 }
80334
80335 /*
80336 ** This procedure generates VDBE code for a single invocation of either the
80337 ** sqlcipher_detach() or sqlcipher_attach() SQL user functions.
80338 */
80339 static void codeAttach(
80340   Parse *pParse,       /* The parser context */
80341   int type,            /* Either SQLCIPHER_ATTACH or SQLCIPHER_DETACH */
80342   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
80343   Expr *pAuthArg,      /* Expression to pass to authorization callback */
80344   Expr *pFilename,     /* Name of database file */
80345   Expr *pDbname,       /* Name of the database to use internally */
80346   Expr *pKey           /* Database key for encryption extension */
80347 ){
80348   int rc;
80349   NameContext sName;
80350   Vdbe *v;
80351   sqlcipher3* db = pParse->db;
80352   int regArgs;
80353
80354   memset(&sName, 0, sizeof(NameContext));
80355   sName.pParse = pParse;
80356
80357   if( 
80358       SQLCIPHER_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
80359       SQLCIPHER_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
80360       SQLCIPHER_OK!=(rc = resolveAttachExpr(&sName, pKey))
80361   ){
80362     pParse->nErr++;
80363     goto attach_end;
80364   }
80365
80366 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
80367   if( pAuthArg ){
80368     char *zAuthArg;
80369     if( pAuthArg->op==TK_STRING ){
80370       zAuthArg = pAuthArg->u.zToken;
80371     }else{
80372       zAuthArg = 0;
80373     }
80374     rc = sqlcipher3AuthCheck(pParse, type, zAuthArg, 0, 0);
80375     if(rc!=SQLCIPHER_OK ){
80376       goto attach_end;
80377     }
80378   }
80379 #endif /* SQLCIPHER_OMIT_AUTHORIZATION */
80380
80381
80382   v = sqlcipher3GetVdbe(pParse);
80383   regArgs = sqlcipher3GetTempRange(pParse, 4);
80384   sqlcipher3ExprCode(pParse, pFilename, regArgs);
80385   sqlcipher3ExprCode(pParse, pDbname, regArgs+1);
80386   sqlcipher3ExprCode(pParse, pKey, regArgs+2);
80387
80388   assert( v || db->mallocFailed );
80389   if( v ){
80390     sqlcipher3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
80391     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
80392     sqlcipher3VdbeChangeP5(v, (u8)(pFunc->nArg));
80393     sqlcipher3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
80394
80395     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
80396     ** statement only). For DETACH, set it to false (expire all existing
80397     ** statements).
80398     */
80399     sqlcipher3VdbeAddOp1(v, OP_Expire, (type==SQLCIPHER_ATTACH));
80400   }
80401   
80402 attach_end:
80403   sqlcipher3ExprDelete(db, pFilename);
80404   sqlcipher3ExprDelete(db, pDbname);
80405   sqlcipher3ExprDelete(db, pKey);
80406 }
80407
80408 /*
80409 ** Called by the parser to compile a DETACH statement.
80410 **
80411 **     DETACH pDbname
80412 */
80413 SQLCIPHER_PRIVATE void sqlcipher3Detach(Parse *pParse, Expr *pDbname){
80414   static const FuncDef detach_func = {
80415     1,                /* nArg */
80416     SQLCIPHER_UTF8,      /* iPrefEnc */
80417     0,                /* flags */
80418     0,                /* pUserData */
80419     0,                /* pNext */
80420     detachFunc,       /* xFunc */
80421     0,                /* xStep */
80422     0,                /* xFinalize */
80423     "sqlcipher_detach",  /* zName */
80424     0,                /* pHash */
80425     0                 /* pDestructor */
80426   };
80427   codeAttach(pParse, SQLCIPHER_DETACH, &detach_func, pDbname, 0, 0, pDbname);
80428 }
80429
80430 /*
80431 ** Called by the parser to compile an ATTACH statement.
80432 **
80433 **     ATTACH p AS pDbname KEY pKey
80434 */
80435 SQLCIPHER_PRIVATE void sqlcipher3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
80436   static const FuncDef attach_func = {
80437     3,                /* nArg */
80438     SQLCIPHER_UTF8,      /* iPrefEnc */
80439     0,                /* flags */
80440     0,                /* pUserData */
80441     0,                /* pNext */
80442     attachFunc,       /* xFunc */
80443     0,                /* xStep */
80444     0,                /* xFinalize */
80445     "sqlcipher_attach",  /* zName */
80446     0,                /* pHash */
80447     0                 /* pDestructor */
80448   };
80449   codeAttach(pParse, SQLCIPHER_ATTACH, &attach_func, p, p, pDbname, pKey);
80450 }
80451 #endif /* SQLCIPHER_OMIT_ATTACH */
80452
80453 /*
80454 ** Initialize a DbFixer structure.  This routine must be called prior
80455 ** to passing the structure to one of the sqlcipherFixAAAA() routines below.
80456 **
80457 ** The return value indicates whether or not fixation is required.  TRUE
80458 ** means we do need to fix the database references, FALSE means we do not.
80459 */
80460 SQLCIPHER_PRIVATE int sqlcipher3FixInit(
80461   DbFixer *pFix,      /* The fixer to be initialized */
80462   Parse *pParse,      /* Error messages will be written here */
80463   int iDb,            /* This is the database that must be used */
80464   const char *zType,  /* "view", "trigger", or "index" */
80465   const Token *pName  /* Name of the view, trigger, or index */
80466 ){
80467   sqlcipher3 *db;
80468
80469   if( NEVER(iDb<0) || iDb==1 ) return 0;
80470   db = pParse->db;
80471   assert( db->nDb>iDb );
80472   pFix->pParse = pParse;
80473   pFix->zDb = db->aDb[iDb].zName;
80474   pFix->zType = zType;
80475   pFix->pName = pName;
80476   return 1;
80477 }
80478
80479 /*
80480 ** The following set of routines walk through the parse tree and assign
80481 ** a specific database to all table references where the database name
80482 ** was left unspecified in the original SQL statement.  The pFix structure
80483 ** must have been initialized by a prior call to sqlcipher3FixInit().
80484 **
80485 ** These routines are used to make sure that an index, trigger, or
80486 ** view in one database does not refer to objects in a different database.
80487 ** (Exception: indices, triggers, and views in the TEMP database are
80488 ** allowed to refer to anything.)  If a reference is explicitly made
80489 ** to an object in a different database, an error message is added to
80490 ** pParse->zErrMsg and these routines return non-zero.  If everything
80491 ** checks out, these routines return 0.
80492 */
80493 SQLCIPHER_PRIVATE int sqlcipher3FixSrcList(
80494   DbFixer *pFix,       /* Context of the fixation */
80495   SrcList *pList       /* The Source list to check and modify */
80496 ){
80497   int i;
80498   const char *zDb;
80499   struct SrcList_item *pItem;
80500
80501   if( NEVER(pList==0) ) return 0;
80502   zDb = pFix->zDb;
80503   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
80504     if( pItem->zDatabase==0 ){
80505       pItem->zDatabase = sqlcipher3DbStrDup(pFix->pParse->db, zDb);
80506     }else if( sqlcipher3StrICmp(pItem->zDatabase,zDb)!=0 ){
80507       sqlcipher3ErrorMsg(pFix->pParse,
80508          "%s %T cannot reference objects in database %s",
80509          pFix->zType, pFix->pName, pItem->zDatabase);
80510       return 1;
80511     }
80512 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_TRIGGER)
80513     if( sqlcipher3FixSelect(pFix, pItem->pSelect) ) return 1;
80514     if( sqlcipher3FixExpr(pFix, pItem->pOn) ) return 1;
80515 #endif
80516   }
80517   return 0;
80518 }
80519 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_TRIGGER)
80520 SQLCIPHER_PRIVATE int sqlcipher3FixSelect(
80521   DbFixer *pFix,       /* Context of the fixation */
80522   Select *pSelect      /* The SELECT statement to be fixed to one database */
80523 ){
80524   while( pSelect ){
80525     if( sqlcipher3FixExprList(pFix, pSelect->pEList) ){
80526       return 1;
80527     }
80528     if( sqlcipher3FixSrcList(pFix, pSelect->pSrc) ){
80529       return 1;
80530     }
80531     if( sqlcipher3FixExpr(pFix, pSelect->pWhere) ){
80532       return 1;
80533     }
80534     if( sqlcipher3FixExpr(pFix, pSelect->pHaving) ){
80535       return 1;
80536     }
80537     pSelect = pSelect->pPrior;
80538   }
80539   return 0;
80540 }
80541 SQLCIPHER_PRIVATE int sqlcipher3FixExpr(
80542   DbFixer *pFix,     /* Context of the fixation */
80543   Expr *pExpr        /* The expression to be fixed to one database */
80544 ){
80545   while( pExpr ){
80546     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
80547     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
80548       if( sqlcipher3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
80549     }else{
80550       if( sqlcipher3FixExprList(pFix, pExpr->x.pList) ) return 1;
80551     }
80552     if( sqlcipher3FixExpr(pFix, pExpr->pRight) ){
80553       return 1;
80554     }
80555     pExpr = pExpr->pLeft;
80556   }
80557   return 0;
80558 }
80559 SQLCIPHER_PRIVATE int sqlcipher3FixExprList(
80560   DbFixer *pFix,     /* Context of the fixation */
80561   ExprList *pList    /* The expression to be fixed to one database */
80562 ){
80563   int i;
80564   struct ExprList_item *pItem;
80565   if( pList==0 ) return 0;
80566   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
80567     if( sqlcipher3FixExpr(pFix, pItem->pExpr) ){
80568       return 1;
80569     }
80570   }
80571   return 0;
80572 }
80573 #endif
80574
80575 #ifndef SQLCIPHER_OMIT_TRIGGER
80576 SQLCIPHER_PRIVATE int sqlcipher3FixTriggerStep(
80577   DbFixer *pFix,     /* Context of the fixation */
80578   TriggerStep *pStep /* The trigger step be fixed to one database */
80579 ){
80580   while( pStep ){
80581     if( sqlcipher3FixSelect(pFix, pStep->pSelect) ){
80582       return 1;
80583     }
80584     if( sqlcipher3FixExpr(pFix, pStep->pWhere) ){
80585       return 1;
80586     }
80587     if( sqlcipher3FixExprList(pFix, pStep->pExprList) ){
80588       return 1;
80589     }
80590     pStep = pStep->pNext;
80591   }
80592   return 0;
80593 }
80594 #endif
80595
80596 /************** End of attach.c **********************************************/
80597 /************** Begin file auth.c ********************************************/
80598 /*
80599 ** 2003 January 11
80600 **
80601 ** The author disclaims copyright to this source code.  In place of
80602 ** a legal notice, here is a blessing:
80603 **
80604 **    May you do good and not evil.
80605 **    May you find forgiveness for yourself and forgive others.
80606 **    May you share freely, never taking more than you give.
80607 **
80608 *************************************************************************
80609 ** This file contains code used to implement the sqlcipher3_set_authorizer()
80610 ** API.  This facility is an optional feature of the library.  Embedded
80611 ** systems that do not need this facility may omit it by recompiling
80612 ** the library with -DSQLCIPHER_OMIT_AUTHORIZATION=1
80613 */
80614
80615 /*
80616 ** All of the code in this file may be omitted by defining a single
80617 ** macro.
80618 */
80619 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
80620
80621 /*
80622 ** Set or clear the access authorization function.
80623 **
80624 ** The access authorization function is be called during the compilation
80625 ** phase to verify that the user has read and/or write access permission on
80626 ** various fields of the database.  The first argument to the auth function
80627 ** is a copy of the 3rd argument to this routine.  The second argument
80628 ** to the auth function is one of these constants:
80629 **
80630 **       SQLCIPHER_CREATE_INDEX
80631 **       SQLCIPHER_CREATE_TABLE
80632 **       SQLCIPHER_CREATE_TEMP_INDEX
80633 **       SQLCIPHER_CREATE_TEMP_TABLE
80634 **       SQLCIPHER_CREATE_TEMP_TRIGGER
80635 **       SQLCIPHER_CREATE_TEMP_VIEW
80636 **       SQLCIPHER_CREATE_TRIGGER
80637 **       SQLCIPHER_CREATE_VIEW
80638 **       SQLCIPHER_DELETE
80639 **       SQLCIPHER_DROP_INDEX
80640 **       SQLCIPHER_DROP_TABLE
80641 **       SQLCIPHER_DROP_TEMP_INDEX
80642 **       SQLCIPHER_DROP_TEMP_TABLE
80643 **       SQLCIPHER_DROP_TEMP_TRIGGER
80644 **       SQLCIPHER_DROP_TEMP_VIEW
80645 **       SQLCIPHER_DROP_TRIGGER
80646 **       SQLCIPHER_DROP_VIEW
80647 **       SQLCIPHER_INSERT
80648 **       SQLCIPHER_PRAGMA
80649 **       SQLCIPHER_READ
80650 **       SQLCIPHER_SELECT
80651 **       SQLCIPHER_TRANSACTION
80652 **       SQLCIPHER_UPDATE
80653 **
80654 ** The third and fourth arguments to the auth function are the name of
80655 ** the table and the column that are being accessed.  The auth function
80656 ** should return either SQLCIPHER_OK, SQLCIPHER_DENY, or SQLCIPHER_IGNORE.  If
80657 ** SQLCIPHER_OK is returned, it means that access is allowed.  SQLCIPHER_DENY
80658 ** means that the SQL statement will never-run - the sqlcipher3_exec() call
80659 ** will return with an error.  SQLCIPHER_IGNORE means that the SQL statement
80660 ** should run but attempts to read the specified column will return NULL
80661 ** and attempts to write the column will be ignored.
80662 **
80663 ** Setting the auth function to NULL disables this hook.  The default
80664 ** setting of the auth function is NULL.
80665 */
80666 SQLCIPHER_API int sqlcipher3_set_authorizer(
80667   sqlcipher3 *db,
80668   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
80669   void *pArg
80670 ){
80671   sqlcipher3_mutex_enter(db->mutex);
80672   db->xAuth = xAuth;
80673   db->pAuthArg = pArg;
80674   sqlcipher3ExpirePreparedStatements(db);
80675   sqlcipher3_mutex_leave(db->mutex);
80676   return SQLCIPHER_OK;
80677 }
80678
80679 /*
80680 ** Write an error message into pParse->zErrMsg that explains that the
80681 ** user-supplied authorization function returned an illegal value.
80682 */
80683 static void sqlcipherAuthBadReturnCode(Parse *pParse){
80684   sqlcipher3ErrorMsg(pParse, "authorizer malfunction");
80685   pParse->rc = SQLCIPHER_ERROR;
80686 }
80687
80688 /*
80689 ** Invoke the authorization callback for permission to read column zCol from
80690 ** table zTab in database zDb. This function assumes that an authorization
80691 ** callback has been registered (i.e. that sqlcipher3.xAuth is not NULL).
80692 **
80693 ** If SQLCIPHER_IGNORE is returned and pExpr is not NULL, then pExpr is changed
80694 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLCIPHER_IGNORE
80695 ** is treated as SQLCIPHER_DENY. In this case an error is left in pParse.
80696 */
80697 SQLCIPHER_PRIVATE int sqlcipher3AuthReadCol(
80698   Parse *pParse,                  /* The parser context */
80699   const char *zTab,               /* Table name */
80700   const char *zCol,               /* Column name */
80701   int iDb                         /* Index of containing database. */
80702 ){
80703   sqlcipher3 *db = pParse->db;       /* Database handle */
80704   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
80705   int rc;                         /* Auth callback return code */
80706
80707   rc = db->xAuth(db->pAuthArg, SQLCIPHER_READ, zTab,zCol,zDb,pParse->zAuthContext);
80708   if( rc==SQLCIPHER_DENY ){
80709     if( db->nDb>2 || iDb!=0 ){
80710       sqlcipher3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
80711     }else{
80712       sqlcipher3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
80713     }
80714     pParse->rc = SQLCIPHER_AUTH;
80715   }else if( rc!=SQLCIPHER_IGNORE && rc!=SQLCIPHER_OK ){
80716     sqlcipherAuthBadReturnCode(pParse);
80717   }
80718   return rc;
80719 }
80720
80721 /*
80722 ** The pExpr should be a TK_COLUMN expression.  The table referred to
80723 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
80724 ** Check to see if it is OK to read this particular column.
80725 **
80726 ** If the auth function returns SQLCIPHER_IGNORE, change the TK_COLUMN 
80727 ** instruction into a TK_NULL.  If the auth function returns SQLCIPHER_DENY,
80728 ** then generate an error.
80729 */
80730 SQLCIPHER_PRIVATE void sqlcipher3AuthRead(
80731   Parse *pParse,        /* The parser context */
80732   Expr *pExpr,          /* The expression to check authorization on */
80733   Schema *pSchema,      /* The schema of the expression */
80734   SrcList *pTabList     /* All table that pExpr might refer to */
80735 ){
80736   sqlcipher3 *db = pParse->db;
80737   Table *pTab = 0;      /* The table being read */
80738   const char *zCol;     /* Name of the column of the table */
80739   int iSrc;             /* Index in pTabList->a[] of table being read */
80740   int iDb;              /* The index of the database the expression refers to */
80741   int iCol;             /* Index of column in table */
80742
80743   if( db->xAuth==0 ) return;
80744   iDb = sqlcipher3SchemaToIndex(pParse->db, pSchema);
80745   if( iDb<0 ){
80746     /* An attempt to read a column out of a subquery or other
80747     ** temporary table. */
80748     return;
80749   }
80750
80751   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
80752   if( pExpr->op==TK_TRIGGER ){
80753     pTab = pParse->pTriggerTab;
80754   }else{
80755     assert( pTabList );
80756     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
80757       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
80758         pTab = pTabList->a[iSrc].pTab;
80759         break;
80760       }
80761     }
80762   }
80763   iCol = pExpr->iColumn;
80764   if( NEVER(pTab==0) ) return;
80765
80766   if( iCol>=0 ){
80767     assert( iCol<pTab->nCol );
80768     zCol = pTab->aCol[iCol].zName;
80769   }else if( pTab->iPKey>=0 ){
80770     assert( pTab->iPKey<pTab->nCol );
80771     zCol = pTab->aCol[pTab->iPKey].zName;
80772   }else{
80773     zCol = "ROWID";
80774   }
80775   assert( iDb>=0 && iDb<db->nDb );
80776   if( SQLCIPHER_IGNORE==sqlcipher3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
80777     pExpr->op = TK_NULL;
80778   }
80779 }
80780
80781 /*
80782 ** Do an authorization check using the code and arguments given.  Return
80783 ** either SQLCIPHER_OK (zero) or SQLCIPHER_IGNORE or SQLCIPHER_DENY.  If SQLCIPHER_DENY
80784 ** is returned, then the error count and error message in pParse are
80785 ** modified appropriately.
80786 */
80787 SQLCIPHER_PRIVATE int sqlcipher3AuthCheck(
80788   Parse *pParse,
80789   int code,
80790   const char *zArg1,
80791   const char *zArg2,
80792   const char *zArg3
80793 ){
80794   sqlcipher3 *db = pParse->db;
80795   int rc;
80796
80797   /* Don't do any authorization checks if the database is initialising
80798   ** or if the parser is being invoked from within sqlcipher3_declare_vtab.
80799   */
80800   if( db->init.busy || IN_DECLARE_VTAB ){
80801     return SQLCIPHER_OK;
80802   }
80803
80804   if( db->xAuth==0 ){
80805     return SQLCIPHER_OK;
80806   }
80807   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
80808   if( rc==SQLCIPHER_DENY ){
80809     sqlcipher3ErrorMsg(pParse, "not authorized");
80810     pParse->rc = SQLCIPHER_AUTH;
80811   }else if( rc!=SQLCIPHER_OK && rc!=SQLCIPHER_IGNORE ){
80812     rc = SQLCIPHER_DENY;
80813     sqlcipherAuthBadReturnCode(pParse);
80814   }
80815   return rc;
80816 }
80817
80818 /*
80819 ** Push an authorization context.  After this routine is called, the
80820 ** zArg3 argument to authorization callbacks will be zContext until
80821 ** popped.  Or if pParse==0, this routine is a no-op.
80822 */
80823 SQLCIPHER_PRIVATE void sqlcipher3AuthContextPush(
80824   Parse *pParse,
80825   AuthContext *pContext, 
80826   const char *zContext
80827 ){
80828   assert( pParse );
80829   pContext->pParse = pParse;
80830   pContext->zAuthContext = pParse->zAuthContext;
80831   pParse->zAuthContext = zContext;
80832 }
80833
80834 /*
80835 ** Pop an authorization context that was previously pushed
80836 ** by sqlcipher3AuthContextPush
80837 */
80838 SQLCIPHER_PRIVATE void sqlcipher3AuthContextPop(AuthContext *pContext){
80839   if( pContext->pParse ){
80840     pContext->pParse->zAuthContext = pContext->zAuthContext;
80841     pContext->pParse = 0;
80842   }
80843 }
80844
80845 #endif /* SQLCIPHER_OMIT_AUTHORIZATION */
80846
80847 /************** End of auth.c ************************************************/
80848 /************** Begin file build.c *******************************************/
80849 /*
80850 ** 2001 September 15
80851 **
80852 ** The author disclaims copyright to this source code.  In place of
80853 ** a legal notice, here is a blessing:
80854 **
80855 **    May you do good and not evil.
80856 **    May you find forgiveness for yourself and forgive others.
80857 **    May you share freely, never taking more than you give.
80858 **
80859 *************************************************************************
80860 ** This file contains C code routines that are called by the SQLite parser
80861 ** when syntax rules are reduced.  The routines in this file handle the
80862 ** following kinds of SQL syntax:
80863 **
80864 **     CREATE TABLE
80865 **     DROP TABLE
80866 **     CREATE INDEX
80867 **     DROP INDEX
80868 **     creating ID lists
80869 **     BEGIN TRANSACTION
80870 **     COMMIT
80871 **     ROLLBACK
80872 */
80873
80874 /*
80875 ** This routine is called when a new SQL statement is beginning to
80876 ** be parsed.  Initialize the pParse structure as needed.
80877 */
80878 SQLCIPHER_PRIVATE void sqlcipher3BeginParse(Parse *pParse, int explainFlag){
80879   pParse->explain = (u8)explainFlag;
80880   pParse->nVar = 0;
80881 }
80882
80883 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
80884 /*
80885 ** The TableLock structure is only used by the sqlcipher3TableLock() and
80886 ** codeTableLocks() functions.
80887 */
80888 struct TableLock {
80889   int iDb;             /* The database containing the table to be locked */
80890   int iTab;            /* The root page of the table to be locked */
80891   u8 isWriteLock;      /* True for write lock.  False for a read lock */
80892   const char *zName;   /* Name of the table */
80893 };
80894
80895 /*
80896 ** Record the fact that we want to lock a table at run-time.  
80897 **
80898 ** The table to be locked has root page iTab and is found in database iDb.
80899 ** A read or a write lock can be taken depending on isWritelock.
80900 **
80901 ** This routine just records the fact that the lock is desired.  The
80902 ** code to make the lock occur is generated by a later call to
80903 ** codeTableLocks() which occurs during sqlcipher3FinishCoding().
80904 */
80905 SQLCIPHER_PRIVATE void sqlcipher3TableLock(
80906   Parse *pParse,     /* Parsing context */
80907   int iDb,           /* Index of the database containing the table to lock */
80908   int iTab,          /* Root page number of the table to be locked */
80909   u8 isWriteLock,    /* True for a write lock */
80910   const char *zName  /* Name of the table to be locked */
80911 ){
80912   Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
80913   int i;
80914   int nBytes;
80915   TableLock *p;
80916   assert( iDb>=0 );
80917
80918   for(i=0; i<pToplevel->nTableLock; i++){
80919     p = &pToplevel->aTableLock[i];
80920     if( p->iDb==iDb && p->iTab==iTab ){
80921       p->isWriteLock = (p->isWriteLock || isWriteLock);
80922       return;
80923     }
80924   }
80925
80926   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
80927   pToplevel->aTableLock =
80928       sqlcipher3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
80929   if( pToplevel->aTableLock ){
80930     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
80931     p->iDb = iDb;
80932     p->iTab = iTab;
80933     p->isWriteLock = isWriteLock;
80934     p->zName = zName;
80935   }else{
80936     pToplevel->nTableLock = 0;
80937     pToplevel->db->mallocFailed = 1;
80938   }
80939 }
80940
80941 /*
80942 ** Code an OP_TableLock instruction for each table locked by the
80943 ** statement (configured by calls to sqlcipher3TableLock()).
80944 */
80945 static void codeTableLocks(Parse *pParse){
80946   int i;
80947   Vdbe *pVdbe; 
80948
80949   pVdbe = sqlcipher3GetVdbe(pParse);
80950   assert( pVdbe!=0 ); /* sqlcipher3GetVdbe cannot fail: VDBE already allocated */
80951
80952   for(i=0; i<pParse->nTableLock; i++){
80953     TableLock *p = &pParse->aTableLock[i];
80954     int p1 = p->iDb;
80955     sqlcipher3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
80956                       p->zName, P4_STATIC);
80957   }
80958 }
80959 #else
80960   #define codeTableLocks(x)
80961 #endif
80962
80963 /*
80964 ** This routine is called after a single SQL statement has been
80965 ** parsed and a VDBE program to execute that statement has been
80966 ** prepared.  This routine puts the finishing touches on the
80967 ** VDBE program and resets the pParse structure for the next
80968 ** parse.
80969 **
80970 ** Note that if an error occurred, it might be the case that
80971 ** no VDBE code was generated.
80972 */
80973 SQLCIPHER_PRIVATE void sqlcipher3FinishCoding(Parse *pParse){
80974   sqlcipher3 *db;
80975   Vdbe *v;
80976
80977   db = pParse->db;
80978   if( db->mallocFailed ) return;
80979   if( pParse->nested ) return;
80980   if( pParse->nErr ) return;
80981
80982   /* Begin by generating some termination code at the end of the
80983   ** vdbe program
80984   */
80985   v = sqlcipher3GetVdbe(pParse);
80986   assert( !pParse->isMultiWrite 
80987        || sqlcipher3VdbeAssertMayAbort(v, pParse->mayAbort));
80988   if( v ){
80989     sqlcipher3VdbeAddOp0(v, OP_Halt);
80990
80991     /* The cookie mask contains one bit for each database file open.
80992     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
80993     ** set for each database that is used.  Generate code to start a
80994     ** transaction on each used database and to verify the schema cookie
80995     ** on each used database.
80996     */
80997     if( pParse->cookieGoto>0 ){
80998       yDbMask mask;
80999       int iDb;
81000       sqlcipher3VdbeJumpHere(v, pParse->cookieGoto-1);
81001       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
81002         if( (mask & pParse->cookieMask)==0 ) continue;
81003         sqlcipher3VdbeUsesBtree(v, iDb);
81004         sqlcipher3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
81005         if( db->init.busy==0 ){
81006           assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
81007           sqlcipher3VdbeAddOp3(v, OP_VerifyCookie,
81008                             iDb, pParse->cookieValue[iDb],
81009                             db->aDb[iDb].pSchema->iGeneration);
81010         }
81011       }
81012 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
81013       {
81014         int i;
81015         for(i=0; i<pParse->nVtabLock; i++){
81016           char *vtab = (char *)sqlcipher3GetVTable(db, pParse->apVtabLock[i]);
81017           sqlcipher3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
81018         }
81019         pParse->nVtabLock = 0;
81020       }
81021 #endif
81022
81023       /* Once all the cookies have been verified and transactions opened, 
81024       ** obtain the required table-locks. This is a no-op unless the 
81025       ** shared-cache feature is enabled.
81026       */
81027       codeTableLocks(pParse);
81028
81029       /* Initialize any AUTOINCREMENT data structures required.
81030       */
81031       sqlcipher3AutoincrementBegin(pParse);
81032
81033       /* Finally, jump back to the beginning of the executable code. */
81034       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
81035     }
81036   }
81037
81038
81039   /* Get the VDBE program ready for execution
81040   */
81041   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
81042 #ifdef SQLCIPHER_DEBUG
81043     FILE *trace = (db->flags & SQLCIPHER_VdbeTrace)!=0 ? stdout : 0;
81044     sqlcipher3VdbeTrace(v, trace);
81045 #endif
81046     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
81047     /* A minimum of one cursor is required if autoincrement is used
81048     *  See ticket [a696379c1f08866] */
81049     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
81050     sqlcipher3VdbeMakeReady(v, pParse);
81051     pParse->rc = SQLCIPHER_DONE;
81052     pParse->colNamesSet = 0;
81053   }else{
81054     pParse->rc = SQLCIPHER_ERROR;
81055   }
81056   pParse->nTab = 0;
81057   pParse->nMem = 0;
81058   pParse->nSet = 0;
81059   pParse->nVar = 0;
81060   pParse->cookieMask = 0;
81061   pParse->cookieGoto = 0;
81062 }
81063
81064 /*
81065 ** Run the parser and code generator recursively in order to generate
81066 ** code for the SQL statement given onto the end of the pParse context
81067 ** currently under construction.  When the parser is run recursively
81068 ** this way, the final OP_Halt is not appended and other initialization
81069 ** and finalization steps are omitted because those are handling by the
81070 ** outermost parser.
81071 **
81072 ** Not everything is nestable.  This facility is designed to permit
81073 ** INSERT, UPDATE, and DELETE operations against SQLCIPHER_MASTER.  Use
81074 ** care if you decide to try to use this routine for some other purposes.
81075 */
81076 SQLCIPHER_PRIVATE void sqlcipher3NestedParse(Parse *pParse, const char *zFormat, ...){
81077   va_list ap;
81078   char *zSql;
81079   char *zErrMsg = 0;
81080   sqlcipher3 *db = pParse->db;
81081 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
81082   char saveBuf[SAVE_SZ];
81083
81084   if( pParse->nErr ) return;
81085   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
81086   va_start(ap, zFormat);
81087   zSql = sqlcipher3VMPrintf(db, zFormat, ap);
81088   va_end(ap);
81089   if( zSql==0 ){
81090     return;   /* A malloc must have failed */
81091   }
81092   pParse->nested++;
81093   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
81094   memset(&pParse->nVar, 0, SAVE_SZ);
81095   sqlcipher3RunParser(pParse, zSql, &zErrMsg);
81096   sqlcipher3DbFree(db, zErrMsg);
81097   sqlcipher3DbFree(db, zSql);
81098   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
81099   pParse->nested--;
81100 }
81101
81102 /*
81103 ** Locate the in-memory structure that describes a particular database
81104 ** table given the name of that table and (optionally) the name of the
81105 ** database containing the table.  Return NULL if not found.
81106 **
81107 ** If zDatabase is 0, all databases are searched for the table and the
81108 ** first matching table is returned.  (No checking for duplicate table
81109 ** names is done.)  The search order is TEMP first, then MAIN, then any
81110 ** auxiliary databases added using the ATTACH command.
81111 **
81112 ** See also sqlcipher3LocateTable().
81113 */
81114 SQLCIPHER_PRIVATE Table *sqlcipher3FindTable(sqlcipher3 *db, const char *zName, const char *zDatabase){
81115   Table *p = 0;
81116   int i;
81117   int nName;
81118   assert( zName!=0 );
81119   nName = sqlcipher3Strlen30(zName);
81120   /* All mutexes are required for schema access.  Make sure we hold them. */
81121   assert( zDatabase!=0 || sqlcipher3BtreeHoldsAllMutexes(db) );
81122   for(i=OMIT_TEMPDB; i<db->nDb; i++){
81123     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
81124     if( zDatabase!=0 && sqlcipher3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
81125     assert( sqlcipher3SchemaMutexHeld(db, j, 0) );
81126     p = sqlcipher3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
81127     if( p ) break;
81128   }
81129   return p;
81130 }
81131
81132 /*
81133 ** Locate the in-memory structure that describes a particular database
81134 ** table given the name of that table and (optionally) the name of the
81135 ** database containing the table.  Return NULL if not found.  Also leave an
81136 ** error message in pParse->zErrMsg.
81137 **
81138 ** The difference between this routine and sqlcipher3FindTable() is that this
81139 ** routine leaves an error message in pParse->zErrMsg where
81140 ** sqlcipher3FindTable() does not.
81141 */
81142 SQLCIPHER_PRIVATE Table *sqlcipher3LocateTable(
81143   Parse *pParse,         /* context in which to report errors */
81144   int isView,            /* True if looking for a VIEW rather than a TABLE */
81145   const char *zName,     /* Name of the table we are looking for */
81146   const char *zDbase     /* Name of the database.  Might be NULL */
81147 ){
81148   Table *p;
81149
81150   /* Read the database schema. If an error occurs, leave an error message
81151   ** and code in pParse and return NULL. */
81152   if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
81153     return 0;
81154   }
81155
81156   p = sqlcipher3FindTable(pParse->db, zName, zDbase);
81157   if( p==0 ){
81158     const char *zMsg = isView ? "no such view" : "no such table";
81159     if( zDbase ){
81160       sqlcipher3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
81161     }else{
81162       sqlcipher3ErrorMsg(pParse, "%s: %s", zMsg, zName);
81163     }
81164     pParse->checkSchema = 1;
81165   }
81166   return p;
81167 }
81168
81169 /*
81170 ** Locate the in-memory structure that describes 
81171 ** a particular index given the name of that index
81172 ** and the name of the database that contains the index.
81173 ** Return NULL if not found.
81174 **
81175 ** If zDatabase is 0, all databases are searched for the
81176 ** table and the first matching index is returned.  (No checking
81177 ** for duplicate index names is done.)  The search order is
81178 ** TEMP first, then MAIN, then any auxiliary databases added
81179 ** using the ATTACH command.
81180 */
81181 SQLCIPHER_PRIVATE Index *sqlcipher3FindIndex(sqlcipher3 *db, const char *zName, const char *zDb){
81182   Index *p = 0;
81183   int i;
81184   int nName = sqlcipher3Strlen30(zName);
81185   /* All mutexes are required for schema access.  Make sure we hold them. */
81186   assert( zDb!=0 || sqlcipher3BtreeHoldsAllMutexes(db) );
81187   for(i=OMIT_TEMPDB; i<db->nDb; i++){
81188     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
81189     Schema *pSchema = db->aDb[j].pSchema;
81190     assert( pSchema );
81191     if( zDb && sqlcipher3StrICmp(zDb, db->aDb[j].zName) ) continue;
81192     assert( sqlcipher3SchemaMutexHeld(db, j, 0) );
81193     p = sqlcipher3HashFind(&pSchema->idxHash, zName, nName);
81194     if( p ) break;
81195   }
81196   return p;
81197 }
81198
81199 /*
81200 ** Reclaim the memory used by an index
81201 */
81202 static void freeIndex(sqlcipher3 *db, Index *p){
81203 #ifndef SQLCIPHER_OMIT_ANALYZE
81204   sqlcipher3DeleteIndexSamples(db, p);
81205 #endif
81206   sqlcipher3DbFree(db, p->zColAff);
81207   sqlcipher3DbFree(db, p);
81208 }
81209
81210 /*
81211 ** For the index called zIdxName which is found in the database iDb,
81212 ** unlike that index from its Table then remove the index from
81213 ** the index hash table and free all memory structures associated
81214 ** with the index.
81215 */
81216 SQLCIPHER_PRIVATE void sqlcipher3UnlinkAndDeleteIndex(sqlcipher3 *db, int iDb, const char *zIdxName){
81217   Index *pIndex;
81218   int len;
81219   Hash *pHash;
81220
81221   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
81222   pHash = &db->aDb[iDb].pSchema->idxHash;
81223   len = sqlcipher3Strlen30(zIdxName);
81224   pIndex = sqlcipher3HashInsert(pHash, zIdxName, len, 0);
81225   if( ALWAYS(pIndex) ){
81226     if( pIndex->pTable->pIndex==pIndex ){
81227       pIndex->pTable->pIndex = pIndex->pNext;
81228     }else{
81229       Index *p;
81230       /* Justification of ALWAYS();  The index must be on the list of
81231       ** indices. */
81232       p = pIndex->pTable->pIndex;
81233       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
81234       if( ALWAYS(p && p->pNext==pIndex) ){
81235         p->pNext = pIndex->pNext;
81236       }
81237     }
81238     freeIndex(db, pIndex);
81239   }
81240   db->flags |= SQLCIPHER_InternChanges;
81241 }
81242
81243 /*
81244 ** Erase all schema information from the in-memory hash tables of
81245 ** a single database.  This routine is called to reclaim memory
81246 ** before the database closes.  It is also called during a rollback
81247 ** if there were schema changes during the transaction or if a
81248 ** schema-cookie mismatch occurs.
81249 **
81250 ** If iDb<0 then reset the internal schema tables for all database
81251 ** files.  If iDb>=0 then reset the internal schema for only the
81252 ** single file indicated.
81253 */
81254 SQLCIPHER_PRIVATE void sqlcipher3ResetInternalSchema(sqlcipher3 *db, int iDb){
81255   int i, j;
81256   assert( iDb<db->nDb );
81257
81258   if( iDb>=0 ){
81259     /* Case 1:  Reset the single schema identified by iDb */
81260     Db *pDb = &db->aDb[iDb];
81261     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
81262     assert( pDb->pSchema!=0 );
81263     sqlcipher3SchemaClear(pDb->pSchema);
81264
81265     /* If any database other than TEMP is reset, then also reset TEMP
81266     ** since TEMP might be holding triggers that reference tables in the
81267     ** other database.
81268     */
81269     if( iDb!=1 ){
81270       pDb = &db->aDb[1];
81271       assert( pDb->pSchema!=0 );
81272       sqlcipher3SchemaClear(pDb->pSchema);
81273     }
81274     return;
81275   }
81276   /* Case 2 (from here to the end): Reset all schemas for all attached
81277   ** databases. */
81278   assert( iDb<0 );
81279   sqlcipher3BtreeEnterAll(db);
81280   for(i=0; i<db->nDb; i++){
81281     Db *pDb = &db->aDb[i];
81282     if( pDb->pSchema ){
81283       sqlcipher3SchemaClear(pDb->pSchema);
81284     }
81285   }
81286   db->flags &= ~SQLCIPHER_InternChanges;
81287   sqlcipher3VtabUnlockList(db);
81288   sqlcipher3BtreeLeaveAll(db);
81289
81290   /* If one or more of the auxiliary database files has been closed,
81291   ** then remove them from the auxiliary database list.  We take the
81292   ** opportunity to do this here since we have just deleted all of the
81293   ** schema hash tables and therefore do not have to make any changes
81294   ** to any of those tables.
81295   */
81296   for(i=j=2; i<db->nDb; i++){
81297     struct Db *pDb = &db->aDb[i];
81298     if( pDb->pBt==0 ){
81299       sqlcipher3DbFree(db, pDb->zName);
81300       pDb->zName = 0;
81301       continue;
81302     }
81303     if( j<i ){
81304       db->aDb[j] = db->aDb[i];
81305     }
81306     j++;
81307   }
81308   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
81309   db->nDb = j;
81310   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
81311     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
81312     sqlcipher3DbFree(db, db->aDb);
81313     db->aDb = db->aDbStatic;
81314   }
81315 }
81316
81317 /*
81318 ** This routine is called when a commit occurs.
81319 */
81320 SQLCIPHER_PRIVATE void sqlcipher3CommitInternalChanges(sqlcipher3 *db){
81321   db->flags &= ~SQLCIPHER_InternChanges;
81322 }
81323
81324 /*
81325 ** Delete memory allocated for the column names of a table or view (the
81326 ** Table.aCol[] array).
81327 */
81328 static void sqlcipherDeleteColumnNames(sqlcipher3 *db, Table *pTable){
81329   int i;
81330   Column *pCol;
81331   assert( pTable!=0 );
81332   if( (pCol = pTable->aCol)!=0 ){
81333     for(i=0; i<pTable->nCol; i++, pCol++){
81334       sqlcipher3DbFree(db, pCol->zName);
81335       sqlcipher3ExprDelete(db, pCol->pDflt);
81336       sqlcipher3DbFree(db, pCol->zDflt);
81337       sqlcipher3DbFree(db, pCol->zType);
81338       sqlcipher3DbFree(db, pCol->zColl);
81339     }
81340     sqlcipher3DbFree(db, pTable->aCol);
81341   }
81342 }
81343
81344 /*
81345 ** Remove the memory data structures associated with the given
81346 ** Table.  No changes are made to disk by this routine.
81347 **
81348 ** This routine just deletes the data structure.  It does not unlink
81349 ** the table data structure from the hash table.  But it does destroy
81350 ** memory structures of the indices and foreign keys associated with 
81351 ** the table.
81352 */
81353 SQLCIPHER_PRIVATE void sqlcipher3DeleteTable(sqlcipher3 *db, Table *pTable){
81354   Index *pIndex, *pNext;
81355
81356   assert( !pTable || pTable->nRef>0 );
81357
81358   /* Do not delete the table until the reference count reaches zero. */
81359   if( !pTable ) return;
81360   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
81361
81362   /* Delete all indices associated with this table. */
81363   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
81364     pNext = pIndex->pNext;
81365     assert( pIndex->pSchema==pTable->pSchema );
81366     if( !db || db->pnBytesFreed==0 ){
81367       char *zName = pIndex->zName; 
81368       TESTONLY ( Index *pOld = ) sqlcipher3HashInsert(
81369           &pIndex->pSchema->idxHash, zName, sqlcipher3Strlen30(zName), 0
81370       );
81371       assert( db==0 || sqlcipher3SchemaMutexHeld(db, 0, pIndex->pSchema) );
81372       assert( pOld==pIndex || pOld==0 );
81373     }
81374     freeIndex(db, pIndex);
81375   }
81376
81377   /* Delete any foreign keys attached to this table. */
81378   sqlcipher3FkDelete(db, pTable);
81379
81380   /* Delete the Table structure itself.
81381   */
81382   sqlcipherDeleteColumnNames(db, pTable);
81383   sqlcipher3DbFree(db, pTable->zName);
81384   sqlcipher3DbFree(db, pTable->zColAff);
81385   sqlcipher3SelectDelete(db, pTable->pSelect);
81386 #ifndef SQLCIPHER_OMIT_CHECK
81387   sqlcipher3ExprDelete(db, pTable->pCheck);
81388 #endif
81389 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
81390   sqlcipher3VtabClear(db, pTable);
81391 #endif
81392   sqlcipher3DbFree(db, pTable);
81393 }
81394
81395 /*
81396 ** Unlink the given table from the hash tables and the delete the
81397 ** table structure with all its indices and foreign keys.
81398 */
81399 SQLCIPHER_PRIVATE void sqlcipher3UnlinkAndDeleteTable(sqlcipher3 *db, int iDb, const char *zTabName){
81400   Table *p;
81401   Db *pDb;
81402
81403   assert( db!=0 );
81404   assert( iDb>=0 && iDb<db->nDb );
81405   assert( zTabName );
81406   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
81407   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
81408   pDb = &db->aDb[iDb];
81409   p = sqlcipher3HashInsert(&pDb->pSchema->tblHash, zTabName,
81410                         sqlcipher3Strlen30(zTabName),0);
81411   sqlcipher3DeleteTable(db, p);
81412   db->flags |= SQLCIPHER_InternChanges;
81413 }
81414
81415 /*
81416 ** Given a token, return a string that consists of the text of that
81417 ** token.  Space to hold the returned string
81418 ** is obtained from sqlcipherMalloc() and must be freed by the calling
81419 ** function.
81420 **
81421 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
81422 ** surround the body of the token are removed.
81423 **
81424 ** Tokens are often just pointers into the original SQL text and so
81425 ** are not \000 terminated and are not persistent.  The returned string
81426 ** is \000 terminated and is persistent.
81427 */
81428 SQLCIPHER_PRIVATE char *sqlcipher3NameFromToken(sqlcipher3 *db, Token *pName){
81429   char *zName;
81430   if( pName ){
81431     zName = sqlcipher3DbStrNDup(db, (char*)pName->z, pName->n);
81432     sqlcipher3Dequote(zName);
81433   }else{
81434     zName = 0;
81435   }
81436   return zName;
81437 }
81438
81439 /*
81440 ** Open the sqlcipher_master table stored in database number iDb for
81441 ** writing. The table is opened using cursor 0.
81442 */
81443 SQLCIPHER_PRIVATE void sqlcipher3OpenMasterTable(Parse *p, int iDb){
81444   Vdbe *v = sqlcipher3GetVdbe(p);
81445   sqlcipher3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
81446   sqlcipher3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
81447   sqlcipher3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
81448   if( p->nTab==0 ){
81449     p->nTab = 1;
81450   }
81451 }
81452
81453 /*
81454 ** Parameter zName points to a nul-terminated buffer containing the name
81455 ** of a database ("main", "temp" or the name of an attached db). This
81456 ** function returns the index of the named database in db->aDb[], or
81457 ** -1 if the named db cannot be found.
81458 */
81459 SQLCIPHER_PRIVATE int sqlcipher3FindDbName(sqlcipher3 *db, const char *zName){
81460   int i = -1;         /* Database number */
81461   if( zName ){
81462     Db *pDb;
81463     int n = sqlcipher3Strlen30(zName);
81464     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
81465       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlcipher3Strlen30(pDb->zName) && 
81466           0==sqlcipher3StrICmp(pDb->zName, zName) ){
81467         break;
81468       }
81469     }
81470   }
81471   return i;
81472 }
81473
81474 /*
81475 ** The token *pName contains the name of a database (either "main" or
81476 ** "temp" or the name of an attached db). This routine returns the
81477 ** index of the named database in db->aDb[], or -1 if the named db 
81478 ** does not exist.
81479 */
81480 SQLCIPHER_PRIVATE int sqlcipher3FindDb(sqlcipher3 *db, Token *pName){
81481   int i;                               /* Database number */
81482   char *zName;                         /* Name we are searching for */
81483   zName = sqlcipher3NameFromToken(db, pName);
81484   i = sqlcipher3FindDbName(db, zName);
81485   sqlcipher3DbFree(db, zName);
81486   return i;
81487 }
81488
81489 /* The table or view or trigger name is passed to this routine via tokens
81490 ** pName1 and pName2. If the table name was fully qualified, for example:
81491 **
81492 ** CREATE TABLE xxx.yyy (...);
81493 ** 
81494 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81495 ** the table name is not fully qualified, i.e.:
81496 **
81497 ** CREATE TABLE yyy(...);
81498 **
81499 ** Then pName1 is set to "yyy" and pName2 is "".
81500 **
81501 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
81502 ** pName2) that stores the unqualified table name.  The index of the
81503 ** database "xxx" is returned.
81504 */
81505 SQLCIPHER_PRIVATE int sqlcipher3TwoPartName(
81506   Parse *pParse,      /* Parsing and code generating context */
81507   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
81508   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
81509   Token **pUnqual     /* Write the unqualified object name here */
81510 ){
81511   int iDb;                    /* Database holding the object */
81512   sqlcipher3 *db = pParse->db;
81513
81514   if( ALWAYS(pName2!=0) && pName2->n>0 ){
81515     if( db->init.busy ) {
81516       sqlcipher3ErrorMsg(pParse, "corrupt database");
81517       pParse->nErr++;
81518       return -1;
81519     }
81520     *pUnqual = pName2;
81521     iDb = sqlcipher3FindDb(db, pName1);
81522     if( iDb<0 ){
81523       sqlcipher3ErrorMsg(pParse, "unknown database %T", pName1);
81524       pParse->nErr++;
81525       return -1;
81526     }
81527   }else{
81528     assert( db->init.iDb==0 || db->init.busy );
81529     iDb = db->init.iDb;
81530     *pUnqual = pName1;
81531   }
81532   return iDb;
81533 }
81534
81535 /*
81536 ** This routine is used to check if the UTF-8 string zName is a legal
81537 ** unqualified name for a new schema object (table, index, view or
81538 ** trigger). All names are legal except those that begin with the string
81539 ** "sqlcipher_" (in upper, lower or mixed case). This portion of the namespace
81540 ** is reserved for internal use.
81541 */
81542 SQLCIPHER_PRIVATE int sqlcipher3CheckObjectName(Parse *pParse, const char *zName){
81543   if( !pParse->db->init.busy && pParse->nested==0 
81544           && (pParse->db->flags & SQLCIPHER_WriteSchema)==0
81545           && 0==sqlcipher3StrNICmp(zName, "sqlcipher_", 7) ){
81546     sqlcipher3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
81547     return SQLCIPHER_ERROR;
81548   }
81549   return SQLCIPHER_OK;
81550 }
81551
81552 /*
81553 ** Begin constructing a new table representation in memory.  This is
81554 ** the first of several action routines that get called in response
81555 ** to a CREATE TABLE statement.  In particular, this routine is called
81556 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
81557 ** flag is true if the table should be stored in the auxiliary database
81558 ** file instead of in the main database file.  This is normally the case
81559 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
81560 ** CREATE and TABLE.
81561 **
81562 ** The new table record is initialized and put in pParse->pNewTable.
81563 ** As more of the CREATE TABLE statement is parsed, additional action
81564 ** routines will be called to add more information to this record.
81565 ** At the end of the CREATE TABLE statement, the sqlcipher3EndTable() routine
81566 ** is called to complete the construction of the new table record.
81567 */
81568 SQLCIPHER_PRIVATE void sqlcipher3StartTable(
81569   Parse *pParse,   /* Parser context */
81570   Token *pName1,   /* First part of the name of the table or view */
81571   Token *pName2,   /* Second part of the name of the table or view */
81572   int isTemp,      /* True if this is a TEMP table */
81573   int isView,      /* True if this is a VIEW */
81574   int isVirtual,   /* True if this is a VIRTUAL table */
81575   int noErr        /* Do nothing if table already exists */
81576 ){
81577   Table *pTable;
81578   char *zName = 0; /* The name of the new table */
81579   sqlcipher3 *db = pParse->db;
81580   Vdbe *v;
81581   int iDb;         /* Database number to create the table in */
81582   Token *pName;    /* Unqualified name of the table to create */
81583
81584   /* The table or view name to create is passed to this routine via tokens
81585   ** pName1 and pName2. If the table name was fully qualified, for example:
81586   **
81587   ** CREATE TABLE xxx.yyy (...);
81588   ** 
81589   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81590   ** the table name is not fully qualified, i.e.:
81591   **
81592   ** CREATE TABLE yyy(...);
81593   **
81594   ** Then pName1 is set to "yyy" and pName2 is "".
81595   **
81596   ** The call below sets the pName pointer to point at the token (pName1 or
81597   ** pName2) that stores the unqualified table name. The variable iDb is
81598   ** set to the index of the database that the table or view is to be
81599   ** created in.
81600   */
81601   iDb = sqlcipher3TwoPartName(pParse, pName1, pName2, &pName);
81602   if( iDb<0 ) return;
81603   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
81604     /* If creating a temp table, the name may not be qualified. Unless 
81605     ** the database name is "temp" anyway.  */
81606     sqlcipher3ErrorMsg(pParse, "temporary table name must be unqualified");
81607     return;
81608   }
81609   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
81610
81611   pParse->sNameToken = *pName;
81612   zName = sqlcipher3NameFromToken(db, pName);
81613   if( zName==0 ) return;
81614   if( SQLCIPHER_OK!=sqlcipher3CheckObjectName(pParse, zName) ){
81615     goto begin_table_error;
81616   }
81617   if( db->init.iDb==1 ) isTemp = 1;
81618 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
81619   assert( (isTemp & 1)==isTemp );
81620   {
81621     int code;
81622     char *zDb = db->aDb[iDb].zName;
81623     if( sqlcipher3AuthCheck(pParse, SQLCIPHER_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
81624       goto begin_table_error;
81625     }
81626     if( isView ){
81627       if( !OMIT_TEMPDB && isTemp ){
81628         code = SQLCIPHER_CREATE_TEMP_VIEW;
81629       }else{
81630         code = SQLCIPHER_CREATE_VIEW;
81631       }
81632     }else{
81633       if( !OMIT_TEMPDB && isTemp ){
81634         code = SQLCIPHER_CREATE_TEMP_TABLE;
81635       }else{
81636         code = SQLCIPHER_CREATE_TABLE;
81637       }
81638     }
81639     if( !isVirtual && sqlcipher3AuthCheck(pParse, code, zName, 0, zDb) ){
81640       goto begin_table_error;
81641     }
81642   }
81643 #endif
81644
81645   /* Make sure the new table name does not collide with an existing
81646   ** index or table name in the same database.  Issue an error message if
81647   ** it does. The exception is if the statement being parsed was passed
81648   ** to an sqlcipher3_declare_vtab() call. In that case only the column names
81649   ** and types will be used, so there is no need to test for namespace
81650   ** collisions.
81651   */
81652   if( !IN_DECLARE_VTAB ){
81653     char *zDb = db->aDb[iDb].zName;
81654     if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
81655       goto begin_table_error;
81656     }
81657     pTable = sqlcipher3FindTable(db, zName, zDb);
81658     if( pTable ){
81659       if( !noErr ){
81660         sqlcipher3ErrorMsg(pParse, "table %T already exists", pName);
81661       }else{
81662         assert( !db->init.busy );
81663         sqlcipher3CodeVerifySchema(pParse, iDb);
81664       }
81665       goto begin_table_error;
81666     }
81667     if( sqlcipher3FindIndex(db, zName, zDb)!=0 ){
81668       sqlcipher3ErrorMsg(pParse, "there is already an index named %s", zName);
81669       goto begin_table_error;
81670     }
81671   }
81672
81673   pTable = sqlcipher3DbMallocZero(db, sizeof(Table));
81674   if( pTable==0 ){
81675     db->mallocFailed = 1;
81676     pParse->rc = SQLCIPHER_NOMEM;
81677     pParse->nErr++;
81678     goto begin_table_error;
81679   }
81680   pTable->zName = zName;
81681   pTable->iPKey = -1;
81682   pTable->pSchema = db->aDb[iDb].pSchema;
81683   pTable->nRef = 1;
81684   pTable->nRowEst = 1000000;
81685   assert( pParse->pNewTable==0 );
81686   pParse->pNewTable = pTable;
81687
81688   /* If this is the magic sqlcipher_sequence table used by autoincrement,
81689   ** then record a pointer to this table in the main database structure
81690   ** so that INSERT can find the table easily.
81691   */
81692 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
81693   if( !pParse->nested && strcmp(zName, "sqlcipher_sequence")==0 ){
81694     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
81695     pTable->pSchema->pSeqTab = pTable;
81696   }
81697 #endif
81698
81699   /* Begin generating the code that will insert the table record into
81700   ** the SQLCIPHER_MASTER table.  Note in particular that we must go ahead
81701   ** and allocate the record number for the table entry now.  Before any
81702   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
81703   ** indices to be created and the table record must come before the 
81704   ** indices.  Hence, the record number for the table must be allocated
81705   ** now.
81706   */
81707   if( !db->init.busy && (v = sqlcipher3GetVdbe(pParse))!=0 ){
81708     int j1;
81709     int fileFormat;
81710     int reg1, reg2, reg3;
81711     sqlcipher3BeginWriteOperation(pParse, 0, iDb);
81712
81713 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
81714     if( isVirtual ){
81715       sqlcipher3VdbeAddOp0(v, OP_VBegin);
81716     }
81717 #endif
81718
81719     /* If the file format and encoding in the database have not been set, 
81720     ** set them now.
81721     */
81722     reg1 = pParse->regRowid = ++pParse->nMem;
81723     reg2 = pParse->regRoot = ++pParse->nMem;
81724     reg3 = ++pParse->nMem;
81725     sqlcipher3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
81726     sqlcipher3VdbeUsesBtree(v, iDb);
81727     j1 = sqlcipher3VdbeAddOp1(v, OP_If, reg3);
81728     fileFormat = (db->flags & SQLCIPHER_LegacyFileFmt)!=0 ?
81729                   1 : SQLCIPHER_MAX_FILE_FORMAT;
81730     sqlcipher3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
81731     sqlcipher3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
81732     sqlcipher3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
81733     sqlcipher3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
81734     sqlcipher3VdbeJumpHere(v, j1);
81735
81736     /* This just creates a place-holder record in the sqlcipher_master table.
81737     ** The record created does not contain anything yet.  It will be replaced
81738     ** by the real entry in code generated at sqlcipher3EndTable().
81739     **
81740     ** The rowid for the new entry is left in register pParse->regRowid.
81741     ** The root page number of the new table is left in reg pParse->regRoot.
81742     ** The rowid and root page number values are needed by the code that
81743     ** sqlcipher3EndTable will generate.
81744     */
81745 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_VIRTUALTABLE)
81746     if( isView || isVirtual ){
81747       sqlcipher3VdbeAddOp2(v, OP_Integer, 0, reg2);
81748     }else
81749 #endif
81750     {
81751       sqlcipher3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
81752     }
81753     sqlcipher3OpenMasterTable(pParse, iDb);
81754     sqlcipher3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
81755     sqlcipher3VdbeAddOp2(v, OP_Null, 0, reg3);
81756     sqlcipher3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
81757     sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
81758     sqlcipher3VdbeAddOp0(v, OP_Close);
81759   }
81760
81761   /* Normal (non-error) return. */
81762   return;
81763
81764   /* If an error occurs, we jump here */
81765 begin_table_error:
81766   sqlcipher3DbFree(db, zName);
81767   return;
81768 }
81769
81770 /*
81771 ** This macro is used to compare two strings in a case-insensitive manner.
81772 ** It is slightly faster than calling sqlcipher3StrICmp() directly, but
81773 ** produces larger code.
81774 **
81775 ** WARNING: This macro is not compatible with the strcmp() family. It
81776 ** returns true if the two strings are equal, otherwise false.
81777 */
81778 #define STRICMP(x, y) (\
81779 sqlcipher3UpperToLower[*(unsigned char *)(x)]==   \
81780 sqlcipher3UpperToLower[*(unsigned char *)(y)]     \
81781 && sqlcipher3StrICmp((x)+1,(y)+1)==0 )
81782
81783 /*
81784 ** Add a new column to the table currently being constructed.
81785 **
81786 ** The parser calls this routine once for each column declaration
81787 ** in a CREATE TABLE statement.  sqlcipher3StartTable() gets called
81788 ** first to get things going.  Then this routine is called for each
81789 ** column.
81790 */
81791 SQLCIPHER_PRIVATE void sqlcipher3AddColumn(Parse *pParse, Token *pName){
81792   Table *p;
81793   int i;
81794   char *z;
81795   Column *pCol;
81796   sqlcipher3 *db = pParse->db;
81797   if( (p = pParse->pNewTable)==0 ) return;
81798 #if SQLCIPHER_MAX_COLUMN
81799   if( p->nCol+1>db->aLimit[SQLCIPHER_LIMIT_COLUMN] ){
81800     sqlcipher3ErrorMsg(pParse, "too many columns on %s", p->zName);
81801     return;
81802   }
81803 #endif
81804   z = sqlcipher3NameFromToken(db, pName);
81805   if( z==0 ) return;
81806   for(i=0; i<p->nCol; i++){
81807     if( STRICMP(z, p->aCol[i].zName) ){
81808       sqlcipher3ErrorMsg(pParse, "duplicate column name: %s", z);
81809       sqlcipher3DbFree(db, z);
81810       return;
81811     }
81812   }
81813   if( (p->nCol & 0x7)==0 ){
81814     Column *aNew;
81815     aNew = sqlcipher3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
81816     if( aNew==0 ){
81817       sqlcipher3DbFree(db, z);
81818       return;
81819     }
81820     p->aCol = aNew;
81821   }
81822   pCol = &p->aCol[p->nCol];
81823   memset(pCol, 0, sizeof(p->aCol[0]));
81824   pCol->zName = z;
81825  
81826   /* If there is no type specified, columns have the default affinity
81827   ** 'NONE'. If there is a type specified, then sqlcipher3AddColumnType() will
81828   ** be called next to set pCol->affinity correctly.
81829   */
81830   pCol->affinity = SQLCIPHER_AFF_NONE;
81831   p->nCol++;
81832 }
81833
81834 /*
81835 ** This routine is called by the parser while in the middle of
81836 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
81837 ** been seen on a column.  This routine sets the notNull flag on
81838 ** the column currently under construction.
81839 */
81840 SQLCIPHER_PRIVATE void sqlcipher3AddNotNull(Parse *pParse, int onError){
81841   Table *p;
81842   p = pParse->pNewTable;
81843   if( p==0 || NEVER(p->nCol<1) ) return;
81844   p->aCol[p->nCol-1].notNull = (u8)onError;
81845 }
81846
81847 /*
81848 ** Scan the column type name zType (length nType) and return the
81849 ** associated affinity type.
81850 **
81851 ** This routine does a case-independent search of zType for the 
81852 ** substrings in the following table. If one of the substrings is
81853 ** found, the corresponding affinity is returned. If zType contains
81854 ** more than one of the substrings, entries toward the top of 
81855 ** the table take priority. For example, if zType is 'BLOBINT', 
81856 ** SQLCIPHER_AFF_INTEGER is returned.
81857 **
81858 ** Substring     | Affinity
81859 ** --------------------------------
81860 ** 'INT'         | SQLCIPHER_AFF_INTEGER
81861 ** 'CHAR'        | SQLCIPHER_AFF_TEXT
81862 ** 'CLOB'        | SQLCIPHER_AFF_TEXT
81863 ** 'TEXT'        | SQLCIPHER_AFF_TEXT
81864 ** 'BLOB'        | SQLCIPHER_AFF_NONE
81865 ** 'REAL'        | SQLCIPHER_AFF_REAL
81866 ** 'FLOA'        | SQLCIPHER_AFF_REAL
81867 ** 'DOUB'        | SQLCIPHER_AFF_REAL
81868 **
81869 ** If none of the substrings in the above table are found,
81870 ** SQLCIPHER_AFF_NUMERIC is returned.
81871 */
81872 SQLCIPHER_PRIVATE char sqlcipher3AffinityType(const char *zIn){
81873   u32 h = 0;
81874   char aff = SQLCIPHER_AFF_NUMERIC;
81875
81876   if( zIn ) while( zIn[0] ){
81877     h = (h<<8) + sqlcipher3UpperToLower[(*zIn)&0xff];
81878     zIn++;
81879     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
81880       aff = SQLCIPHER_AFF_TEXT; 
81881     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
81882       aff = SQLCIPHER_AFF_TEXT;
81883     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
81884       aff = SQLCIPHER_AFF_TEXT;
81885     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
81886         && (aff==SQLCIPHER_AFF_NUMERIC || aff==SQLCIPHER_AFF_REAL) ){
81887       aff = SQLCIPHER_AFF_NONE;
81888 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
81889     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
81890         && aff==SQLCIPHER_AFF_NUMERIC ){
81891       aff = SQLCIPHER_AFF_REAL;
81892     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
81893         && aff==SQLCIPHER_AFF_NUMERIC ){
81894       aff = SQLCIPHER_AFF_REAL;
81895     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
81896         && aff==SQLCIPHER_AFF_NUMERIC ){
81897       aff = SQLCIPHER_AFF_REAL;
81898 #endif
81899     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
81900       aff = SQLCIPHER_AFF_INTEGER;
81901       break;
81902     }
81903   }
81904
81905   return aff;
81906 }
81907
81908 /*
81909 ** This routine is called by the parser while in the middle of
81910 ** parsing a CREATE TABLE statement.  The pFirst token is the first
81911 ** token in the sequence of tokens that describe the type of the
81912 ** column currently under construction.   pLast is the last token
81913 ** in the sequence.  Use this information to construct a string
81914 ** that contains the typename of the column and store that string
81915 ** in zType.
81916 */ 
81917 SQLCIPHER_PRIVATE void sqlcipher3AddColumnType(Parse *pParse, Token *pType){
81918   Table *p;
81919   Column *pCol;
81920
81921   p = pParse->pNewTable;
81922   if( p==0 || NEVER(p->nCol<1) ) return;
81923   pCol = &p->aCol[p->nCol-1];
81924   assert( pCol->zType==0 );
81925   pCol->zType = sqlcipher3NameFromToken(pParse->db, pType);
81926   pCol->affinity = sqlcipher3AffinityType(pCol->zType);
81927 }
81928
81929 /*
81930 ** The expression is the default value for the most recently added column
81931 ** of the table currently under construction.
81932 **
81933 ** Default value expressions must be constant.  Raise an exception if this
81934 ** is not the case.
81935 **
81936 ** This routine is called by the parser while in the middle of
81937 ** parsing a CREATE TABLE statement.
81938 */
81939 SQLCIPHER_PRIVATE void sqlcipher3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
81940   Table *p;
81941   Column *pCol;
81942   sqlcipher3 *db = pParse->db;
81943   p = pParse->pNewTable;
81944   if( p!=0 ){
81945     pCol = &(p->aCol[p->nCol-1]);
81946     if( !sqlcipher3ExprIsConstantOrFunction(pSpan->pExpr) ){
81947       sqlcipher3ErrorMsg(pParse, "default value of column [%s] is not constant",
81948           pCol->zName);
81949     }else{
81950       /* A copy of pExpr is used instead of the original, as pExpr contains
81951       ** tokens that point to volatile memory. The 'span' of the expression
81952       ** is required by pragma table_info.
81953       */
81954       sqlcipher3ExprDelete(db, pCol->pDflt);
81955       pCol->pDflt = sqlcipher3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
81956       sqlcipher3DbFree(db, pCol->zDflt);
81957       pCol->zDflt = sqlcipher3DbStrNDup(db, (char*)pSpan->zStart,
81958                                      (int)(pSpan->zEnd - pSpan->zStart));
81959     }
81960   }
81961   sqlcipher3ExprDelete(db, pSpan->pExpr);
81962 }
81963
81964 /*
81965 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
81966 ** of columns that form the primary key.  If pList is NULL, then the
81967 ** most recently added column of the table is the primary key.
81968 **
81969 ** A table can have at most one primary key.  If the table already has
81970 ** a primary key (and this is the second primary key) then create an
81971 ** error.
81972 **
81973 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
81974 ** then we will try to use that column as the rowid.  Set the Table.iPKey
81975 ** field of the table under construction to be the index of the
81976 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
81977 ** no INTEGER PRIMARY KEY.
81978 **
81979 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
81980 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
81981 */
81982 SQLCIPHER_PRIVATE void sqlcipher3AddPrimaryKey(
81983   Parse *pParse,    /* Parsing context */
81984   ExprList *pList,  /* List of field names to be indexed */
81985   int onError,      /* What to do with a uniqueness conflict */
81986   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
81987   int sortOrder     /* SQLCIPHER_SO_ASC or SQLCIPHER_SO_DESC */
81988 ){
81989   Table *pTab = pParse->pNewTable;
81990   char *zType = 0;
81991   int iCol = -1, i;
81992   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
81993   if( pTab->tabFlags & TF_HasPrimaryKey ){
81994     sqlcipher3ErrorMsg(pParse, 
81995       "table \"%s\" has more than one primary key", pTab->zName);
81996     goto primary_key_exit;
81997   }
81998   pTab->tabFlags |= TF_HasPrimaryKey;
81999   if( pList==0 ){
82000     iCol = pTab->nCol - 1;
82001     pTab->aCol[iCol].isPrimKey = 1;
82002   }else{
82003     for(i=0; i<pList->nExpr; i++){
82004       for(iCol=0; iCol<pTab->nCol; iCol++){
82005         if( sqlcipher3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
82006           break;
82007         }
82008       }
82009       if( iCol<pTab->nCol ){
82010         pTab->aCol[iCol].isPrimKey = 1;
82011       }
82012     }
82013     if( pList->nExpr>1 ) iCol = -1;
82014   }
82015   if( iCol>=0 && iCol<pTab->nCol ){
82016     zType = pTab->aCol[iCol].zType;
82017   }
82018   if( zType && sqlcipher3StrICmp(zType, "INTEGER")==0
82019         && sortOrder==SQLCIPHER_SO_ASC ){
82020     pTab->iPKey = iCol;
82021     pTab->keyConf = (u8)onError;
82022     assert( autoInc==0 || autoInc==1 );
82023     pTab->tabFlags |= autoInc*TF_Autoincrement;
82024   }else if( autoInc ){
82025 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
82026     sqlcipher3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
82027        "INTEGER PRIMARY KEY");
82028 #endif
82029   }else{
82030     Index *p;
82031     p = sqlcipher3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
82032     if( p ){
82033       p->autoIndex = 2;
82034     }
82035     pList = 0;
82036   }
82037
82038 primary_key_exit:
82039   sqlcipher3ExprListDelete(pParse->db, pList);
82040   return;
82041 }
82042
82043 /*
82044 ** Add a new CHECK constraint to the table currently under construction.
82045 */
82046 SQLCIPHER_PRIVATE void sqlcipher3AddCheckConstraint(
82047   Parse *pParse,    /* Parsing context */
82048   Expr *pCheckExpr  /* The check expression */
82049 ){
82050   sqlcipher3 *db = pParse->db;
82051 #ifndef SQLCIPHER_OMIT_CHECK
82052   Table *pTab = pParse->pNewTable;
82053   if( pTab && !IN_DECLARE_VTAB ){
82054     pTab->pCheck = sqlcipher3ExprAnd(db, pTab->pCheck, pCheckExpr);
82055   }else
82056 #endif
82057   {
82058     sqlcipher3ExprDelete(db, pCheckExpr);
82059   }
82060 }
82061
82062 /*
82063 ** Set the collation function of the most recently parsed table column
82064 ** to the CollSeq given.
82065 */
82066 SQLCIPHER_PRIVATE void sqlcipher3AddCollateType(Parse *pParse, Token *pToken){
82067   Table *p;
82068   int i;
82069   char *zColl;              /* Dequoted name of collation sequence */
82070   sqlcipher3 *db;
82071
82072   if( (p = pParse->pNewTable)==0 ) return;
82073   i = p->nCol-1;
82074   db = pParse->db;
82075   zColl = sqlcipher3NameFromToken(db, pToken);
82076   if( !zColl ) return;
82077
82078   if( sqlcipher3LocateCollSeq(pParse, zColl) ){
82079     Index *pIdx;
82080     p->aCol[i].zColl = zColl;
82081   
82082     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
82083     ** then an index may have been created on this column before the
82084     ** collation type was added. Correct this if it is the case.
82085     */
82086     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
82087       assert( pIdx->nColumn==1 );
82088       if( pIdx->aiColumn[0]==i ){
82089         pIdx->azColl[0] = p->aCol[i].zColl;
82090       }
82091     }
82092   }else{
82093     sqlcipher3DbFree(db, zColl);
82094   }
82095 }
82096
82097 /*
82098 ** This function returns the collation sequence for database native text
82099 ** encoding identified by the string zName, length nName.
82100 **
82101 ** If the requested collation sequence is not available, or not available
82102 ** in the database native encoding, the collation factory is invoked to
82103 ** request it. If the collation factory does not supply such a sequence,
82104 ** and the sequence is available in another text encoding, then that is
82105 ** returned instead.
82106 **
82107 ** If no versions of the requested collations sequence are available, or
82108 ** another error occurs, NULL is returned and an error message written into
82109 ** pParse.
82110 **
82111 ** This routine is a wrapper around sqlcipher3FindCollSeq().  This routine
82112 ** invokes the collation factory if the named collation cannot be found
82113 ** and generates an error message.
82114 **
82115 ** See also: sqlcipher3FindCollSeq(), sqlcipher3GetCollSeq()
82116 */
82117 SQLCIPHER_PRIVATE CollSeq *sqlcipher3LocateCollSeq(Parse *pParse, const char *zName){
82118   sqlcipher3 *db = pParse->db;
82119   u8 enc = ENC(db);
82120   u8 initbusy = db->init.busy;
82121   CollSeq *pColl;
82122
82123   pColl = sqlcipher3FindCollSeq(db, enc, zName, initbusy);
82124   if( !initbusy && (!pColl || !pColl->xCmp) ){
82125     pColl = sqlcipher3GetCollSeq(db, enc, pColl, zName);
82126     if( !pColl ){
82127       sqlcipher3ErrorMsg(pParse, "no such collation sequence: %s", zName);
82128     }
82129   }
82130
82131   return pColl;
82132 }
82133
82134
82135 /*
82136 ** Generate code that will increment the schema cookie.
82137 **
82138 ** The schema cookie is used to determine when the schema for the
82139 ** database changes.  After each schema change, the cookie value
82140 ** changes.  When a process first reads the schema it records the
82141 ** cookie.  Thereafter, whenever it goes to access the database,
82142 ** it checks the cookie to make sure the schema has not changed
82143 ** since it was last read.
82144 **
82145 ** This plan is not completely bullet-proof.  It is possible for
82146 ** the schema to change multiple times and for the cookie to be
82147 ** set back to prior value.  But schema changes are infrequent
82148 ** and the probability of hitting the same cookie value is only
82149 ** 1 chance in 2^32.  So we're safe enough.
82150 */
82151 SQLCIPHER_PRIVATE void sqlcipher3ChangeCookie(Parse *pParse, int iDb){
82152   int r1 = sqlcipher3GetTempReg(pParse);
82153   sqlcipher3 *db = pParse->db;
82154   Vdbe *v = pParse->pVdbe;
82155   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
82156   sqlcipher3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
82157   sqlcipher3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
82158   sqlcipher3ReleaseTempReg(pParse, r1);
82159 }
82160
82161 /*
82162 ** Measure the number of characters needed to output the given
82163 ** identifier.  The number returned includes any quotes used
82164 ** but does not include the null terminator.
82165 **
82166 ** The estimate is conservative.  It might be larger that what is
82167 ** really needed.
82168 */
82169 static int identLength(const char *z){
82170   int n;
82171   for(n=0; *z; n++, z++){
82172     if( *z=='"' ){ n++; }
82173   }
82174   return n + 2;
82175 }
82176
82177 /*
82178 ** The first parameter is a pointer to an output buffer. The second 
82179 ** parameter is a pointer to an integer that contains the offset at
82180 ** which to write into the output buffer. This function copies the
82181 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
82182 ** to the specified offset in the buffer and updates *pIdx to refer
82183 ** to the first byte after the last byte written before returning.
82184 ** 
82185 ** If the string zSignedIdent consists entirely of alpha-numeric
82186 ** characters, does not begin with a digit and is not an SQL keyword,
82187 ** then it is copied to the output buffer exactly as it is. Otherwise,
82188 ** it is quoted using double-quotes.
82189 */
82190 static void identPut(char *z, int *pIdx, char *zSignedIdent){
82191   unsigned char *zIdent = (unsigned char*)zSignedIdent;
82192   int i, j, needQuote;
82193   i = *pIdx;
82194
82195   for(j=0; zIdent[j]; j++){
82196     if( !sqlcipher3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
82197   }
82198   needQuote = sqlcipher3Isdigit(zIdent[0]) || sqlcipher3KeywordCode(zIdent, j)!=TK_ID;
82199   if( !needQuote ){
82200     needQuote = zIdent[j];
82201   }
82202
82203   if( needQuote ) z[i++] = '"';
82204   for(j=0; zIdent[j]; j++){
82205     z[i++] = zIdent[j];
82206     if( zIdent[j]=='"' ) z[i++] = '"';
82207   }
82208   if( needQuote ) z[i++] = '"';
82209   z[i] = 0;
82210   *pIdx = i;
82211 }
82212
82213 /*
82214 ** Generate a CREATE TABLE statement appropriate for the given
82215 ** table.  Memory to hold the text of the statement is obtained
82216 ** from sqlcipherMalloc() and must be freed by the calling function.
82217 */
82218 static char *createTableStmt(sqlcipher3 *db, Table *p){
82219   int i, k, n;
82220   char *zStmt;
82221   char *zSep, *zSep2, *zEnd;
82222   Column *pCol;
82223   n = 0;
82224   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
82225     n += identLength(pCol->zName) + 5;
82226   }
82227   n += identLength(p->zName);
82228   if( n<50 ){ 
82229     zSep = "";
82230     zSep2 = ",";
82231     zEnd = ")";
82232   }else{
82233     zSep = "\n  ";
82234     zSep2 = ",\n  ";
82235     zEnd = "\n)";
82236   }
82237   n += 35 + 6*p->nCol;
82238   zStmt = sqlcipher3DbMallocRaw(0, n);
82239   if( zStmt==0 ){
82240     db->mallocFailed = 1;
82241     return 0;
82242   }
82243   sqlcipher3_snprintf(n, zStmt, "CREATE TABLE ");
82244   k = sqlcipher3Strlen30(zStmt);
82245   identPut(zStmt, &k, p->zName);
82246   zStmt[k++] = '(';
82247   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
82248     static const char * const azType[] = {
82249         /* SQLCIPHER_AFF_TEXT    */ " TEXT",
82250         /* SQLCIPHER_AFF_NONE    */ "",
82251         /* SQLCIPHER_AFF_NUMERIC */ " NUM",
82252         /* SQLCIPHER_AFF_INTEGER */ " INT",
82253         /* SQLCIPHER_AFF_REAL    */ " REAL"
82254     };
82255     int len;
82256     const char *zType;
82257
82258     sqlcipher3_snprintf(n-k, &zStmt[k], zSep);
82259     k += sqlcipher3Strlen30(&zStmt[k]);
82260     zSep = zSep2;
82261     identPut(zStmt, &k, pCol->zName);
82262     assert( pCol->affinity-SQLCIPHER_AFF_TEXT >= 0 );
82263     assert( pCol->affinity-SQLCIPHER_AFF_TEXT < ArraySize(azType) );
82264     testcase( pCol->affinity==SQLCIPHER_AFF_TEXT );
82265     testcase( pCol->affinity==SQLCIPHER_AFF_NONE );
82266     testcase( pCol->affinity==SQLCIPHER_AFF_NUMERIC );
82267     testcase( pCol->affinity==SQLCIPHER_AFF_INTEGER );
82268     testcase( pCol->affinity==SQLCIPHER_AFF_REAL );
82269     
82270     zType = azType[pCol->affinity - SQLCIPHER_AFF_TEXT];
82271     len = sqlcipher3Strlen30(zType);
82272     assert( pCol->affinity==SQLCIPHER_AFF_NONE 
82273             || pCol->affinity==sqlcipher3AffinityType(zType) );
82274     memcpy(&zStmt[k], zType, len);
82275     k += len;
82276     assert( k<=n );
82277   }
82278   sqlcipher3_snprintf(n-k, &zStmt[k], "%s", zEnd);
82279   return zStmt;
82280 }
82281
82282 /*
82283 ** This routine is called to report the final ")" that terminates
82284 ** a CREATE TABLE statement.
82285 **
82286 ** The table structure that other action routines have been building
82287 ** is added to the internal hash tables, assuming no errors have
82288 ** occurred.
82289 **
82290 ** An entry for the table is made in the master table on disk, unless
82291 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
82292 ** it means we are reading the sqlcipher_master table because we just
82293 ** connected to the database or because the sqlcipher_master table has
82294 ** recently changed, so the entry for this table already exists in
82295 ** the sqlcipher_master table.  We do not want to create it again.
82296 **
82297 ** If the pSelect argument is not NULL, it means that this routine
82298 ** was called to create a table generated from a 
82299 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
82300 ** the new table will match the result set of the SELECT.
82301 */
82302 SQLCIPHER_PRIVATE void sqlcipher3EndTable(
82303   Parse *pParse,          /* Parse context */
82304   Token *pCons,           /* The ',' token after the last column defn. */
82305   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
82306   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
82307 ){
82308   Table *p;
82309   sqlcipher3 *db = pParse->db;
82310   int iDb;
82311
82312   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
82313     return;
82314   }
82315   p = pParse->pNewTable;
82316   if( p==0 ) return;
82317
82318   assert( !db->init.busy || !pSelect );
82319
82320   iDb = sqlcipher3SchemaToIndex(db, p->pSchema);
82321
82322 #ifndef SQLCIPHER_OMIT_CHECK
82323   /* Resolve names in all CHECK constraint expressions.
82324   */
82325   if( p->pCheck ){
82326     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
82327     NameContext sNC;                /* Name context for pParse->pNewTable */
82328
82329     memset(&sNC, 0, sizeof(sNC));
82330     memset(&sSrc, 0, sizeof(sSrc));
82331     sSrc.nSrc = 1;
82332     sSrc.a[0].zName = p->zName;
82333     sSrc.a[0].pTab = p;
82334     sSrc.a[0].iCursor = -1;
82335     sNC.pParse = pParse;
82336     sNC.pSrcList = &sSrc;
82337     sNC.isCheck = 1;
82338     if( sqlcipher3ResolveExprNames(&sNC, p->pCheck) ){
82339       return;
82340     }
82341   }
82342 #endif /* !defined(SQLCIPHER_OMIT_CHECK) */
82343
82344   /* If the db->init.busy is 1 it means we are reading the SQL off the
82345   ** "sqlcipher_master" or "sqlcipher_temp_master" table on the disk.
82346   ** So do not write to the disk again.  Extract the root page number
82347   ** for the table from the db->init.newTnum field.  (The page number
82348   ** should have been put there by the sqlcipherOpenCb routine.)
82349   */
82350   if( db->init.busy ){
82351     p->tnum = db->init.newTnum;
82352   }
82353
82354   /* If not initializing, then create a record for the new table
82355   ** in the SQLCIPHER_MASTER table of the database.
82356   **
82357   ** If this is a TEMPORARY table, write the entry into the auxiliary
82358   ** file instead of into the main database file.
82359   */
82360   if( !db->init.busy ){
82361     int n;
82362     Vdbe *v;
82363     char *zType;    /* "view" or "table" */
82364     char *zType2;   /* "VIEW" or "TABLE" */
82365     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
82366
82367     v = sqlcipher3GetVdbe(pParse);
82368     if( NEVER(v==0) ) return;
82369
82370     sqlcipher3VdbeAddOp1(v, OP_Close, 0);
82371
82372     /* 
82373     ** Initialize zType for the new view or table.
82374     */
82375     if( p->pSelect==0 ){
82376       /* A regular table */
82377       zType = "table";
82378       zType2 = "TABLE";
82379 #ifndef SQLCIPHER_OMIT_VIEW
82380     }else{
82381       /* A view */
82382       zType = "view";
82383       zType2 = "VIEW";
82384 #endif
82385     }
82386
82387     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
82388     ** statement to populate the new table. The root-page number for the
82389     ** new table is in register pParse->regRoot.
82390     **
82391     ** Once the SELECT has been coded by sqlcipher3Select(), it is in a
82392     ** suitable state to query for the column names and types to be used
82393     ** by the new table.
82394     **
82395     ** A shared-cache write-lock is not required to write to the new table,
82396     ** as a schema-lock must have already been obtained to create it. Since
82397     ** a schema-lock excludes all other database users, the write-lock would
82398     ** be redundant.
82399     */
82400     if( pSelect ){
82401       SelectDest dest;
82402       Table *pSelTab;
82403
82404       assert(pParse->nTab==1);
82405       sqlcipher3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
82406       sqlcipher3VdbeChangeP5(v, 1);
82407       pParse->nTab = 2;
82408       sqlcipher3SelectDestInit(&dest, SRT_Table, 1);
82409       sqlcipher3Select(pParse, pSelect, &dest);
82410       sqlcipher3VdbeAddOp1(v, OP_Close, 1);
82411       if( pParse->nErr==0 ){
82412         pSelTab = sqlcipher3ResultSetOfSelect(pParse, pSelect);
82413         if( pSelTab==0 ) return;
82414         assert( p->aCol==0 );
82415         p->nCol = pSelTab->nCol;
82416         p->aCol = pSelTab->aCol;
82417         pSelTab->nCol = 0;
82418         pSelTab->aCol = 0;
82419         sqlcipher3DeleteTable(db, pSelTab);
82420       }
82421     }
82422
82423     /* Compute the complete text of the CREATE statement */
82424     if( pSelect ){
82425       zStmt = createTableStmt(db, p);
82426     }else{
82427       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
82428       zStmt = sqlcipher3MPrintf(db, 
82429           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
82430       );
82431     }
82432
82433     /* A slot for the record has already been allocated in the 
82434     ** SQLCIPHER_MASTER table.  We just need to update that slot with all
82435     ** the information we've collected.
82436     */
82437     sqlcipher3NestedParse(pParse,
82438       "UPDATE %Q.%s "
82439          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
82440        "WHERE rowid=#%d",
82441       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
82442       zType,
82443       p->zName,
82444       p->zName,
82445       pParse->regRoot,
82446       zStmt,
82447       pParse->regRowid
82448     );
82449     sqlcipher3DbFree(db, zStmt);
82450     sqlcipher3ChangeCookie(pParse, iDb);
82451
82452 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
82453     /* Check to see if we need to create an sqlcipher_sequence table for
82454     ** keeping track of autoincrement keys.
82455     */
82456     if( p->tabFlags & TF_Autoincrement ){
82457       Db *pDb = &db->aDb[iDb];
82458       assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
82459       if( pDb->pSchema->pSeqTab==0 ){
82460         sqlcipher3NestedParse(pParse,
82461           "CREATE TABLE %Q.sqlcipher_sequence(name,seq)",
82462           pDb->zName
82463         );
82464       }
82465     }
82466 #endif
82467
82468     /* Reparse everything to update our internal data structures */
82469     sqlcipher3VdbeAddParseSchemaOp(v, iDb,
82470                sqlcipher3MPrintf(db, "tbl_name='%q'", p->zName));
82471   }
82472
82473
82474   /* Add the table to the in-memory representation of the database.
82475   */
82476   if( db->init.busy ){
82477     Table *pOld;
82478     Schema *pSchema = p->pSchema;
82479     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
82480     pOld = sqlcipher3HashInsert(&pSchema->tblHash, p->zName,
82481                              sqlcipher3Strlen30(p->zName),p);
82482     if( pOld ){
82483       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
82484       db->mallocFailed = 1;
82485       return;
82486     }
82487     pParse->pNewTable = 0;
82488     db->nTable++;
82489     db->flags |= SQLCIPHER_InternChanges;
82490
82491 #ifndef SQLCIPHER_OMIT_ALTERTABLE
82492     if( !p->pSelect ){
82493       const char *zName = (const char *)pParse->sNameToken.z;
82494       int nName;
82495       assert( !pSelect && pCons && pEnd );
82496       if( pCons->z==0 ){
82497         pCons = pEnd;
82498       }
82499       nName = (int)((const char *)pCons->z - zName);
82500       p->addColOffset = 13 + sqlcipher3Utf8CharLen(zName, nName);
82501     }
82502 #endif
82503   }
82504 }
82505
82506 #ifndef SQLCIPHER_OMIT_VIEW
82507 /*
82508 ** The parser calls this routine in order to create a new VIEW
82509 */
82510 SQLCIPHER_PRIVATE void sqlcipher3CreateView(
82511   Parse *pParse,     /* The parsing context */
82512   Token *pBegin,     /* The CREATE token that begins the statement */
82513   Token *pName1,     /* The token that holds the name of the view */
82514   Token *pName2,     /* The token that holds the name of the view */
82515   Select *pSelect,   /* A SELECT statement that will become the new view */
82516   int isTemp,        /* TRUE for a TEMPORARY view */
82517   int noErr          /* Suppress error messages if VIEW already exists */
82518 ){
82519   Table *p;
82520   int n;
82521   const char *z;
82522   Token sEnd;
82523   DbFixer sFix;
82524   Token *pName = 0;
82525   int iDb;
82526   sqlcipher3 *db = pParse->db;
82527
82528   if( pParse->nVar>0 ){
82529     sqlcipher3ErrorMsg(pParse, "parameters are not allowed in views");
82530     sqlcipher3SelectDelete(db, pSelect);
82531     return;
82532   }
82533   sqlcipher3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
82534   p = pParse->pNewTable;
82535   if( p==0 || pParse->nErr ){
82536     sqlcipher3SelectDelete(db, pSelect);
82537     return;
82538   }
82539   sqlcipher3TwoPartName(pParse, pName1, pName2, &pName);
82540   iDb = sqlcipher3SchemaToIndex(db, p->pSchema);
82541   if( sqlcipher3FixInit(&sFix, pParse, iDb, "view", pName)
82542     && sqlcipher3FixSelect(&sFix, pSelect)
82543   ){
82544     sqlcipher3SelectDelete(db, pSelect);
82545     return;
82546   }
82547
82548   /* Make a copy of the entire SELECT statement that defines the view.
82549   ** This will force all the Expr.token.z values to be dynamically
82550   ** allocated rather than point to the input string - which means that
82551   ** they will persist after the current sqlcipher3_exec() call returns.
82552   */
82553   p->pSelect = sqlcipher3SelectDup(db, pSelect, EXPRDUP_REDUCE);
82554   sqlcipher3SelectDelete(db, pSelect);
82555   if( db->mallocFailed ){
82556     return;
82557   }
82558   if( !db->init.busy ){
82559     sqlcipher3ViewGetColumnNames(pParse, p);
82560   }
82561
82562   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
82563   ** the end.
82564   */
82565   sEnd = pParse->sLastToken;
82566   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
82567     sEnd.z += sEnd.n;
82568   }
82569   sEnd.n = 0;
82570   n = (int)(sEnd.z - pBegin->z);
82571   z = pBegin->z;
82572   while( ALWAYS(n>0) && sqlcipher3Isspace(z[n-1]) ){ n--; }
82573   sEnd.z = &z[n-1];
82574   sEnd.n = 1;
82575
82576   /* Use sqlcipher3EndTable() to add the view to the SQLCIPHER_MASTER table */
82577   sqlcipher3EndTable(pParse, 0, &sEnd, 0);
82578   return;
82579 }
82580 #endif /* SQLCIPHER_OMIT_VIEW */
82581
82582 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_VIRTUALTABLE)
82583 /*
82584 ** The Table structure pTable is really a VIEW.  Fill in the names of
82585 ** the columns of the view in the pTable structure.  Return the number
82586 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
82587 */
82588 SQLCIPHER_PRIVATE int sqlcipher3ViewGetColumnNames(Parse *pParse, Table *pTable){
82589   Table *pSelTab;   /* A fake table from which we get the result set */
82590   Select *pSel;     /* Copy of the SELECT that implements the view */
82591   int nErr = 0;     /* Number of errors encountered */
82592   int n;            /* Temporarily holds the number of cursors assigned */
82593   sqlcipher3 *db = pParse->db;  /* Database connection for malloc errors */
82594   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
82595
82596   assert( pTable );
82597
82598 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
82599   if( sqlcipher3VtabCallConnect(pParse, pTable) ){
82600     return SQLCIPHER_ERROR;
82601   }
82602   if( IsVirtual(pTable) ) return 0;
82603 #endif
82604
82605 #ifndef SQLCIPHER_OMIT_VIEW
82606   /* A positive nCol means the columns names for this view are
82607   ** already known.
82608   */
82609   if( pTable->nCol>0 ) return 0;
82610
82611   /* A negative nCol is a special marker meaning that we are currently
82612   ** trying to compute the column names.  If we enter this routine with
82613   ** a negative nCol, it means two or more views form a loop, like this:
82614   **
82615   **     CREATE VIEW one AS SELECT * FROM two;
82616   **     CREATE VIEW two AS SELECT * FROM one;
82617   **
82618   ** Actually, the error above is now caught prior to reaching this point.
82619   ** But the following test is still important as it does come up
82620   ** in the following:
82621   ** 
82622   **     CREATE TABLE main.ex1(a);
82623   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
82624   **     SELECT * FROM temp.ex1;
82625   */
82626   if( pTable->nCol<0 ){
82627     sqlcipher3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
82628     return 1;
82629   }
82630   assert( pTable->nCol>=0 );
82631
82632   /* If we get this far, it means we need to compute the table names.
82633   ** Note that the call to sqlcipher3ResultSetOfSelect() will expand any
82634   ** "*" elements in the results set of the view and will assign cursors
82635   ** to the elements of the FROM clause.  But we do not want these changes
82636   ** to be permanent.  So the computation is done on a copy of the SELECT
82637   ** statement that defines the view.
82638   */
82639   assert( pTable->pSelect );
82640   pSel = sqlcipher3SelectDup(db, pTable->pSelect, 0);
82641   if( pSel ){
82642     u8 enableLookaside = db->lookaside.bEnabled;
82643     n = pParse->nTab;
82644     sqlcipher3SrcListAssignCursors(pParse, pSel->pSrc);
82645     pTable->nCol = -1;
82646     db->lookaside.bEnabled = 0;
82647 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
82648     xAuth = db->xAuth;
82649     db->xAuth = 0;
82650     pSelTab = sqlcipher3ResultSetOfSelect(pParse, pSel);
82651     db->xAuth = xAuth;
82652 #else
82653     pSelTab = sqlcipher3ResultSetOfSelect(pParse, pSel);
82654 #endif
82655     db->lookaside.bEnabled = enableLookaside;
82656     pParse->nTab = n;
82657     if( pSelTab ){
82658       assert( pTable->aCol==0 );
82659       pTable->nCol = pSelTab->nCol;
82660       pTable->aCol = pSelTab->aCol;
82661       pSelTab->nCol = 0;
82662       pSelTab->aCol = 0;
82663       sqlcipher3DeleteTable(db, pSelTab);
82664       assert( sqlcipher3SchemaMutexHeld(db, 0, pTable->pSchema) );
82665       pTable->pSchema->flags |= DB_UnresetViews;
82666     }else{
82667       pTable->nCol = 0;
82668       nErr++;
82669     }
82670     sqlcipher3SelectDelete(db, pSel);
82671   } else {
82672     nErr++;
82673   }
82674 #endif /* SQLCIPHER_OMIT_VIEW */
82675   return nErr;  
82676 }
82677 #endif /* !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_VIRTUALTABLE) */
82678
82679 #ifndef SQLCIPHER_OMIT_VIEW
82680 /*
82681 ** Clear the column names from every VIEW in database idx.
82682 */
82683 static void sqlcipherViewResetAll(sqlcipher3 *db, int idx){
82684   HashElem *i;
82685   assert( sqlcipher3SchemaMutexHeld(db, idx, 0) );
82686   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
82687   for(i=sqlcipherHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqlcipherHashNext(i)){
82688     Table *pTab = sqlcipherHashData(i);
82689     if( pTab->pSelect ){
82690       sqlcipherDeleteColumnNames(db, pTab);
82691       pTab->aCol = 0;
82692       pTab->nCol = 0;
82693     }
82694   }
82695   DbClearProperty(db, idx, DB_UnresetViews);
82696 }
82697 #else
82698 # define sqlcipherViewResetAll(A,B)
82699 #endif /* SQLCIPHER_OMIT_VIEW */
82700
82701 /*
82702 ** This function is called by the VDBE to adjust the internal schema
82703 ** used by SQLite when the btree layer moves a table root page. The
82704 ** root-page of a table or index in database iDb has changed from iFrom
82705 ** to iTo.
82706 **
82707 ** Ticket #1728:  The symbol table might still contain information
82708 ** on tables and/or indices that are the process of being deleted.
82709 ** If you are unlucky, one of those deleted indices or tables might
82710 ** have the same rootpage number as the real table or index that is
82711 ** being moved.  So we cannot stop searching after the first match 
82712 ** because the first match might be for one of the deleted indices
82713 ** or tables and not the table/index that is actually being moved.
82714 ** We must continue looping until all tables and indices with
82715 ** rootpage==iFrom have been converted to have a rootpage of iTo
82716 ** in order to be certain that we got the right one.
82717 */
82718 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
82719 SQLCIPHER_PRIVATE void sqlcipher3RootPageMoved(sqlcipher3 *db, int iDb, int iFrom, int iTo){
82720   HashElem *pElem;
82721   Hash *pHash;
82722   Db *pDb;
82723
82724   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
82725   pDb = &db->aDb[iDb];
82726   pHash = &pDb->pSchema->tblHash;
82727   for(pElem=sqlcipherHashFirst(pHash); pElem; pElem=sqlcipherHashNext(pElem)){
82728     Table *pTab = sqlcipherHashData(pElem);
82729     if( pTab->tnum==iFrom ){
82730       pTab->tnum = iTo;
82731     }
82732   }
82733   pHash = &pDb->pSchema->idxHash;
82734   for(pElem=sqlcipherHashFirst(pHash); pElem; pElem=sqlcipherHashNext(pElem)){
82735     Index *pIdx = sqlcipherHashData(pElem);
82736     if( pIdx->tnum==iFrom ){
82737       pIdx->tnum = iTo;
82738     }
82739   }
82740 }
82741 #endif
82742
82743 /*
82744 ** Write code to erase the table with root-page iTable from database iDb.
82745 ** Also write code to modify the sqlcipher_master table and internal schema
82746 ** if a root-page of another table is moved by the btree-layer whilst
82747 ** erasing iTable (this can happen with an auto-vacuum database).
82748 */ 
82749 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
82750   Vdbe *v = sqlcipher3GetVdbe(pParse);
82751   int r1 = sqlcipher3GetTempReg(pParse);
82752   sqlcipher3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
82753   sqlcipher3MayAbort(pParse);
82754 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
82755   /* OP_Destroy stores an in integer r1. If this integer
82756   ** is non-zero, then it is the root page number of a table moved to
82757   ** location iTable. The following code modifies the sqlcipher_master table to
82758   ** reflect this.
82759   **
82760   ** The "#NNN" in the SQL is a special constant that means whatever value
82761   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
82762   ** token for additional information.
82763   */
82764   sqlcipher3NestedParse(pParse, 
82765      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
82766      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
82767 #endif
82768   sqlcipher3ReleaseTempReg(pParse, r1);
82769 }
82770
82771 /*
82772 ** Write VDBE code to erase table pTab and all associated indices on disk.
82773 ** Code to update the sqlcipher_master tables and internal schema definitions
82774 ** in case a root-page belonging to another table is moved by the btree layer
82775 ** is also added (this can happen with an auto-vacuum database).
82776 */
82777 static void destroyTable(Parse *pParse, Table *pTab){
82778 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
82779   Index *pIdx;
82780   int iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
82781   destroyRootPage(pParse, pTab->tnum, iDb);
82782   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82783     destroyRootPage(pParse, pIdx->tnum, iDb);
82784   }
82785 #else
82786   /* If the database may be auto-vacuum capable (if SQLCIPHER_OMIT_AUTOVACUUM
82787   ** is not defined), then it is important to call OP_Destroy on the
82788   ** table and index root-pages in order, starting with the numerically 
82789   ** largest root-page number. This guarantees that none of the root-pages
82790   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
82791   ** following were coded:
82792   **
82793   ** OP_Destroy 4 0
82794   ** ...
82795   ** OP_Destroy 5 0
82796   **
82797   ** and root page 5 happened to be the largest root-page number in the
82798   ** database, then root page 5 would be moved to page 4 by the 
82799   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
82800   ** a free-list page.
82801   */
82802   int iTab = pTab->tnum;
82803   int iDestroyed = 0;
82804
82805   while( 1 ){
82806     Index *pIdx;
82807     int iLargest = 0;
82808
82809     if( iDestroyed==0 || iTab<iDestroyed ){
82810       iLargest = iTab;
82811     }
82812     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82813       int iIdx = pIdx->tnum;
82814       assert( pIdx->pSchema==pTab->pSchema );
82815       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
82816         iLargest = iIdx;
82817       }
82818     }
82819     if( iLargest==0 ){
82820       return;
82821     }else{
82822       int iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
82823       destroyRootPage(pParse, iLargest, iDb);
82824       iDestroyed = iLargest;
82825     }
82826   }
82827 #endif
82828 }
82829
82830 /*
82831 ** Remove entries from the sqlcipher_statN tables (for N in (1,2,3))
82832 ** after a DROP INDEX or DROP TABLE command.
82833 */
82834 static void sqlcipher3ClearStatTables(
82835   Parse *pParse,         /* The parsing context */
82836   int iDb,               /* The database number */
82837   const char *zType,     /* "idx" or "tbl" */
82838   const char *zName      /* Name of index or table */
82839 ){
82840   int i;
82841   const char *zDbName = pParse->db->aDb[iDb].zName;
82842   for(i=1; i<=3; i++){
82843     char zTab[24];
82844     sqlcipher3_snprintf(sizeof(zTab),zTab,"sqlcipher_stat%d",i);
82845     if( sqlcipher3FindTable(pParse->db, zTab, zDbName) ){
82846       sqlcipher3NestedParse(pParse,
82847         "DELETE FROM %Q.%s WHERE %s=%Q",
82848         zDbName, zTab, zType, zName
82849       );
82850     }
82851   }
82852 }
82853
82854 /*
82855 ** Generate code to drop a table.
82856 */
82857 SQLCIPHER_PRIVATE void sqlcipher3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
82858   Vdbe *v;
82859   sqlcipher3 *db = pParse->db;
82860   Trigger *pTrigger;
82861   Db *pDb = &db->aDb[iDb];
82862
82863   v = sqlcipher3GetVdbe(pParse);
82864   assert( v!=0 );
82865   sqlcipher3BeginWriteOperation(pParse, 1, iDb);
82866
82867 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
82868   if( IsVirtual(pTab) ){
82869     sqlcipher3VdbeAddOp0(v, OP_VBegin);
82870   }
82871 #endif
82872
82873   /* Drop all triggers associated with the table being dropped. Code
82874   ** is generated to remove entries from sqlcipher_master and/or
82875   ** sqlcipher_temp_master if required.
82876   */
82877   pTrigger = sqlcipher3TriggerList(pParse, pTab);
82878   while( pTrigger ){
82879     assert( pTrigger->pSchema==pTab->pSchema || 
82880         pTrigger->pSchema==db->aDb[1].pSchema );
82881     sqlcipher3DropTriggerPtr(pParse, pTrigger);
82882     pTrigger = pTrigger->pNext;
82883   }
82884
82885 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
82886   /* Remove any entries of the sqlcipher_sequence table associated with
82887   ** the table being dropped. This is done before the table is dropped
82888   ** at the btree level, in case the sqlcipher_sequence table needs to
82889   ** move as a result of the drop (can happen in auto-vacuum mode).
82890   */
82891   if( pTab->tabFlags & TF_Autoincrement ){
82892     sqlcipher3NestedParse(pParse,
82893       "DELETE FROM %Q.sqlcipher_sequence WHERE name=%Q",
82894       pDb->zName, pTab->zName
82895     );
82896   }
82897 #endif
82898
82899   /* Drop all SQLCIPHER_MASTER table and index entries that refer to the
82900   ** table. The program name loops through the master table and deletes
82901   ** every row that refers to a table of the same name as the one being
82902   ** dropped. Triggers are handled seperately because a trigger can be
82903   ** created in the temp database that refers to a table in another
82904   ** database.
82905   */
82906   sqlcipher3NestedParse(pParse, 
82907       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
82908       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
82909   if( !isView && !IsVirtual(pTab) ){
82910     destroyTable(pParse, pTab);
82911   }
82912
82913   /* Remove the table entry from SQLite's internal schema and modify
82914   ** the schema cookie.
82915   */
82916   if( IsVirtual(pTab) ){
82917     sqlcipher3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
82918   }
82919   sqlcipher3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
82920   sqlcipher3ChangeCookie(pParse, iDb);
82921   sqlcipherViewResetAll(db, iDb);
82922 }
82923
82924 /*
82925 ** This routine is called to do the work of a DROP TABLE statement.
82926 ** pName is the name of the table to be dropped.
82927 */
82928 SQLCIPHER_PRIVATE void sqlcipher3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
82929   Table *pTab;
82930   Vdbe *v;
82931   sqlcipher3 *db = pParse->db;
82932   int iDb;
82933
82934   if( db->mallocFailed ){
82935     goto exit_drop_table;
82936   }
82937   assert( pParse->nErr==0 );
82938   assert( pName->nSrc==1 );
82939   if( noErr ) db->suppressErr++;
82940   pTab = sqlcipher3LocateTable(pParse, isView, 
82941                             pName->a[0].zName, pName->a[0].zDatabase);
82942   if( noErr ) db->suppressErr--;
82943
82944   if( pTab==0 ){
82945     if( noErr ) sqlcipher3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
82946     goto exit_drop_table;
82947   }
82948   iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
82949   assert( iDb>=0 && iDb<db->nDb );
82950
82951   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
82952   ** it is initialized.
82953   */
82954   if( IsVirtual(pTab) && sqlcipher3ViewGetColumnNames(pParse, pTab) ){
82955     goto exit_drop_table;
82956   }
82957 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
82958   {
82959     int code;
82960     const char *zTab = SCHEMA_TABLE(iDb);
82961     const char *zDb = db->aDb[iDb].zName;
82962     const char *zArg2 = 0;
82963     if( sqlcipher3AuthCheck(pParse, SQLCIPHER_DELETE, zTab, 0, zDb)){
82964       goto exit_drop_table;
82965     }
82966     if( isView ){
82967       if( !OMIT_TEMPDB && iDb==1 ){
82968         code = SQLCIPHER_DROP_TEMP_VIEW;
82969       }else{
82970         code = SQLCIPHER_DROP_VIEW;
82971       }
82972 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
82973     }else if( IsVirtual(pTab) ){
82974       code = SQLCIPHER_DROP_VTABLE;
82975       zArg2 = sqlcipher3GetVTable(db, pTab)->pMod->zName;
82976 #endif
82977     }else{
82978       if( !OMIT_TEMPDB && iDb==1 ){
82979         code = SQLCIPHER_DROP_TEMP_TABLE;
82980       }else{
82981         code = SQLCIPHER_DROP_TABLE;
82982       }
82983     }
82984     if( sqlcipher3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
82985       goto exit_drop_table;
82986     }
82987     if( sqlcipher3AuthCheck(pParse, SQLCIPHER_DELETE, pTab->zName, 0, zDb) ){
82988       goto exit_drop_table;
82989     }
82990   }
82991 #endif
82992   if( sqlcipher3StrNICmp(pTab->zName, "sqlcipher_", 7)==0 
82993     && sqlcipher3StrNICmp(pTab->zName, "sqlcipher_stat", 11)!=0 ){
82994     sqlcipher3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
82995     goto exit_drop_table;
82996   }
82997
82998 #ifndef SQLCIPHER_OMIT_VIEW
82999   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
83000   ** on a table.
83001   */
83002   if( isView && pTab->pSelect==0 ){
83003     sqlcipher3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
83004     goto exit_drop_table;
83005   }
83006   if( !isView && pTab->pSelect ){
83007     sqlcipher3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
83008     goto exit_drop_table;
83009   }
83010 #endif
83011
83012   /* Generate code to remove the table from the master table
83013   ** on disk.
83014   */
83015   v = sqlcipher3GetVdbe(pParse);
83016   if( v ){
83017     sqlcipher3BeginWriteOperation(pParse, 1, iDb);
83018     sqlcipher3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
83019     sqlcipher3FkDropTable(pParse, pName, pTab);
83020     sqlcipher3CodeDropTable(pParse, pTab, iDb, isView);
83021   }
83022
83023 exit_drop_table:
83024   sqlcipher3SrcListDelete(db, pName);
83025 }
83026
83027 /*
83028 ** This routine is called to create a new foreign key on the table
83029 ** currently under construction.  pFromCol determines which columns
83030 ** in the current table point to the foreign key.  If pFromCol==0 then
83031 ** connect the key to the last column inserted.  pTo is the name of
83032 ** the table referred to.  pToCol is a list of tables in the other
83033 ** pTo table that the foreign key points to.  flags contains all
83034 ** information about the conflict resolution algorithms specified
83035 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
83036 **
83037 ** An FKey structure is created and added to the table currently
83038 ** under construction in the pParse->pNewTable field.
83039 **
83040 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
83041 ** to sqlcipher3DeferForeignKey() might change this to DEFERRED.
83042 */
83043 SQLCIPHER_PRIVATE void sqlcipher3CreateForeignKey(
83044   Parse *pParse,       /* Parsing context */
83045   ExprList *pFromCol,  /* Columns in this table that point to other table */
83046   Token *pTo,          /* Name of the other table */
83047   ExprList *pToCol,    /* Columns in the other table */
83048   int flags            /* Conflict resolution algorithms. */
83049 ){
83050   sqlcipher3 *db = pParse->db;
83051 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
83052   FKey *pFKey = 0;
83053   FKey *pNextTo;
83054   Table *p = pParse->pNewTable;
83055   int nByte;
83056   int i;
83057   int nCol;
83058   char *z;
83059
83060   assert( pTo!=0 );
83061   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
83062   if( pFromCol==0 ){
83063     int iCol = p->nCol-1;
83064     if( NEVER(iCol<0) ) goto fk_end;
83065     if( pToCol && pToCol->nExpr!=1 ){
83066       sqlcipher3ErrorMsg(pParse, "foreign key on %s"
83067          " should reference only one column of table %T",
83068          p->aCol[iCol].zName, pTo);
83069       goto fk_end;
83070     }
83071     nCol = 1;
83072   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
83073     sqlcipher3ErrorMsg(pParse,
83074         "number of columns in foreign key does not match the number of "
83075         "columns in the referenced table");
83076     goto fk_end;
83077   }else{
83078     nCol = pFromCol->nExpr;
83079   }
83080   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
83081   if( pToCol ){
83082     for(i=0; i<pToCol->nExpr; i++){
83083       nByte += sqlcipher3Strlen30(pToCol->a[i].zName) + 1;
83084     }
83085   }
83086   pFKey = sqlcipher3DbMallocZero(db, nByte );
83087   if( pFKey==0 ){
83088     goto fk_end;
83089   }
83090   pFKey->pFrom = p;
83091   pFKey->pNextFrom = p->pFKey;
83092   z = (char*)&pFKey->aCol[nCol];
83093   pFKey->zTo = z;
83094   memcpy(z, pTo->z, pTo->n);
83095   z[pTo->n] = 0;
83096   sqlcipher3Dequote(z);
83097   z += pTo->n+1;
83098   pFKey->nCol = nCol;
83099   if( pFromCol==0 ){
83100     pFKey->aCol[0].iFrom = p->nCol-1;
83101   }else{
83102     for(i=0; i<nCol; i++){
83103       int j;
83104       for(j=0; j<p->nCol; j++){
83105         if( sqlcipher3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
83106           pFKey->aCol[i].iFrom = j;
83107           break;
83108         }
83109       }
83110       if( j>=p->nCol ){
83111         sqlcipher3ErrorMsg(pParse, 
83112           "unknown column \"%s\" in foreign key definition", 
83113           pFromCol->a[i].zName);
83114         goto fk_end;
83115       }
83116     }
83117   }
83118   if( pToCol ){
83119     for(i=0; i<nCol; i++){
83120       int n = sqlcipher3Strlen30(pToCol->a[i].zName);
83121       pFKey->aCol[i].zCol = z;
83122       memcpy(z, pToCol->a[i].zName, n);
83123       z[n] = 0;
83124       z += n+1;
83125     }
83126   }
83127   pFKey->isDeferred = 0;
83128   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
83129   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
83130
83131   assert( sqlcipher3SchemaMutexHeld(db, 0, p->pSchema) );
83132   pNextTo = (FKey *)sqlcipher3HashInsert(&p->pSchema->fkeyHash, 
83133       pFKey->zTo, sqlcipher3Strlen30(pFKey->zTo), (void *)pFKey
83134   );
83135   if( pNextTo==pFKey ){
83136     db->mallocFailed = 1;
83137     goto fk_end;
83138   }
83139   if( pNextTo ){
83140     assert( pNextTo->pPrevTo==0 );
83141     pFKey->pNextTo = pNextTo;
83142     pNextTo->pPrevTo = pFKey;
83143   }
83144
83145   /* Link the foreign key to the table as the last step.
83146   */
83147   p->pFKey = pFKey;
83148   pFKey = 0;
83149
83150 fk_end:
83151   sqlcipher3DbFree(db, pFKey);
83152 #endif /* !defined(SQLCIPHER_OMIT_FOREIGN_KEY) */
83153   sqlcipher3ExprListDelete(db, pFromCol);
83154   sqlcipher3ExprListDelete(db, pToCol);
83155 }
83156
83157 /*
83158 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
83159 ** clause is seen as part of a foreign key definition.  The isDeferred
83160 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
83161 ** The behavior of the most recently created foreign key is adjusted
83162 ** accordingly.
83163 */
83164 SQLCIPHER_PRIVATE void sqlcipher3DeferForeignKey(Parse *pParse, int isDeferred){
83165 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
83166   Table *pTab;
83167   FKey *pFKey;
83168   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
83169   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
83170   pFKey->isDeferred = (u8)isDeferred;
83171 #endif
83172 }
83173
83174 /*
83175 ** Generate code that will erase and refill index *pIdx.  This is
83176 ** used to initialize a newly created index or to recompute the
83177 ** content of an index in response to a REINDEX command.
83178 **
83179 ** if memRootPage is not negative, it means that the index is newly
83180 ** created.  The register specified by memRootPage contains the
83181 ** root page number of the index.  If memRootPage is negative, then
83182 ** the index already exists and must be cleared before being refilled and
83183 ** the root page number of the index is taken from pIndex->tnum.
83184 */
83185 static void sqlcipher3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
83186   Table *pTab = pIndex->pTable;  /* The table that is indexed */
83187   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
83188   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
83189   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
83190   int addr1;                     /* Address of top of loop */
83191   int addr2;                     /* Address to jump to for next iteration */
83192   int tnum;                      /* Root page of index */
83193   Vdbe *v;                       /* Generate code into this virtual machine */
83194   KeyInfo *pKey;                 /* KeyInfo for index */
83195 #ifdef SQLCIPHER_OMIT_MERGE_SORT
83196   int regIdxKey;                 /* Registers containing the index key */
83197 #endif
83198   int regRecord;                 /* Register holding assemblied index record */
83199   sqlcipher3 *db = pParse->db;      /* The database connection */
83200   int iDb = sqlcipher3SchemaToIndex(db, pIndex->pSchema);
83201
83202 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
83203   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_REINDEX, pIndex->zName, 0,
83204       db->aDb[iDb].zName ) ){
83205     return;
83206   }
83207 #endif
83208
83209   /* Require a write-lock on the table to perform this operation */
83210   sqlcipher3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
83211
83212   v = sqlcipher3GetVdbe(pParse);
83213   if( v==0 ) return;
83214   if( memRootPage>=0 ){
83215     tnum = memRootPage;
83216   }else{
83217     tnum = pIndex->tnum;
83218     sqlcipher3VdbeAddOp2(v, OP_Clear, tnum, iDb);
83219   }
83220   pKey = sqlcipher3IndexKeyinfo(pParse, pIndex);
83221   sqlcipher3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
83222                     (char *)pKey, P4_KEYINFO_HANDOFF);
83223   if( memRootPage>=0 ){
83224     sqlcipher3VdbeChangeP5(v, 1);
83225   }
83226
83227 #ifndef SQLCIPHER_OMIT_MERGE_SORT
83228   /* Open the sorter cursor if we are to use one. */
83229   iSorter = pParse->nTab++;
83230   sqlcipher3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
83231 #else
83232   iSorter = iTab;
83233 #endif
83234
83235   /* Open the table. Loop through all rows of the table, inserting index
83236   ** records into the sorter. */
83237   sqlcipher3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
83238   addr1 = sqlcipher3VdbeAddOp2(v, OP_Rewind, iTab, 0);
83239   regRecord = sqlcipher3GetTempReg(pParse);
83240
83241 #ifndef SQLCIPHER_OMIT_MERGE_SORT
83242   sqlcipher3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
83243   sqlcipher3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
83244   sqlcipher3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
83245   sqlcipher3VdbeJumpHere(v, addr1);
83246   addr1 = sqlcipher3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
83247   if( pIndex->onError!=OE_None ){
83248     int j2 = sqlcipher3VdbeCurrentAddr(v) + 3;
83249     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, j2);
83250     addr2 = sqlcipher3VdbeCurrentAddr(v);
83251     sqlcipher3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
83252     sqlcipher3HaltConstraint(
83253         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
83254     );
83255   }else{
83256     addr2 = sqlcipher3VdbeCurrentAddr(v);
83257   }
83258   sqlcipher3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
83259   sqlcipher3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
83260   sqlcipher3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83261 #else
83262   regIdxKey = sqlcipher3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
83263   addr2 = addr1 + 1;
83264   if( pIndex->onError!=OE_None ){
83265     const int regRowid = regIdxKey + pIndex->nColumn;
83266     const int j2 = sqlcipher3VdbeCurrentAddr(v) + 2;
83267     void * const pRegKey = SQLCIPHER_INT_TO_PTR(regIdxKey);
83268
83269     /* The registers accessed by the OP_IsUnique opcode were allocated
83270     ** using sqlcipher3GetTempRange() inside of the sqlcipher3GenerateIndexKey()
83271     ** call above. Just before that function was freed they were released
83272     ** (made available to the compiler for reuse) using 
83273     ** sqlcipher3ReleaseTempRange(). So in some ways having the OP_IsUnique
83274     ** opcode use the values stored within seems dangerous. However, since
83275     ** we can be sure that no other temp registers have been allocated
83276     ** since sqlcipher3ReleaseTempRange() was called, it is safe to do so.
83277     */
83278     sqlcipher3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
83279     sqlcipher3HaltConstraint(
83280         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
83281   }
83282   sqlcipher3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
83283   sqlcipher3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83284 #endif
83285   sqlcipher3ReleaseTempReg(pParse, regRecord);
83286   sqlcipher3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
83287   sqlcipher3VdbeJumpHere(v, addr1);
83288
83289   sqlcipher3VdbeAddOp1(v, OP_Close, iTab);
83290   sqlcipher3VdbeAddOp1(v, OP_Close, iIdx);
83291   sqlcipher3VdbeAddOp1(v, OP_Close, iSorter);
83292 }
83293
83294 /*
83295 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
83296 ** and pTblList is the name of the table that is to be indexed.  Both will 
83297 ** be NULL for a primary key or an index that is created to satisfy a
83298 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
83299 ** as the table to be indexed.  pParse->pNewTable is a table that is
83300 ** currently being constructed by a CREATE TABLE statement.
83301 **
83302 ** pList is a list of columns to be indexed.  pList will be NULL if this
83303 ** is a primary key or unique-constraint on the most recent column added
83304 ** to the table currently under construction.  
83305 **
83306 ** If the index is created successfully, return a pointer to the new Index
83307 ** structure. This is used by sqlcipher3AddPrimaryKey() to mark the index
83308 ** as the tables primary key (Index.autoIndex==2).
83309 */
83310 SQLCIPHER_PRIVATE Index *sqlcipher3CreateIndex(
83311   Parse *pParse,     /* All information about this parse */
83312   Token *pName1,     /* First part of index name. May be NULL */
83313   Token *pName2,     /* Second part of index name. May be NULL */
83314   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
83315   ExprList *pList,   /* A list of columns to be indexed */
83316   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
83317   Token *pStart,     /* The CREATE token that begins this statement */
83318   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
83319   int sortOrder,     /* Sort order of primary key when pList==NULL */
83320   int ifNotExist     /* Omit error if index already exists */
83321 ){
83322   Index *pRet = 0;     /* Pointer to return */
83323   Table *pTab = 0;     /* Table to be indexed */
83324   Index *pIndex = 0;   /* The index to be created */
83325   char *zName = 0;     /* Name of the index */
83326   int nName;           /* Number of characters in zName */
83327   int i, j;
83328   Token nullId;        /* Fake token for an empty ID list */
83329   DbFixer sFix;        /* For assigning database names to pTable */
83330   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
83331   sqlcipher3 *db = pParse->db;
83332   Db *pDb;             /* The specific table containing the indexed database */
83333   int iDb;             /* Index of the database that is being written */
83334   Token *pName = 0;    /* Unqualified name of the index to create */
83335   struct ExprList_item *pListItem; /* For looping over pList */
83336   int nCol;
83337   int nExtra = 0;
83338   char *zExtra;
83339
83340   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
83341   assert( pParse->nErr==0 );      /* Never called with prior errors */
83342   if( db->mallocFailed || IN_DECLARE_VTAB ){
83343     goto exit_create_index;
83344   }
83345   if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
83346     goto exit_create_index;
83347   }
83348
83349   /*
83350   ** Find the table that is to be indexed.  Return early if not found.
83351   */
83352   if( pTblName!=0 ){
83353
83354     /* Use the two-part index name to determine the database 
83355     ** to search for the table. 'Fix' the table name to this db
83356     ** before looking up the table.
83357     */
83358     assert( pName1 && pName2 );
83359     iDb = sqlcipher3TwoPartName(pParse, pName1, pName2, &pName);
83360     if( iDb<0 ) goto exit_create_index;
83361     assert( pName && pName->z );
83362
83363 #ifndef SQLCIPHER_OMIT_TEMPDB
83364     /* If the index name was unqualified, check if the the table
83365     ** is a temp table. If so, set the database to 1. Do not do this
83366     ** if initialising a database schema.
83367     */
83368     if( !db->init.busy ){
83369       pTab = sqlcipher3SrcListLookup(pParse, pTblName);
83370       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
83371         iDb = 1;
83372       }
83373     }
83374 #endif
83375
83376     if( sqlcipher3FixInit(&sFix, pParse, iDb, "index", pName) &&
83377         sqlcipher3FixSrcList(&sFix, pTblName)
83378     ){
83379       /* Because the parser constructs pTblName from a single identifier,
83380       ** sqlcipher3FixSrcList can never fail. */
83381       assert(0);
83382     }
83383     pTab = sqlcipher3LocateTable(pParse, 0, pTblName->a[0].zName, 
83384         pTblName->a[0].zDatabase);
83385     if( !pTab || db->mallocFailed ) goto exit_create_index;
83386     assert( db->aDb[iDb].pSchema==pTab->pSchema );
83387   }else{
83388     assert( pName==0 );
83389     assert( pStart==0 );
83390     pTab = pParse->pNewTable;
83391     if( !pTab ) goto exit_create_index;
83392     iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
83393   }
83394   pDb = &db->aDb[iDb];
83395
83396   assert( pTab!=0 );
83397   assert( pParse->nErr==0 );
83398   if( sqlcipher3StrNICmp(pTab->zName, "sqlcipher_", 7)==0 
83399        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
83400     sqlcipher3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
83401     goto exit_create_index;
83402   }
83403 #ifndef SQLCIPHER_OMIT_VIEW
83404   if( pTab->pSelect ){
83405     sqlcipher3ErrorMsg(pParse, "views may not be indexed");
83406     goto exit_create_index;
83407   }
83408 #endif
83409 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
83410   if( IsVirtual(pTab) ){
83411     sqlcipher3ErrorMsg(pParse, "virtual tables may not be indexed");
83412     goto exit_create_index;
83413   }
83414 #endif
83415
83416   /*
83417   ** Find the name of the index.  Make sure there is not already another
83418   ** index or table with the same name.  
83419   **
83420   ** Exception:  If we are reading the names of permanent indices from the
83421   ** sqlcipher_master table (because some other process changed the schema) and
83422   ** one of the index names collides with the name of a temporary table or
83423   ** index, then we will continue to process this index.
83424   **
83425   ** If pName==0 it means that we are
83426   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
83427   ** own name.
83428   */
83429   if( pName ){
83430     zName = sqlcipher3NameFromToken(db, pName);
83431     if( zName==0 ) goto exit_create_index;
83432     assert( pName->z!=0 );
83433     if( SQLCIPHER_OK!=sqlcipher3CheckObjectName(pParse, zName) ){
83434       goto exit_create_index;
83435     }
83436     if( !db->init.busy ){
83437       if( sqlcipher3FindTable(db, zName, 0)!=0 ){
83438         sqlcipher3ErrorMsg(pParse, "there is already a table named %s", zName);
83439         goto exit_create_index;
83440       }
83441     }
83442     if( sqlcipher3FindIndex(db, zName, pDb->zName)!=0 ){
83443       if( !ifNotExist ){
83444         sqlcipher3ErrorMsg(pParse, "index %s already exists", zName);
83445       }else{
83446         assert( !db->init.busy );
83447         sqlcipher3CodeVerifySchema(pParse, iDb);
83448       }
83449       goto exit_create_index;
83450     }
83451   }else{
83452     int n;
83453     Index *pLoop;
83454     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
83455     zName = sqlcipher3MPrintf(db, "sqlcipher_autoindex_%s_%d", pTab->zName, n);
83456     if( zName==0 ){
83457       goto exit_create_index;
83458     }
83459   }
83460
83461   /* Check for authorization to create an index.
83462   */
83463 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
83464   {
83465     const char *zDb = pDb->zName;
83466     if( sqlcipher3AuthCheck(pParse, SQLCIPHER_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
83467       goto exit_create_index;
83468     }
83469     i = SQLCIPHER_CREATE_INDEX;
83470     if( !OMIT_TEMPDB && iDb==1 ) i = SQLCIPHER_CREATE_TEMP_INDEX;
83471     if( sqlcipher3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
83472       goto exit_create_index;
83473     }
83474   }
83475 #endif
83476
83477   /* If pList==0, it means this routine was called to make a primary
83478   ** key out of the last column added to the table under construction.
83479   ** So create a fake list to simulate this.
83480   */
83481   if( pList==0 ){
83482     nullId.z = pTab->aCol[pTab->nCol-1].zName;
83483     nullId.n = sqlcipher3Strlen30((char*)nullId.z);
83484     pList = sqlcipher3ExprListAppend(pParse, 0, 0);
83485     if( pList==0 ) goto exit_create_index;
83486     sqlcipher3ExprListSetName(pParse, pList, &nullId, 0);
83487     pList->a[0].sortOrder = (u8)sortOrder;
83488   }
83489
83490   /* Figure out how many bytes of space are required to store explicitly
83491   ** specified collation sequence names.
83492   */
83493   for(i=0; i<pList->nExpr; i++){
83494     Expr *pExpr = pList->a[i].pExpr;
83495     if( pExpr ){
83496       CollSeq *pColl = pExpr->pColl;
83497       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
83498       ** failure we have quit before reaching this point. */
83499       if( ALWAYS(pColl) ){
83500         nExtra += (1 + sqlcipher3Strlen30(pColl->zName));
83501       }
83502     }
83503   }
83504
83505   /* 
83506   ** Allocate the index structure. 
83507   */
83508   nName = sqlcipher3Strlen30(zName);
83509   nCol = pList->nExpr;
83510   pIndex = sqlcipher3DbMallocZero(db, 
83511       sizeof(Index) +              /* Index structure  */
83512       sizeof(tRowcnt)*(nCol+1) +   /* Index.aiRowEst   */
83513       sizeof(int)*nCol +           /* Index.aiColumn   */
83514       sizeof(char *)*nCol +        /* Index.azColl     */
83515       sizeof(u8)*nCol +            /* Index.aSortOrder */
83516       nName + 1 +                  /* Index.zName      */
83517       nExtra                       /* Collation sequence names */
83518   );
83519   if( db->mallocFailed ){
83520     goto exit_create_index;
83521   }
83522   pIndex->aiRowEst = (tRowcnt*)(&pIndex[1]);
83523   pIndex->azColl = (char**)(&pIndex->aiRowEst[nCol+1]);
83524   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
83525   pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
83526   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
83527   zExtra = (char *)(&pIndex->zName[nName+1]);
83528   memcpy(pIndex->zName, zName, nName+1);
83529   pIndex->pTable = pTab;
83530   pIndex->nColumn = pList->nExpr;
83531   pIndex->onError = (u8)onError;
83532   pIndex->autoIndex = (u8)(pName==0);
83533   pIndex->pSchema = db->aDb[iDb].pSchema;
83534   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
83535
83536   /* Check to see if we should honor DESC requests on index columns
83537   */
83538   if( pDb->pSchema->file_format>=4 ){
83539     sortOrderMask = -1;   /* Honor DESC */
83540   }else{
83541     sortOrderMask = 0;    /* Ignore DESC */
83542   }
83543
83544   /* Scan the names of the columns of the table to be indexed and
83545   ** load the column indices into the Index structure.  Report an error
83546   ** if any column is not found.
83547   **
83548   ** TODO:  Add a test to make sure that the same column is not named
83549   ** more than once within the same index.  Only the first instance of
83550   ** the column will ever be used by the optimizer.  Note that using the
83551   ** same column more than once cannot be an error because that would 
83552   ** break backwards compatibility - it needs to be a warning.
83553   */
83554   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
83555     const char *zColName = pListItem->zName;
83556     Column *pTabCol;
83557     int requestedSortOrder;
83558     char *zColl;                   /* Collation sequence name */
83559
83560     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
83561       if( sqlcipher3StrICmp(zColName, pTabCol->zName)==0 ) break;
83562     }
83563     if( j>=pTab->nCol ){
83564       sqlcipher3ErrorMsg(pParse, "table %s has no column named %s",
83565         pTab->zName, zColName);
83566       pParse->checkSchema = 1;
83567       goto exit_create_index;
83568     }
83569     pIndex->aiColumn[i] = j;
83570     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
83571     ** the way the "idxlist" non-terminal is constructed by the parser,
83572     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
83573     ** must exist or else there must have been an OOM error.  But if there
83574     ** was an OOM error, we would never reach this point. */
83575     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
83576       int nColl;
83577       zColl = pListItem->pExpr->pColl->zName;
83578       nColl = sqlcipher3Strlen30(zColl) + 1;
83579       assert( nExtra>=nColl );
83580       memcpy(zExtra, zColl, nColl);
83581       zColl = zExtra;
83582       zExtra += nColl;
83583       nExtra -= nColl;
83584     }else{
83585       zColl = pTab->aCol[j].zColl;
83586       if( !zColl ){
83587         zColl = db->pDfltColl->zName;
83588       }
83589     }
83590     if( !db->init.busy && !sqlcipher3LocateCollSeq(pParse, zColl) ){
83591       goto exit_create_index;
83592     }
83593     pIndex->azColl[i] = zColl;
83594     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
83595     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
83596   }
83597   sqlcipher3DefaultRowEst(pIndex);
83598
83599   if( pTab==pParse->pNewTable ){
83600     /* This routine has been called to create an automatic index as a
83601     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
83602     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
83603     ** i.e. one of:
83604     **
83605     ** CREATE TABLE t(x PRIMARY KEY, y);
83606     ** CREATE TABLE t(x, y, UNIQUE(x, y));
83607     **
83608     ** Either way, check to see if the table already has such an index. If
83609     ** so, don't bother creating this one. This only applies to
83610     ** automatically created indices. Users can do as they wish with
83611     ** explicit indices.
83612     **
83613     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
83614     ** (and thus suppressing the second one) even if they have different
83615     ** sort orders.
83616     **
83617     ** If there are different collating sequences or if the columns of
83618     ** the constraint occur in different orders, then the constraints are
83619     ** considered distinct and both result in separate indices.
83620     */
83621     Index *pIdx;
83622     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83623       int k;
83624       assert( pIdx->onError!=OE_None );
83625       assert( pIdx->autoIndex );
83626       assert( pIndex->onError!=OE_None );
83627
83628       if( pIdx->nColumn!=pIndex->nColumn ) continue;
83629       for(k=0; k<pIdx->nColumn; k++){
83630         const char *z1;
83631         const char *z2;
83632         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
83633         z1 = pIdx->azColl[k];
83634         z2 = pIndex->azColl[k];
83635         if( z1!=z2 && sqlcipher3StrICmp(z1, z2) ) break;
83636       }
83637       if( k==pIdx->nColumn ){
83638         if( pIdx->onError!=pIndex->onError ){
83639           /* This constraint creates the same index as a previous
83640           ** constraint specified somewhere in the CREATE TABLE statement.
83641           ** However the ON CONFLICT clauses are different. If both this 
83642           ** constraint and the previous equivalent constraint have explicit
83643           ** ON CONFLICT clauses this is an error. Otherwise, use the
83644           ** explicitly specified behaviour for the index.
83645           */
83646           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
83647             sqlcipher3ErrorMsg(pParse, 
83648                 "conflicting ON CONFLICT clauses specified", 0);
83649           }
83650           if( pIdx->onError==OE_Default ){
83651             pIdx->onError = pIndex->onError;
83652           }
83653         }
83654         goto exit_create_index;
83655       }
83656     }
83657   }
83658
83659   /* Link the new Index structure to its table and to the other
83660   ** in-memory database structures. 
83661   */
83662   if( db->init.busy ){
83663     Index *p;
83664     assert( sqlcipher3SchemaMutexHeld(db, 0, pIndex->pSchema) );
83665     p = sqlcipher3HashInsert(&pIndex->pSchema->idxHash, 
83666                           pIndex->zName, sqlcipher3Strlen30(pIndex->zName),
83667                           pIndex);
83668     if( p ){
83669       assert( p==pIndex );  /* Malloc must have failed */
83670       db->mallocFailed = 1;
83671       goto exit_create_index;
83672     }
83673     db->flags |= SQLCIPHER_InternChanges;
83674     if( pTblName!=0 ){
83675       pIndex->tnum = db->init.newTnum;
83676     }
83677   }
83678
83679   /* If the db->init.busy is 0 then create the index on disk.  This
83680   ** involves writing the index into the master table and filling in the
83681   ** index with the current table contents.
83682   **
83683   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
83684   ** command.  db->init.busy is 1 when a database is opened and 
83685   ** CREATE INDEX statements are read out of the master table.  In
83686   ** the latter case the index already exists on disk, which is why
83687   ** we don't want to recreate it.
83688   **
83689   ** If pTblName==0 it means this index is generated as a primary key
83690   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
83691   ** has just been created, it contains no data and the index initialization
83692   ** step can be skipped.
83693   */
83694   else{ /* if( db->init.busy==0 ) */
83695     Vdbe *v;
83696     char *zStmt;
83697     int iMem = ++pParse->nMem;
83698
83699     v = sqlcipher3GetVdbe(pParse);
83700     if( v==0 ) goto exit_create_index;
83701
83702
83703     /* Create the rootpage for the index
83704     */
83705     sqlcipher3BeginWriteOperation(pParse, 1, iDb);
83706     sqlcipher3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
83707
83708     /* Gather the complete text of the CREATE INDEX statement into
83709     ** the zStmt variable
83710     */
83711     if( pStart ){
83712       assert( pEnd!=0 );
83713       /* A named index with an explicit CREATE INDEX statement */
83714       zStmt = sqlcipher3MPrintf(db, "CREATE%s INDEX %.*s",
83715         onError==OE_None ? "" : " UNIQUE",
83716         (int)(pEnd->z - pName->z) + 1,
83717         pName->z);
83718     }else{
83719       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
83720       /* zStmt = sqlcipher3MPrintf(""); */
83721       zStmt = 0;
83722     }
83723
83724     /* Add an entry in sqlcipher_master for this index
83725     */
83726     sqlcipher3NestedParse(pParse, 
83727         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
83728         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
83729         pIndex->zName,
83730         pTab->zName,
83731         iMem,
83732         zStmt
83733     );
83734     sqlcipher3DbFree(db, zStmt);
83735
83736     /* Fill the index with data and reparse the schema. Code an OP_Expire
83737     ** to invalidate all pre-compiled statements.
83738     */
83739     if( pTblName ){
83740       sqlcipher3RefillIndex(pParse, pIndex, iMem);
83741       sqlcipher3ChangeCookie(pParse, iDb);
83742       sqlcipher3VdbeAddParseSchemaOp(v, iDb,
83743          sqlcipher3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
83744       sqlcipher3VdbeAddOp1(v, OP_Expire, 0);
83745     }
83746   }
83747
83748   /* When adding an index to the list of indices for a table, make
83749   ** sure all indices labeled OE_Replace come after all those labeled
83750   ** OE_Ignore.  This is necessary for the correct constraint check
83751   ** processing (in sqlcipher3GenerateConstraintChecks()) as part of
83752   ** UPDATE and INSERT statements.  
83753   */
83754   if( db->init.busy || pTblName==0 ){
83755     if( onError!=OE_Replace || pTab->pIndex==0
83756          || pTab->pIndex->onError==OE_Replace){
83757       pIndex->pNext = pTab->pIndex;
83758       pTab->pIndex = pIndex;
83759     }else{
83760       Index *pOther = pTab->pIndex;
83761       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
83762         pOther = pOther->pNext;
83763       }
83764       pIndex->pNext = pOther->pNext;
83765       pOther->pNext = pIndex;
83766     }
83767     pRet = pIndex;
83768     pIndex = 0;
83769   }
83770
83771   /* Clean up before exiting */
83772 exit_create_index:
83773   if( pIndex ){
83774     sqlcipher3DbFree(db, pIndex->zColAff);
83775     sqlcipher3DbFree(db, pIndex);
83776   }
83777   sqlcipher3ExprListDelete(db, pList);
83778   sqlcipher3SrcListDelete(db, pTblName);
83779   sqlcipher3DbFree(db, zName);
83780   return pRet;
83781 }
83782
83783 /*
83784 ** Fill the Index.aiRowEst[] array with default information - information
83785 ** to be used when we have not run the ANALYZE command.
83786 **
83787 ** aiRowEst[0] is suppose to contain the number of elements in the index.
83788 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
83789 ** number of rows in the table that match any particular value of the
83790 ** first column of the index.  aiRowEst[2] is an estimate of the number
83791 ** of rows that match any particular combiniation of the first 2 columns
83792 ** of the index.  And so forth.  It must always be the case that
83793 *
83794 **           aiRowEst[N]<=aiRowEst[N-1]
83795 **           aiRowEst[N]>=1
83796 **
83797 ** Apart from that, we have little to go on besides intuition as to
83798 ** how aiRowEst[] should be initialized.  The numbers generated here
83799 ** are based on typical values found in actual indices.
83800 */
83801 SQLCIPHER_PRIVATE void sqlcipher3DefaultRowEst(Index *pIdx){
83802   tRowcnt *a = pIdx->aiRowEst;
83803   int i;
83804   tRowcnt n;
83805   assert( a!=0 );
83806   a[0] = pIdx->pTable->nRowEst;
83807   if( a[0]<10 ) a[0] = 10;
83808   n = 10;
83809   for(i=1; i<=pIdx->nColumn; i++){
83810     a[i] = n;
83811     if( n>5 ) n--;
83812   }
83813   if( pIdx->onError!=OE_None ){
83814     a[pIdx->nColumn] = 1;
83815   }
83816 }
83817
83818 /*
83819 ** This routine will drop an existing named index.  This routine
83820 ** implements the DROP INDEX statement.
83821 */
83822 SQLCIPHER_PRIVATE void sqlcipher3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
83823   Index *pIndex;
83824   Vdbe *v;
83825   sqlcipher3 *db = pParse->db;
83826   int iDb;
83827
83828   assert( pParse->nErr==0 );   /* Never called with prior errors */
83829   if( db->mallocFailed ){
83830     goto exit_drop_index;
83831   }
83832   assert( pName->nSrc==1 );
83833   if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
83834     goto exit_drop_index;
83835   }
83836   pIndex = sqlcipher3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
83837   if( pIndex==0 ){
83838     if( !ifExists ){
83839       sqlcipher3ErrorMsg(pParse, "no such index: %S", pName, 0);
83840     }else{
83841       sqlcipher3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
83842     }
83843     pParse->checkSchema = 1;
83844     goto exit_drop_index;
83845   }
83846   if( pIndex->autoIndex ){
83847     sqlcipher3ErrorMsg(pParse, "index associated with UNIQUE "
83848       "or PRIMARY KEY constraint cannot be dropped", 0);
83849     goto exit_drop_index;
83850   }
83851   iDb = sqlcipher3SchemaToIndex(db, pIndex->pSchema);
83852 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
83853   {
83854     int code = SQLCIPHER_DROP_INDEX;
83855     Table *pTab = pIndex->pTable;
83856     const char *zDb = db->aDb[iDb].zName;
83857     const char *zTab = SCHEMA_TABLE(iDb);
83858     if( sqlcipher3AuthCheck(pParse, SQLCIPHER_DELETE, zTab, 0, zDb) ){
83859       goto exit_drop_index;
83860     }
83861     if( !OMIT_TEMPDB && iDb ) code = SQLCIPHER_DROP_TEMP_INDEX;
83862     if( sqlcipher3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
83863       goto exit_drop_index;
83864     }
83865   }
83866 #endif
83867
83868   /* Generate code to remove the index and from the master table */
83869   v = sqlcipher3GetVdbe(pParse);
83870   if( v ){
83871     sqlcipher3BeginWriteOperation(pParse, 1, iDb);
83872     sqlcipher3NestedParse(pParse,
83873        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
83874        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
83875     );
83876     sqlcipher3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
83877     sqlcipher3ChangeCookie(pParse, iDb);
83878     destroyRootPage(pParse, pIndex->tnum, iDb);
83879     sqlcipher3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
83880   }
83881
83882 exit_drop_index:
83883   sqlcipher3SrcListDelete(db, pName);
83884 }
83885
83886 /*
83887 ** pArray is a pointer to an array of objects.  Each object in the
83888 ** array is szEntry bytes in size.  This routine allocates a new
83889 ** object on the end of the array.
83890 **
83891 ** *pnEntry is the number of entries already in use.  *pnAlloc is
83892 ** the previously allocated size of the array.  initSize is the
83893 ** suggested initial array size allocation.
83894 **
83895 ** The index of the new entry is returned in *pIdx.
83896 **
83897 ** This routine returns a pointer to the array of objects.  This
83898 ** might be the same as the pArray parameter or it might be a different
83899 ** pointer if the array was resized.
83900 */
83901 SQLCIPHER_PRIVATE void *sqlcipher3ArrayAllocate(
83902   sqlcipher3 *db,      /* Connection to notify of malloc failures */
83903   void *pArray,     /* Array of objects.  Might be reallocated */
83904   int szEntry,      /* Size of each object in the array */
83905   int initSize,     /* Suggested initial allocation, in elements */
83906   int *pnEntry,     /* Number of objects currently in use */
83907   int *pnAlloc,     /* Current size of the allocation, in elements */
83908   int *pIdx         /* Write the index of a new slot here */
83909 ){
83910   char *z;
83911   if( *pnEntry >= *pnAlloc ){
83912     void *pNew;
83913     int newSize;
83914     newSize = (*pnAlloc)*2 + initSize;
83915     pNew = sqlcipher3DbRealloc(db, pArray, newSize*szEntry);
83916     if( pNew==0 ){
83917       *pIdx = -1;
83918       return pArray;
83919     }
83920     *pnAlloc = sqlcipher3DbMallocSize(db, pNew)/szEntry;
83921     pArray = pNew;
83922   }
83923   z = (char*)pArray;
83924   memset(&z[*pnEntry * szEntry], 0, szEntry);
83925   *pIdx = *pnEntry;
83926   ++*pnEntry;
83927   return pArray;
83928 }
83929
83930 /*
83931 ** Append a new element to the given IdList.  Create a new IdList if
83932 ** need be.
83933 **
83934 ** A new IdList is returned, or NULL if malloc() fails.
83935 */
83936 SQLCIPHER_PRIVATE IdList *sqlcipher3IdListAppend(sqlcipher3 *db, IdList *pList, Token *pToken){
83937   int i;
83938   if( pList==0 ){
83939     pList = sqlcipher3DbMallocZero(db, sizeof(IdList) );
83940     if( pList==0 ) return 0;
83941     pList->nAlloc = 0;
83942   }
83943   pList->a = sqlcipher3ArrayAllocate(
83944       db,
83945       pList->a,
83946       sizeof(pList->a[0]),
83947       5,
83948       &pList->nId,
83949       &pList->nAlloc,
83950       &i
83951   );
83952   if( i<0 ){
83953     sqlcipher3IdListDelete(db, pList);
83954     return 0;
83955   }
83956   pList->a[i].zName = sqlcipher3NameFromToken(db, pToken);
83957   return pList;
83958 }
83959
83960 /*
83961 ** Delete an IdList.
83962 */
83963 SQLCIPHER_PRIVATE void sqlcipher3IdListDelete(sqlcipher3 *db, IdList *pList){
83964   int i;
83965   if( pList==0 ) return;
83966   for(i=0; i<pList->nId; i++){
83967     sqlcipher3DbFree(db, pList->a[i].zName);
83968   }
83969   sqlcipher3DbFree(db, pList->a);
83970   sqlcipher3DbFree(db, pList);
83971 }
83972
83973 /*
83974 ** Return the index in pList of the identifier named zId.  Return -1
83975 ** if not found.
83976 */
83977 SQLCIPHER_PRIVATE int sqlcipher3IdListIndex(IdList *pList, const char *zName){
83978   int i;
83979   if( pList==0 ) return -1;
83980   for(i=0; i<pList->nId; i++){
83981     if( sqlcipher3StrICmp(pList->a[i].zName, zName)==0 ) return i;
83982   }
83983   return -1;
83984 }
83985
83986 /*
83987 ** Expand the space allocated for the given SrcList object by
83988 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
83989 ** New slots are zeroed.
83990 **
83991 ** For example, suppose a SrcList initially contains two entries: A,B.
83992 ** To append 3 new entries onto the end, do this:
83993 **
83994 **    sqlcipher3SrcListEnlarge(db, pSrclist, 3, 2);
83995 **
83996 ** After the call above it would contain:  A, B, nil, nil, nil.
83997 ** If the iStart argument had been 1 instead of 2, then the result
83998 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
83999 ** the iStart value would be 0.  The result then would
84000 ** be: nil, nil, nil, A, B.
84001 **
84002 ** If a memory allocation fails the SrcList is unchanged.  The
84003 ** db->mallocFailed flag will be set to true.
84004 */
84005 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListEnlarge(
84006   sqlcipher3 *db,       /* Database connection to notify of OOM errors */
84007   SrcList *pSrc,     /* The SrcList to be enlarged */
84008   int nExtra,        /* Number of new slots to add to pSrc->a[] */
84009   int iStart         /* Index in pSrc->a[] of first new slot */
84010 ){
84011   int i;
84012
84013   /* Sanity checking on calling parameters */
84014   assert( iStart>=0 );
84015   assert( nExtra>=1 );
84016   assert( pSrc!=0 );
84017   assert( iStart<=pSrc->nSrc );
84018
84019   /* Allocate additional space if needed */
84020   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
84021     SrcList *pNew;
84022     int nAlloc = pSrc->nSrc+nExtra;
84023     int nGot;
84024     pNew = sqlcipher3DbRealloc(db, pSrc,
84025                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
84026     if( pNew==0 ){
84027       assert( db->mallocFailed );
84028       return pSrc;
84029     }
84030     pSrc = pNew;
84031     nGot = (sqlcipher3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
84032     pSrc->nAlloc = (u16)nGot;
84033   }
84034
84035   /* Move existing slots that come after the newly inserted slots
84036   ** out of the way */
84037   for(i=pSrc->nSrc-1; i>=iStart; i--){
84038     pSrc->a[i+nExtra] = pSrc->a[i];
84039   }
84040   pSrc->nSrc += (i16)nExtra;
84041
84042   /* Zero the newly allocated slots */
84043   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
84044   for(i=iStart; i<iStart+nExtra; i++){
84045     pSrc->a[i].iCursor = -1;
84046   }
84047
84048   /* Return a pointer to the enlarged SrcList */
84049   return pSrc;
84050 }
84051
84052
84053 /*
84054 ** Append a new table name to the given SrcList.  Create a new SrcList if
84055 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
84056 **
84057 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
84058 ** SrcList might be the same as the SrcList that was input or it might be
84059 ** a new one.  If an OOM error does occurs, then the prior value of pList
84060 ** that is input to this routine is automatically freed.
84061 **
84062 ** If pDatabase is not null, it means that the table has an optional
84063 ** database name prefix.  Like this:  "database.table".  The pDatabase
84064 ** points to the table name and the pTable points to the database name.
84065 ** The SrcList.a[].zName field is filled with the table name which might
84066 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
84067 ** SrcList.a[].zDatabase is filled with the database name from pTable,
84068 ** or with NULL if no database is specified.
84069 **
84070 ** In other words, if call like this:
84071 **
84072 **         sqlcipher3SrcListAppend(D,A,B,0);
84073 **
84074 ** Then B is a table name and the database name is unspecified.  If called
84075 ** like this:
84076 **
84077 **         sqlcipher3SrcListAppend(D,A,B,C);
84078 **
84079 ** Then C is the table name and B is the database name.  If C is defined
84080 ** then so is B.  In other words, we never have a case where:
84081 **
84082 **         sqlcipher3SrcListAppend(D,A,0,C);
84083 **
84084 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
84085 ** before being added to the SrcList.
84086 */
84087 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListAppend(
84088   sqlcipher3 *db,        /* Connection to notify of malloc failures */
84089   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
84090   Token *pTable,      /* Table to append */
84091   Token *pDatabase    /* Database of the table */
84092 ){
84093   struct SrcList_item *pItem;
84094   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
84095   if( pList==0 ){
84096     pList = sqlcipher3DbMallocZero(db, sizeof(SrcList) );
84097     if( pList==0 ) return 0;
84098     pList->nAlloc = 1;
84099   }
84100   pList = sqlcipher3SrcListEnlarge(db, pList, 1, pList->nSrc);
84101   if( db->mallocFailed ){
84102     sqlcipher3SrcListDelete(db, pList);
84103     return 0;
84104   }
84105   pItem = &pList->a[pList->nSrc-1];
84106   if( pDatabase && pDatabase->z==0 ){
84107     pDatabase = 0;
84108   }
84109   if( pDatabase ){
84110     Token *pTemp = pDatabase;
84111     pDatabase = pTable;
84112     pTable = pTemp;
84113   }
84114   pItem->zName = sqlcipher3NameFromToken(db, pTable);
84115   pItem->zDatabase = sqlcipher3NameFromToken(db, pDatabase);
84116   return pList;
84117 }
84118
84119 /*
84120 ** Assign VdbeCursor index numbers to all tables in a SrcList
84121 */
84122 SQLCIPHER_PRIVATE void sqlcipher3SrcListAssignCursors(Parse *pParse, SrcList *pList){
84123   int i;
84124   struct SrcList_item *pItem;
84125   assert(pList || pParse->db->mallocFailed );
84126   if( pList ){
84127     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
84128       if( pItem->iCursor>=0 ) break;
84129       pItem->iCursor = pParse->nTab++;
84130       if( pItem->pSelect ){
84131         sqlcipher3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
84132       }
84133     }
84134   }
84135 }
84136
84137 /*
84138 ** Delete an entire SrcList including all its substructure.
84139 */
84140 SQLCIPHER_PRIVATE void sqlcipher3SrcListDelete(sqlcipher3 *db, SrcList *pList){
84141   int i;
84142   struct SrcList_item *pItem;
84143   if( pList==0 ) return;
84144   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
84145     sqlcipher3DbFree(db, pItem->zDatabase);
84146     sqlcipher3DbFree(db, pItem->zName);
84147     sqlcipher3DbFree(db, pItem->zAlias);
84148     sqlcipher3DbFree(db, pItem->zIndex);
84149     sqlcipher3DeleteTable(db, pItem->pTab);
84150     sqlcipher3SelectDelete(db, pItem->pSelect);
84151     sqlcipher3ExprDelete(db, pItem->pOn);
84152     sqlcipher3IdListDelete(db, pItem->pUsing);
84153   }
84154   sqlcipher3DbFree(db, pList);
84155 }
84156
84157 /*
84158 ** This routine is called by the parser to add a new term to the
84159 ** end of a growing FROM clause.  The "p" parameter is the part of
84160 ** the FROM clause that has already been constructed.  "p" is NULL
84161 ** if this is the first term of the FROM clause.  pTable and pDatabase
84162 ** are the name of the table and database named in the FROM clause term.
84163 ** pDatabase is NULL if the database name qualifier is missing - the
84164 ** usual case.  If the term has a alias, then pAlias points to the
84165 ** alias token.  If the term is a subquery, then pSubquery is the
84166 ** SELECT statement that the subquery encodes.  The pTable and
84167 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
84168 ** parameters are the content of the ON and USING clauses.
84169 **
84170 ** Return a new SrcList which encodes is the FROM with the new
84171 ** term added.
84172 */
84173 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListAppendFromTerm(
84174   Parse *pParse,          /* Parsing context */
84175   SrcList *p,             /* The left part of the FROM clause already seen */
84176   Token *pTable,          /* Name of the table to add to the FROM clause */
84177   Token *pDatabase,       /* Name of the database containing pTable */
84178   Token *pAlias,          /* The right-hand side of the AS subexpression */
84179   Select *pSubquery,      /* A subquery used in place of a table name */
84180   Expr *pOn,              /* The ON clause of a join */
84181   IdList *pUsing          /* The USING clause of a join */
84182 ){
84183   struct SrcList_item *pItem;
84184   sqlcipher3 *db = pParse->db;
84185   if( !p && (pOn || pUsing) ){
84186     sqlcipher3ErrorMsg(pParse, "a JOIN clause is required before %s", 
84187       (pOn ? "ON" : "USING")
84188     );
84189     goto append_from_error;
84190   }
84191   p = sqlcipher3SrcListAppend(db, p, pTable, pDatabase);
84192   if( p==0 || NEVER(p->nSrc==0) ){
84193     goto append_from_error;
84194   }
84195   pItem = &p->a[p->nSrc-1];
84196   assert( pAlias!=0 );
84197   if( pAlias->n ){
84198     pItem->zAlias = sqlcipher3NameFromToken(db, pAlias);
84199   }
84200   pItem->pSelect = pSubquery;
84201   pItem->pOn = pOn;
84202   pItem->pUsing = pUsing;
84203   return p;
84204
84205  append_from_error:
84206   assert( p==0 );
84207   sqlcipher3ExprDelete(db, pOn);
84208   sqlcipher3IdListDelete(db, pUsing);
84209   sqlcipher3SelectDelete(db, pSubquery);
84210   return 0;
84211 }
84212
84213 /*
84214 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
84215 ** element of the source-list passed as the second argument.
84216 */
84217 SQLCIPHER_PRIVATE void sqlcipher3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
84218   assert( pIndexedBy!=0 );
84219   if( p && ALWAYS(p->nSrc>0) ){
84220     struct SrcList_item *pItem = &p->a[p->nSrc-1];
84221     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
84222     if( pIndexedBy->n==1 && !pIndexedBy->z ){
84223       /* A "NOT INDEXED" clause was supplied. See parse.y 
84224       ** construct "indexed_opt" for details. */
84225       pItem->notIndexed = 1;
84226     }else{
84227       pItem->zIndex = sqlcipher3NameFromToken(pParse->db, pIndexedBy);
84228     }
84229   }
84230 }
84231
84232 /*
84233 ** When building up a FROM clause in the parser, the join operator
84234 ** is initially attached to the left operand.  But the code generator
84235 ** expects the join operator to be on the right operand.  This routine
84236 ** Shifts all join operators from left to right for an entire FROM
84237 ** clause.
84238 **
84239 ** Example: Suppose the join is like this:
84240 **
84241 **           A natural cross join B
84242 **
84243 ** The operator is "natural cross join".  The A and B operands are stored
84244 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
84245 ** operator with A.  This routine shifts that operator over to B.
84246 */
84247 SQLCIPHER_PRIVATE void sqlcipher3SrcListShiftJoinType(SrcList *p){
84248   if( p ){
84249     int i;
84250     assert( p->a || p->nSrc==0 );
84251     for(i=p->nSrc-1; i>0; i--){
84252       p->a[i].jointype = p->a[i-1].jointype;
84253     }
84254     p->a[0].jointype = 0;
84255   }
84256 }
84257
84258 /*
84259 ** Begin a transaction
84260 */
84261 SQLCIPHER_PRIVATE void sqlcipher3BeginTransaction(Parse *pParse, int type){
84262   sqlcipher3 *db;
84263   Vdbe *v;
84264   int i;
84265
84266   assert( pParse!=0 );
84267   db = pParse->db;
84268   assert( db!=0 );
84269 /*  if( db->aDb[0].pBt==0 ) return; */
84270   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_TRANSACTION, "BEGIN", 0, 0) ){
84271     return;
84272   }
84273   v = sqlcipher3GetVdbe(pParse);
84274   if( !v ) return;
84275   if( type!=TK_DEFERRED ){
84276     for(i=0; i<db->nDb; i++){
84277       sqlcipher3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
84278       sqlcipher3VdbeUsesBtree(v, i);
84279     }
84280   }
84281   sqlcipher3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
84282 }
84283
84284 /*
84285 ** Commit a transaction
84286 */
84287 SQLCIPHER_PRIVATE void sqlcipher3CommitTransaction(Parse *pParse){
84288   Vdbe *v;
84289
84290   assert( pParse!=0 );
84291   assert( pParse->db!=0 );
84292   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_TRANSACTION, "COMMIT", 0, 0) ){
84293     return;
84294   }
84295   v = sqlcipher3GetVdbe(pParse);
84296   if( v ){
84297     sqlcipher3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
84298   }
84299 }
84300
84301 /*
84302 ** Rollback a transaction
84303 */
84304 SQLCIPHER_PRIVATE void sqlcipher3RollbackTransaction(Parse *pParse){
84305   Vdbe *v;
84306
84307   assert( pParse!=0 );
84308   assert( pParse->db!=0 );
84309   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_TRANSACTION, "ROLLBACK", 0, 0) ){
84310     return;
84311   }
84312   v = sqlcipher3GetVdbe(pParse);
84313   if( v ){
84314     sqlcipher3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
84315   }
84316 }
84317
84318 /*
84319 ** This function is called by the parser when it parses a command to create,
84320 ** release or rollback an SQL savepoint. 
84321 */
84322 SQLCIPHER_PRIVATE void sqlcipher3Savepoint(Parse *pParse, int op, Token *pName){
84323   char *zName = sqlcipher3NameFromToken(pParse->db, pName);
84324   if( zName ){
84325     Vdbe *v = sqlcipher3GetVdbe(pParse);
84326 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
84327     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
84328     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
84329 #endif
84330     if( !v || sqlcipher3AuthCheck(pParse, SQLCIPHER_SAVEPOINT, az[op], zName, 0) ){
84331       sqlcipher3DbFree(pParse->db, zName);
84332       return;
84333     }
84334     sqlcipher3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
84335   }
84336 }
84337
84338 /*
84339 ** Make sure the TEMP database is open and available for use.  Return
84340 ** the number of errors.  Leave any error messages in the pParse structure.
84341 */
84342 SQLCIPHER_PRIVATE int sqlcipher3OpenTempDatabase(Parse *pParse){
84343   sqlcipher3 *db = pParse->db;
84344   if( db->aDb[1].pBt==0 && !pParse->explain ){
84345     int rc;
84346     Btree *pBt;
84347     static const int flags = 
84348           SQLCIPHER_OPEN_READWRITE |
84349           SQLCIPHER_OPEN_CREATE |
84350           SQLCIPHER_OPEN_EXCLUSIVE |
84351           SQLCIPHER_OPEN_DELETEONCLOSE |
84352           SQLCIPHER_OPEN_TEMP_DB;
84353
84354     rc = sqlcipher3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
84355     if( rc!=SQLCIPHER_OK ){
84356       sqlcipher3ErrorMsg(pParse, "unable to open a temporary database "
84357         "file for storing temporary tables");
84358       pParse->rc = rc;
84359       return 1;
84360     }
84361     db->aDb[1].pBt = pBt;
84362     assert( db->aDb[1].pSchema );
84363     if( SQLCIPHER_NOMEM==sqlcipher3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
84364       db->mallocFailed = 1;
84365       return 1;
84366     }
84367   }
84368   return 0;
84369 }
84370
84371 /*
84372 ** Generate VDBE code that will verify the schema cookie and start
84373 ** a read-transaction for all named database files.
84374 **
84375 ** It is important that all schema cookies be verified and all
84376 ** read transactions be started before anything else happens in
84377 ** the VDBE program.  But this routine can be called after much other
84378 ** code has been generated.  So here is what we do:
84379 **
84380 ** The first time this routine is called, we code an OP_Goto that
84381 ** will jump to a subroutine at the end of the program.  Then we
84382 ** record every database that needs its schema verified in the
84383 ** pParse->cookieMask field.  Later, after all other code has been
84384 ** generated, the subroutine that does the cookie verifications and
84385 ** starts the transactions will be coded and the OP_Goto P2 value
84386 ** will be made to point to that subroutine.  The generation of the
84387 ** cookie verification subroutine code happens in sqlcipher3FinishCoding().
84388 **
84389 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
84390 ** schema on any databases.  This can be used to position the OP_Goto
84391 ** early in the code, before we know if any database tables will be used.
84392 */
84393 SQLCIPHER_PRIVATE void sqlcipher3CodeVerifySchema(Parse *pParse, int iDb){
84394   Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
84395
84396   if( pToplevel->cookieGoto==0 ){
84397     Vdbe *v = sqlcipher3GetVdbe(pToplevel);
84398     if( v==0 ) return;  /* This only happens if there was a prior error */
84399     pToplevel->cookieGoto = sqlcipher3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
84400   }
84401   if( iDb>=0 ){
84402     sqlcipher3 *db = pToplevel->db;
84403     yDbMask mask;
84404
84405     assert( iDb<db->nDb );
84406     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
84407     assert( iDb<SQLCIPHER_MAX_ATTACHED+2 );
84408     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
84409     mask = ((yDbMask)1)<<iDb;
84410     if( (pToplevel->cookieMask & mask)==0 ){
84411       pToplevel->cookieMask |= mask;
84412       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
84413       if( !OMIT_TEMPDB && iDb==1 ){
84414         sqlcipher3OpenTempDatabase(pToplevel);
84415       }
84416     }
84417   }
84418 }
84419
84420 /*
84421 ** If argument zDb is NULL, then call sqlcipher3CodeVerifySchema() for each 
84422 ** attached database. Otherwise, invoke it for the database named zDb only.
84423 */
84424 SQLCIPHER_PRIVATE void sqlcipher3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
84425   sqlcipher3 *db = pParse->db;
84426   int i;
84427   for(i=0; i<db->nDb; i++){
84428     Db *pDb = &db->aDb[i];
84429     if( pDb->pBt && (!zDb || 0==sqlcipher3StrICmp(zDb, pDb->zName)) ){
84430       sqlcipher3CodeVerifySchema(pParse, i);
84431     }
84432   }
84433 }
84434
84435 /*
84436 ** Generate VDBE code that prepares for doing an operation that
84437 ** might change the database.
84438 **
84439 ** This routine starts a new transaction if we are not already within
84440 ** a transaction.  If we are already within a transaction, then a checkpoint
84441 ** is set if the setStatement parameter is true.  A checkpoint should
84442 ** be set for operations that might fail (due to a constraint) part of
84443 ** the way through and which will need to undo some writes without having to
84444 ** rollback the whole transaction.  For operations where all constraints
84445 ** can be checked before any changes are made to the database, it is never
84446 ** necessary to undo a write and the checkpoint should not be set.
84447 */
84448 SQLCIPHER_PRIVATE void sqlcipher3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
84449   Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
84450   sqlcipher3CodeVerifySchema(pParse, iDb);
84451   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
84452   pToplevel->isMultiWrite |= setStatement;
84453 }
84454
84455 /*
84456 ** Indicate that the statement currently under construction might write
84457 ** more than one entry (example: deleting one row then inserting another,
84458 ** inserting multiple rows in a table, or inserting a row and index entries.)
84459 ** If an abort occurs after some of these writes have completed, then it will
84460 ** be necessary to undo the completed writes.
84461 */
84462 SQLCIPHER_PRIVATE void sqlcipher3MultiWrite(Parse *pParse){
84463   Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
84464   pToplevel->isMultiWrite = 1;
84465 }
84466
84467 /* 
84468 ** The code generator calls this routine if is discovers that it is
84469 ** possible to abort a statement prior to completion.  In order to 
84470 ** perform this abort without corrupting the database, we need to make
84471 ** sure that the statement is protected by a statement transaction.
84472 **
84473 ** Technically, we only need to set the mayAbort flag if the
84474 ** isMultiWrite flag was previously set.  There is a time dependency
84475 ** such that the abort must occur after the multiwrite.  This makes
84476 ** some statements involving the REPLACE conflict resolution algorithm
84477 ** go a little faster.  But taking advantage of this time dependency
84478 ** makes it more difficult to prove that the code is correct (in 
84479 ** particular, it prevents us from writing an effective
84480 ** implementation of sqlcipher3AssertMayAbort()) and so we have chosen
84481 ** to take the safe route and skip the optimization.
84482 */
84483 SQLCIPHER_PRIVATE void sqlcipher3MayAbort(Parse *pParse){
84484   Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
84485   pToplevel->mayAbort = 1;
84486 }
84487
84488 /*
84489 ** Code an OP_Halt that causes the vdbe to return an SQLCIPHER_CONSTRAINT
84490 ** error. The onError parameter determines which (if any) of the statement
84491 ** and/or current transaction is rolled back.
84492 */
84493 SQLCIPHER_PRIVATE void sqlcipher3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
84494   Vdbe *v = sqlcipher3GetVdbe(pParse);
84495   if( onError==OE_Abort ){
84496     sqlcipher3MayAbort(pParse);
84497   }
84498   sqlcipher3VdbeAddOp4(v, OP_Halt, SQLCIPHER_CONSTRAINT, onError, 0, p4, p4type);
84499 }
84500
84501 /*
84502 ** Check to see if pIndex uses the collating sequence pColl.  Return
84503 ** true if it does and false if it does not.
84504 */
84505 #ifndef SQLCIPHER_OMIT_REINDEX
84506 static int collationMatch(const char *zColl, Index *pIndex){
84507   int i;
84508   assert( zColl!=0 );
84509   for(i=0; i<pIndex->nColumn; i++){
84510     const char *z = pIndex->azColl[i];
84511     assert( z!=0 );
84512     if( 0==sqlcipher3StrICmp(z, zColl) ){
84513       return 1;
84514     }
84515   }
84516   return 0;
84517 }
84518 #endif
84519
84520 /*
84521 ** Recompute all indices of pTab that use the collating sequence pColl.
84522 ** If pColl==0 then recompute all indices of pTab.
84523 */
84524 #ifndef SQLCIPHER_OMIT_REINDEX
84525 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
84526   Index *pIndex;              /* An index associated with pTab */
84527
84528   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
84529     if( zColl==0 || collationMatch(zColl, pIndex) ){
84530       int iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
84531       sqlcipher3BeginWriteOperation(pParse, 0, iDb);
84532       sqlcipher3RefillIndex(pParse, pIndex, -1);
84533     }
84534   }
84535 }
84536 #endif
84537
84538 /*
84539 ** Recompute all indices of all tables in all databases where the
84540 ** indices use the collating sequence pColl.  If pColl==0 then recompute
84541 ** all indices everywhere.
84542 */
84543 #ifndef SQLCIPHER_OMIT_REINDEX
84544 static void reindexDatabases(Parse *pParse, char const *zColl){
84545   Db *pDb;                    /* A single database */
84546   int iDb;                    /* The database index number */
84547   sqlcipher3 *db = pParse->db;   /* The database connection */
84548   HashElem *k;                /* For looping over tables in pDb */
84549   Table *pTab;                /* A table in the database */
84550
84551   assert( sqlcipher3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
84552   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
84553     assert( pDb!=0 );
84554     for(k=sqlcipherHashFirst(&pDb->pSchema->tblHash);  k; k=sqlcipherHashNext(k)){
84555       pTab = (Table*)sqlcipherHashData(k);
84556       reindexTable(pParse, pTab, zColl);
84557     }
84558   }
84559 }
84560 #endif
84561
84562 /*
84563 ** Generate code for the REINDEX command.
84564 **
84565 **        REINDEX                            -- 1
84566 **        REINDEX  <collation>               -- 2
84567 **        REINDEX  ?<database>.?<tablename>  -- 3
84568 **        REINDEX  ?<database>.?<indexname>  -- 4
84569 **
84570 ** Form 1 causes all indices in all attached databases to be rebuilt.
84571 ** Form 2 rebuilds all indices in all databases that use the named
84572 ** collating function.  Forms 3 and 4 rebuild the named index or all
84573 ** indices associated with the named table.
84574 */
84575 #ifndef SQLCIPHER_OMIT_REINDEX
84576 SQLCIPHER_PRIVATE void sqlcipher3Reindex(Parse *pParse, Token *pName1, Token *pName2){
84577   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
84578   char *z;                    /* Name of a table or index */
84579   const char *zDb;            /* Name of the database */
84580   Table *pTab;                /* A table in the database */
84581   Index *pIndex;              /* An index associated with pTab */
84582   int iDb;                    /* The database index number */
84583   sqlcipher3 *db = pParse->db;   /* The database connection */
84584   Token *pObjName;            /* Name of the table or index to be reindexed */
84585
84586   /* Read the database schema. If an error occurs, leave an error message
84587   ** and code in pParse and return NULL. */
84588   if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
84589     return;
84590   }
84591
84592   if( pName1==0 ){
84593     reindexDatabases(pParse, 0);
84594     return;
84595   }else if( NEVER(pName2==0) || pName2->z==0 ){
84596     char *zColl;
84597     assert( pName1->z );
84598     zColl = sqlcipher3NameFromToken(pParse->db, pName1);
84599     if( !zColl ) return;
84600     pColl = sqlcipher3FindCollSeq(db, ENC(db), zColl, 0);
84601     if( pColl ){
84602       reindexDatabases(pParse, zColl);
84603       sqlcipher3DbFree(db, zColl);
84604       return;
84605     }
84606     sqlcipher3DbFree(db, zColl);
84607   }
84608   iDb = sqlcipher3TwoPartName(pParse, pName1, pName2, &pObjName);
84609   if( iDb<0 ) return;
84610   z = sqlcipher3NameFromToken(db, pObjName);
84611   if( z==0 ) return;
84612   zDb = db->aDb[iDb].zName;
84613   pTab = sqlcipher3FindTable(db, z, zDb);
84614   if( pTab ){
84615     reindexTable(pParse, pTab, 0);
84616     sqlcipher3DbFree(db, z);
84617     return;
84618   }
84619   pIndex = sqlcipher3FindIndex(db, z, zDb);
84620   sqlcipher3DbFree(db, z);
84621   if( pIndex ){
84622     sqlcipher3BeginWriteOperation(pParse, 0, iDb);
84623     sqlcipher3RefillIndex(pParse, pIndex, -1);
84624     return;
84625   }
84626   sqlcipher3ErrorMsg(pParse, "unable to identify the object to be reindexed");
84627 }
84628 #endif
84629
84630 /*
84631 ** Return a dynamicly allocated KeyInfo structure that can be used
84632 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
84633 **
84634 ** If successful, a pointer to the new structure is returned. In this case
84635 ** the caller is responsible for calling sqlcipher3DbFree(db, ) on the returned 
84636 ** pointer. If an error occurs (out of memory or missing collation 
84637 ** sequence), NULL is returned and the state of pParse updated to reflect
84638 ** the error.
84639 */
84640 SQLCIPHER_PRIVATE KeyInfo *sqlcipher3IndexKeyinfo(Parse *pParse, Index *pIdx){
84641   int i;
84642   int nCol = pIdx->nColumn;
84643   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
84644   sqlcipher3 *db = pParse->db;
84645   KeyInfo *pKey = (KeyInfo *)sqlcipher3DbMallocZero(db, nBytes);
84646
84647   if( pKey ){
84648     pKey->db = pParse->db;
84649     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
84650     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
84651     for(i=0; i<nCol; i++){
84652       char *zColl = pIdx->azColl[i];
84653       assert( zColl );
84654       pKey->aColl[i] = sqlcipher3LocateCollSeq(pParse, zColl);
84655       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
84656     }
84657     pKey->nField = (u16)nCol;
84658   }
84659
84660   if( pParse->nErr ){
84661     sqlcipher3DbFree(db, pKey);
84662     pKey = 0;
84663   }
84664   return pKey;
84665 }
84666
84667 /************** End of build.c ***********************************************/
84668 /************** Begin file callback.c ****************************************/
84669 /*
84670 ** 2005 May 23 
84671 **
84672 ** The author disclaims copyright to this source code.  In place of
84673 ** a legal notice, here is a blessing:
84674 **
84675 **    May you do good and not evil.
84676 **    May you find forgiveness for yourself and forgive others.
84677 **    May you share freely, never taking more than you give.
84678 **
84679 *************************************************************************
84680 **
84681 ** This file contains functions used to access the internal hash tables
84682 ** of user defined functions and collation sequences.
84683 */
84684
84685
84686 /*
84687 ** Invoke the 'collation needed' callback to request a collation sequence
84688 ** in the encoding enc of name zName, length nName.
84689 */
84690 static void callCollNeeded(sqlcipher3 *db, int enc, const char *zName){
84691   assert( !db->xCollNeeded || !db->xCollNeeded16 );
84692   if( db->xCollNeeded ){
84693     char *zExternal = sqlcipher3DbStrDup(db, zName);
84694     if( !zExternal ) return;
84695     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
84696     sqlcipher3DbFree(db, zExternal);
84697   }
84698 #ifndef SQLCIPHER_OMIT_UTF16
84699   if( db->xCollNeeded16 ){
84700     char const *zExternal;
84701     sqlcipher3_value *pTmp = sqlcipher3ValueNew(db);
84702     sqlcipher3ValueSetStr(pTmp, -1, zName, SQLCIPHER_UTF8, SQLCIPHER_STATIC);
84703     zExternal = sqlcipher3ValueText(pTmp, SQLCIPHER_UTF16NATIVE);
84704     if( zExternal ){
84705       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
84706     }
84707     sqlcipher3ValueFree(pTmp);
84708   }
84709 #endif
84710 }
84711
84712 /*
84713 ** This routine is called if the collation factory fails to deliver a
84714 ** collation function in the best encoding but there may be other versions
84715 ** of this collation function (for other text encodings) available. Use one
84716 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
84717 ** possible.
84718 */
84719 static int synthCollSeq(sqlcipher3 *db, CollSeq *pColl){
84720   CollSeq *pColl2;
84721   char *z = pColl->zName;
84722   int i;
84723   static const u8 aEnc[] = { SQLCIPHER_UTF16BE, SQLCIPHER_UTF16LE, SQLCIPHER_UTF8 };
84724   for(i=0; i<3; i++){
84725     pColl2 = sqlcipher3FindCollSeq(db, aEnc[i], z, 0);
84726     if( pColl2->xCmp!=0 ){
84727       memcpy(pColl, pColl2, sizeof(CollSeq));
84728       pColl->xDel = 0;         /* Do not copy the destructor */
84729       return SQLCIPHER_OK;
84730     }
84731   }
84732   return SQLCIPHER_ERROR;
84733 }
84734
84735 /*
84736 ** This function is responsible for invoking the collation factory callback
84737 ** or substituting a collation sequence of a different encoding when the
84738 ** requested collation sequence is not available in the desired encoding.
84739 ** 
84740 ** If it is not NULL, then pColl must point to the database native encoding 
84741 ** collation sequence with name zName, length nName.
84742 **
84743 ** The return value is either the collation sequence to be used in database
84744 ** db for collation type name zName, length nName, or NULL, if no collation
84745 ** sequence can be found.
84746 **
84747 ** See also: sqlcipher3LocateCollSeq(), sqlcipher3FindCollSeq()
84748 */
84749 SQLCIPHER_PRIVATE CollSeq *sqlcipher3GetCollSeq(
84750   sqlcipher3* db,          /* The database connection */
84751   u8 enc,               /* The desired encoding for the collating sequence */
84752   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
84753   const char *zName     /* Collating sequence name */
84754 ){
84755   CollSeq *p;
84756
84757   p = pColl;
84758   if( !p ){
84759     p = sqlcipher3FindCollSeq(db, enc, zName, 0);
84760   }
84761   if( !p || !p->xCmp ){
84762     /* No collation sequence of this type for this encoding is registered.
84763     ** Call the collation factory to see if it can supply us with one.
84764     */
84765     callCollNeeded(db, enc, zName);
84766     p = sqlcipher3FindCollSeq(db, enc, zName, 0);
84767   }
84768   if( p && !p->xCmp && synthCollSeq(db, p) ){
84769     p = 0;
84770   }
84771   assert( !p || p->xCmp );
84772   return p;
84773 }
84774
84775 /*
84776 ** This routine is called on a collation sequence before it is used to
84777 ** check that it is defined. An undefined collation sequence exists when
84778 ** a database is loaded that contains references to collation sequences
84779 ** that have not been defined by sqlcipher3_create_collation() etc.
84780 **
84781 ** If required, this routine calls the 'collation needed' callback to
84782 ** request a definition of the collating sequence. If this doesn't work, 
84783 ** an equivalent collating sequence that uses a text encoding different
84784 ** from the main database is substituted, if one is available.
84785 */
84786 SQLCIPHER_PRIVATE int sqlcipher3CheckCollSeq(Parse *pParse, CollSeq *pColl){
84787   if( pColl ){
84788     const char *zName = pColl->zName;
84789     sqlcipher3 *db = pParse->db;
84790     CollSeq *p = sqlcipher3GetCollSeq(db, ENC(db), pColl, zName);
84791     if( !p ){
84792       sqlcipher3ErrorMsg(pParse, "no such collation sequence: %s", zName);
84793       pParse->nErr++;
84794       return SQLCIPHER_ERROR;
84795     }
84796     assert( p==pColl );
84797   }
84798   return SQLCIPHER_OK;
84799 }
84800
84801
84802
84803 /*
84804 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
84805 ** specified by zName and nName is not found and parameter 'create' is
84806 ** true, then create a new entry. Otherwise return NULL.
84807 **
84808 ** Each pointer stored in the sqlcipher3.aCollSeq hash table contains an
84809 ** array of three CollSeq structures. The first is the collation sequence
84810 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
84811 **
84812 ** Stored immediately after the three collation sequences is a copy of
84813 ** the collation sequence name. A pointer to this string is stored in
84814 ** each collation sequence structure.
84815 */
84816 static CollSeq *findCollSeqEntry(
84817   sqlcipher3 *db,          /* Database connection */
84818   const char *zName,    /* Name of the collating sequence */
84819   int create            /* Create a new entry if true */
84820 ){
84821   CollSeq *pColl;
84822   int nName = sqlcipher3Strlen30(zName);
84823   pColl = sqlcipher3HashFind(&db->aCollSeq, zName, nName);
84824
84825   if( 0==pColl && create ){
84826     pColl = sqlcipher3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
84827     if( pColl ){
84828       CollSeq *pDel = 0;
84829       pColl[0].zName = (char*)&pColl[3];
84830       pColl[0].enc = SQLCIPHER_UTF8;
84831       pColl[1].zName = (char*)&pColl[3];
84832       pColl[1].enc = SQLCIPHER_UTF16LE;
84833       pColl[2].zName = (char*)&pColl[3];
84834       pColl[2].enc = SQLCIPHER_UTF16BE;
84835       memcpy(pColl[0].zName, zName, nName);
84836       pColl[0].zName[nName] = 0;
84837       pDel = sqlcipher3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
84838
84839       /* If a malloc() failure occurred in sqlcipher3HashInsert(), it will 
84840       ** return the pColl pointer to be deleted (because it wasn't added
84841       ** to the hash table).
84842       */
84843       assert( pDel==0 || pDel==pColl );
84844       if( pDel!=0 ){
84845         db->mallocFailed = 1;
84846         sqlcipher3DbFree(db, pDel);
84847         pColl = 0;
84848       }
84849     }
84850   }
84851   return pColl;
84852 }
84853
84854 /*
84855 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
84856 ** Return the CollSeq* pointer for the collation sequence named zName
84857 ** for the encoding 'enc' from the database 'db'.
84858 **
84859 ** If the entry specified is not found and 'create' is true, then create a
84860 ** new entry.  Otherwise return NULL.
84861 **
84862 ** A separate function sqlcipher3LocateCollSeq() is a wrapper around
84863 ** this routine.  sqlcipher3LocateCollSeq() invokes the collation factory
84864 ** if necessary and generates an error message if the collating sequence
84865 ** cannot be found.
84866 **
84867 ** See also: sqlcipher3LocateCollSeq(), sqlcipher3GetCollSeq()
84868 */
84869 SQLCIPHER_PRIVATE CollSeq *sqlcipher3FindCollSeq(
84870   sqlcipher3 *db,
84871   u8 enc,
84872   const char *zName,
84873   int create
84874 ){
84875   CollSeq *pColl;
84876   if( zName ){
84877     pColl = findCollSeqEntry(db, zName, create);
84878   }else{
84879     pColl = db->pDfltColl;
84880   }
84881   assert( SQLCIPHER_UTF8==1 && SQLCIPHER_UTF16LE==2 && SQLCIPHER_UTF16BE==3 );
84882   assert( enc>=SQLCIPHER_UTF8 && enc<=SQLCIPHER_UTF16BE );
84883   if( pColl ) pColl += enc-1;
84884   return pColl;
84885 }
84886
84887 /* During the search for the best function definition, this procedure
84888 ** is called to test how well the function passed as the first argument
84889 ** matches the request for a function with nArg arguments in a system
84890 ** that uses encoding enc. The value returned indicates how well the
84891 ** request is matched. A higher value indicates a better match.
84892 **
84893 ** The returned value is always between 0 and 6, as follows:
84894 **
84895 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
84896 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
84897 **    encoding is requested, or vice versa.
84898 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
84899 **    requested, or vice versa.
84900 ** 3: A variable arguments function using the same text encoding.
84901 ** 4: A function with the exact number of arguments requested that
84902 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
84903 ** 5: A function with the exact number of arguments requested that
84904 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
84905 ** 6: An exact match.
84906 **
84907 */
84908 static int matchQuality(FuncDef *p, int nArg, u8 enc){
84909   int match = 0;
84910   if( p->nArg==-1 || p->nArg==nArg 
84911    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
84912   ){
84913     match = 1;
84914     if( p->nArg==nArg || nArg==-1 ){
84915       match = 4;
84916     }
84917     if( enc==p->iPrefEnc ){
84918       match += 2;
84919     }
84920     else if( (enc==SQLCIPHER_UTF16LE && p->iPrefEnc==SQLCIPHER_UTF16BE) ||
84921              (enc==SQLCIPHER_UTF16BE && p->iPrefEnc==SQLCIPHER_UTF16LE) ){
84922       match += 1;
84923     }
84924   }
84925   return match;
84926 }
84927
84928 /*
84929 ** Search a FuncDefHash for a function with the given name.  Return
84930 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
84931 */
84932 static FuncDef *functionSearch(
84933   FuncDefHash *pHash,  /* Hash table to search */
84934   int h,               /* Hash of the name */
84935   const char *zFunc,   /* Name of function */
84936   int nFunc            /* Number of bytes in zFunc */
84937 ){
84938   FuncDef *p;
84939   for(p=pHash->a[h]; p; p=p->pHash){
84940     if( sqlcipher3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
84941       return p;
84942     }
84943   }
84944   return 0;
84945 }
84946
84947 /*
84948 ** Insert a new FuncDef into a FuncDefHash hash table.
84949 */
84950 SQLCIPHER_PRIVATE void sqlcipher3FuncDefInsert(
84951   FuncDefHash *pHash,  /* The hash table into which to insert */
84952   FuncDef *pDef        /* The function definition to insert */
84953 ){
84954   FuncDef *pOther;
84955   int nName = sqlcipher3Strlen30(pDef->zName);
84956   u8 c1 = (u8)pDef->zName[0];
84957   int h = (sqlcipher3UpperToLower[c1] + nName) % ArraySize(pHash->a);
84958   pOther = functionSearch(pHash, h, pDef->zName, nName);
84959   if( pOther ){
84960     assert( pOther!=pDef && pOther->pNext!=pDef );
84961     pDef->pNext = pOther->pNext;
84962     pOther->pNext = pDef;
84963   }else{
84964     pDef->pNext = 0;
84965     pDef->pHash = pHash->a[h];
84966     pHash->a[h] = pDef;
84967   }
84968 }
84969   
84970   
84971
84972 /*
84973 ** Locate a user function given a name, a number of arguments and a flag
84974 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
84975 ** pointer to the FuncDef structure that defines that function, or return
84976 ** NULL if the function does not exist.
84977 **
84978 ** If the createFlag argument is true, then a new (blank) FuncDef
84979 ** structure is created and liked into the "db" structure if a
84980 ** no matching function previously existed.  When createFlag is true
84981 ** and the nArg parameter is -1, then only a function that accepts
84982 ** any number of arguments will be returned.
84983 **
84984 ** If createFlag is false and nArg is -1, then the first valid
84985 ** function found is returned.  A function is valid if either xFunc
84986 ** or xStep is non-zero.
84987 **
84988 ** If createFlag is false, then a function with the required name and
84989 ** number of arguments may be returned even if the eTextRep flag does not
84990 ** match that requested.
84991 */
84992 SQLCIPHER_PRIVATE FuncDef *sqlcipher3FindFunction(
84993   sqlcipher3 *db,       /* An open database */
84994   const char *zName, /* Name of the function.  Not null-terminated */
84995   int nName,         /* Number of characters in the name */
84996   int nArg,          /* Number of arguments.  -1 means any number */
84997   u8 enc,            /* Preferred text encoding */
84998   int createFlag     /* Create new entry if true and does not otherwise exist */
84999 ){
85000   FuncDef *p;         /* Iterator variable */
85001   FuncDef *pBest = 0; /* Best match found so far */
85002   int bestScore = 0;  /* Score of best match */
85003   int h;              /* Hash value */
85004
85005
85006   assert( enc==SQLCIPHER_UTF8 || enc==SQLCIPHER_UTF16LE || enc==SQLCIPHER_UTF16BE );
85007   h = (sqlcipher3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
85008
85009   /* First search for a match amongst the application-defined functions.
85010   */
85011   p = functionSearch(&db->aFunc, h, zName, nName);
85012   while( p ){
85013     int score = matchQuality(p, nArg, enc);
85014     if( score>bestScore ){
85015       pBest = p;
85016       bestScore = score;
85017     }
85018     p = p->pNext;
85019   }
85020
85021   /* If no match is found, search the built-in functions.
85022   **
85023   ** If the SQLCIPHER_PreferBuiltin flag is set, then search the built-in
85024   ** functions even if a prior app-defined function was found.  And give
85025   ** priority to built-in functions.
85026   **
85027   ** Except, if createFlag is true, that means that we are trying to
85028   ** install a new function.  Whatever FuncDef structure is returned it will
85029   ** have fields overwritten with new information appropriate for the
85030   ** new function.  But the FuncDefs for built-in functions are read-only.
85031   ** So we must not search for built-ins when creating a new function.
85032   */ 
85033   if( !createFlag && (pBest==0 || (db->flags & SQLCIPHER_PreferBuiltin)!=0) ){
85034     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlcipher3GlobalFunctions);
85035     bestScore = 0;
85036     p = functionSearch(pHash, h, zName, nName);
85037     while( p ){
85038       int score = matchQuality(p, nArg, enc);
85039       if( score>bestScore ){
85040         pBest = p;
85041         bestScore = score;
85042       }
85043       p = p->pNext;
85044     }
85045   }
85046
85047   /* If the createFlag parameter is true and the search did not reveal an
85048   ** exact match for the name, number of arguments and encoding, then add a
85049   ** new entry to the hash table and return it.
85050   */
85051   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
85052       (pBest = sqlcipher3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
85053     pBest->zName = (char *)&pBest[1];
85054     pBest->nArg = (u16)nArg;
85055     pBest->iPrefEnc = enc;
85056     memcpy(pBest->zName, zName, nName);
85057     pBest->zName[nName] = 0;
85058     sqlcipher3FuncDefInsert(&db->aFunc, pBest);
85059   }
85060
85061   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
85062     return pBest;
85063   }
85064   return 0;
85065 }
85066
85067 /*
85068 ** Free all resources held by the schema structure. The void* argument points
85069 ** at a Schema struct. This function does not call sqlcipher3DbFree(db, ) on the 
85070 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
85071 ** of the schema hash tables).
85072 **
85073 ** The Schema.cache_size variable is not cleared.
85074 */
85075 SQLCIPHER_PRIVATE void sqlcipher3SchemaClear(void *p){
85076   Hash temp1;
85077   Hash temp2;
85078   HashElem *pElem;
85079   Schema *pSchema = (Schema *)p;
85080
85081   temp1 = pSchema->tblHash;
85082   temp2 = pSchema->trigHash;
85083   sqlcipher3HashInit(&pSchema->trigHash);
85084   sqlcipher3HashClear(&pSchema->idxHash);
85085   for(pElem=sqlcipherHashFirst(&temp2); pElem; pElem=sqlcipherHashNext(pElem)){
85086     sqlcipher3DeleteTrigger(0, (Trigger*)sqlcipherHashData(pElem));
85087   }
85088   sqlcipher3HashClear(&temp2);
85089   sqlcipher3HashInit(&pSchema->tblHash);
85090   for(pElem=sqlcipherHashFirst(&temp1); pElem; pElem=sqlcipherHashNext(pElem)){
85091     Table *pTab = sqlcipherHashData(pElem);
85092     sqlcipher3DeleteTable(0, pTab);
85093   }
85094   sqlcipher3HashClear(&temp1);
85095   sqlcipher3HashClear(&pSchema->fkeyHash);
85096   pSchema->pSeqTab = 0;
85097   if( pSchema->flags & DB_SchemaLoaded ){
85098     pSchema->iGeneration++;
85099     pSchema->flags &= ~DB_SchemaLoaded;
85100   }
85101 }
85102
85103 /*
85104 ** Find and return the schema associated with a BTree.  Create
85105 ** a new one if necessary.
85106 */
85107 SQLCIPHER_PRIVATE Schema *sqlcipher3SchemaGet(sqlcipher3 *db, Btree *pBt){
85108   Schema * p;
85109   if( pBt ){
85110     p = (Schema *)sqlcipher3BtreeSchema(pBt, sizeof(Schema), sqlcipher3SchemaClear);
85111   }else{
85112     p = (Schema *)sqlcipher3DbMallocZero(0, sizeof(Schema));
85113   }
85114   if( !p ){
85115     db->mallocFailed = 1;
85116   }else if ( 0==p->file_format ){
85117     sqlcipher3HashInit(&p->tblHash);
85118     sqlcipher3HashInit(&p->idxHash);
85119     sqlcipher3HashInit(&p->trigHash);
85120     sqlcipher3HashInit(&p->fkeyHash);
85121     p->enc = SQLCIPHER_UTF8;
85122   }
85123   return p;
85124 }
85125
85126 /************** End of callback.c ********************************************/
85127 /************** Begin file delete.c ******************************************/
85128 /*
85129 ** 2001 September 15
85130 **
85131 ** The author disclaims copyright to this source code.  In place of
85132 ** a legal notice, here is a blessing:
85133 **
85134 **    May you do good and not evil.
85135 **    May you find forgiveness for yourself and forgive others.
85136 **    May you share freely, never taking more than you give.
85137 **
85138 *************************************************************************
85139 ** This file contains C code routines that are called by the parser
85140 ** in order to generate code for DELETE FROM statements.
85141 */
85142
85143 /*
85144 ** While a SrcList can in general represent multiple tables and subqueries
85145 ** (as in the FROM clause of a SELECT statement) in this case it contains
85146 ** the name of a single table, as one might find in an INSERT, DELETE,
85147 ** or UPDATE statement.  Look up that table in the symbol table and
85148 ** return a pointer.  Set an error message and return NULL if the table 
85149 ** name is not found or if any other error occurs.
85150 **
85151 ** The following fields are initialized appropriate in pSrc:
85152 **
85153 **    pSrc->a[0].pTab       Pointer to the Table object
85154 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
85155 **
85156 */
85157 SQLCIPHER_PRIVATE Table *sqlcipher3SrcListLookup(Parse *pParse, SrcList *pSrc){
85158   struct SrcList_item *pItem = pSrc->a;
85159   Table *pTab;
85160   assert( pItem && pSrc->nSrc==1 );
85161   pTab = sqlcipher3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
85162   sqlcipher3DeleteTable(pParse->db, pItem->pTab);
85163   pItem->pTab = pTab;
85164   if( pTab ){
85165     pTab->nRef++;
85166   }
85167   if( sqlcipher3IndexedByLookup(pParse, pItem) ){
85168     pTab = 0;
85169   }
85170   return pTab;
85171 }
85172
85173 /*
85174 ** Check to make sure the given table is writable.  If it is not
85175 ** writable, generate an error message and return 1.  If it is
85176 ** writable return 0;
85177 */
85178 SQLCIPHER_PRIVATE int sqlcipher3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
85179   /* A table is not writable under the following circumstances:
85180   **
85181   **   1) It is a virtual table and no implementation of the xUpdate method
85182   **      has been provided, or
85183   **   2) It is a system table (i.e. sqlcipher_master), this call is not
85184   **      part of a nested parse and writable_schema pragma has not 
85185   **      been specified.
85186   **
85187   ** In either case leave an error message in pParse and return non-zero.
85188   */
85189   if( ( IsVirtual(pTab) 
85190      && sqlcipher3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
85191    || ( (pTab->tabFlags & TF_Readonly)!=0
85192      && (pParse->db->flags & SQLCIPHER_WriteSchema)==0
85193      && pParse->nested==0 )
85194   ){
85195     sqlcipher3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
85196     return 1;
85197   }
85198
85199 #ifndef SQLCIPHER_OMIT_VIEW
85200   if( !viewOk && pTab->pSelect ){
85201     sqlcipher3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
85202     return 1;
85203   }
85204 #endif
85205   return 0;
85206 }
85207
85208
85209 #if !defined(SQLCIPHER_OMIT_VIEW) && !defined(SQLCIPHER_OMIT_TRIGGER)
85210 /*
85211 ** Evaluate a view and store its result in an ephemeral table.  The
85212 ** pWhere argument is an optional WHERE clause that restricts the
85213 ** set of rows in the view that are to be added to the ephemeral table.
85214 */
85215 SQLCIPHER_PRIVATE void sqlcipher3MaterializeView(
85216   Parse *pParse,       /* Parsing context */
85217   Table *pView,        /* View definition */
85218   Expr *pWhere,        /* Optional WHERE clause to be added */
85219   int iCur             /* Cursor number for ephemerial table */
85220 ){
85221   SelectDest dest;
85222   Select *pDup;
85223   sqlcipher3 *db = pParse->db;
85224
85225   pDup = sqlcipher3SelectDup(db, pView->pSelect, 0);
85226   if( pWhere ){
85227     SrcList *pFrom;
85228     
85229     pWhere = sqlcipher3ExprDup(db, pWhere, 0);
85230     pFrom = sqlcipher3SrcListAppend(db, 0, 0, 0);
85231     if( pFrom ){
85232       assert( pFrom->nSrc==1 );
85233       pFrom->a[0].zAlias = sqlcipher3DbStrDup(db, pView->zName);
85234       pFrom->a[0].pSelect = pDup;
85235       assert( pFrom->a[0].pOn==0 );
85236       assert( pFrom->a[0].pUsing==0 );
85237     }else{
85238       sqlcipher3SelectDelete(db, pDup);
85239     }
85240     pDup = sqlcipher3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
85241   }
85242   sqlcipher3SelectDestInit(&dest, SRT_EphemTab, iCur);
85243   sqlcipher3Select(pParse, pDup, &dest);
85244   sqlcipher3SelectDelete(db, pDup);
85245 }
85246 #endif /* !defined(SQLCIPHER_OMIT_VIEW) && !defined(SQLCIPHER_OMIT_TRIGGER) */
85247
85248 #if defined(SQLCIPHER_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLCIPHER_OMIT_SUBQUERY)
85249 /*
85250 ** Generate an expression tree to implement the WHERE, ORDER BY,
85251 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
85252 **
85253 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
85254 **                            \__________________________/
85255 **                               pLimitWhere (pInClause)
85256 */
85257 SQLCIPHER_PRIVATE Expr *sqlcipher3LimitWhere(
85258   Parse *pParse,               /* The parser context */
85259   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
85260   Expr *pWhere,                /* The WHERE clause.  May be null */
85261   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
85262   Expr *pLimit,                /* The LIMIT clause.  May be null */
85263   Expr *pOffset,               /* The OFFSET clause.  May be null */
85264   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
85265 ){
85266   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
85267   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
85268   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
85269   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
85270   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
85271   Select *pSelect = NULL;      /* Complete SELECT tree */
85272
85273   /* Check that there isn't an ORDER BY without a LIMIT clause.
85274   */
85275   if( pOrderBy && (pLimit == 0) ) {
85276     sqlcipher3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
85277     pParse->parseError = 1;
85278     goto limit_where_cleanup_2;
85279   }
85280
85281   /* We only need to generate a select expression if there
85282   ** is a limit/offset term to enforce.
85283   */
85284   if( pLimit == 0 ) {
85285     /* if pLimit is null, pOffset will always be null as well. */
85286     assert( pOffset == 0 );
85287     return pWhere;
85288   }
85289
85290   /* Generate a select expression tree to enforce the limit/offset 
85291   ** term for the DELETE or UPDATE statement.  For example:
85292   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85293   ** becomes:
85294   **   DELETE FROM table_a WHERE rowid IN ( 
85295   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85296   **   );
85297   */
85298
85299   pSelectRowid = sqlcipher3PExpr(pParse, TK_ROW, 0, 0, 0);
85300   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
85301   pEList = sqlcipher3ExprListAppend(pParse, 0, pSelectRowid);
85302   if( pEList == 0 ) goto limit_where_cleanup_2;
85303
85304   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
85305   ** and the SELECT subtree. */
85306   pSelectSrc = sqlcipher3SrcListDup(pParse->db, pSrc, 0);
85307   if( pSelectSrc == 0 ) {
85308     sqlcipher3ExprListDelete(pParse->db, pEList);
85309     goto limit_where_cleanup_2;
85310   }
85311
85312   /* generate the SELECT expression tree. */
85313   pSelect = sqlcipher3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
85314                              pOrderBy,0,pLimit,pOffset);
85315   if( pSelect == 0 ) return 0;
85316
85317   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
85318   pWhereRowid = sqlcipher3PExpr(pParse, TK_ROW, 0, 0, 0);
85319   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
85320   pInClause = sqlcipher3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
85321   if( pInClause == 0 ) goto limit_where_cleanup_1;
85322
85323   pInClause->x.pSelect = pSelect;
85324   pInClause->flags |= EP_xIsSelect;
85325   sqlcipher3ExprSetHeight(pParse, pInClause);
85326   return pInClause;
85327
85328   /* something went wrong. clean up anything allocated. */
85329 limit_where_cleanup_1:
85330   sqlcipher3SelectDelete(pParse->db, pSelect);
85331   return 0;
85332
85333 limit_where_cleanup_2:
85334   sqlcipher3ExprDelete(pParse->db, pWhere);
85335   sqlcipher3ExprListDelete(pParse->db, pOrderBy);
85336   sqlcipher3ExprDelete(pParse->db, pLimit);
85337   sqlcipher3ExprDelete(pParse->db, pOffset);
85338   return 0;
85339 }
85340 #endif /* defined(SQLCIPHER_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLCIPHER_OMIT_SUBQUERY) */
85341
85342 /*
85343 ** Generate code for a DELETE FROM statement.
85344 **
85345 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
85346 **                 \________/       \________________/
85347 **                  pTabList              pWhere
85348 */
85349 SQLCIPHER_PRIVATE void sqlcipher3DeleteFrom(
85350   Parse *pParse,         /* The parser context */
85351   SrcList *pTabList,     /* The table from which we should delete things */
85352   Expr *pWhere           /* The WHERE clause.  May be null */
85353 ){
85354   Vdbe *v;               /* The virtual database engine */
85355   Table *pTab;           /* The table from which records will be deleted */
85356   const char *zDb;       /* Name of database holding pTab */
85357   int end, addr = 0;     /* A couple addresses of generated code */
85358   int i;                 /* Loop counter */
85359   WhereInfo *pWInfo;     /* Information about the WHERE clause */
85360   Index *pIdx;           /* For looping over indices of the table */
85361   int iCur;              /* VDBE Cursor number for pTab */
85362   sqlcipher3 *db;           /* Main database structure */
85363   AuthContext sContext;  /* Authorization context */
85364   NameContext sNC;       /* Name context to resolve expressions in */
85365   int iDb;               /* Database number */
85366   int memCnt = -1;       /* Memory cell used for change counting */
85367   int rcauth;            /* Value returned by authorization callback */
85368
85369 #ifndef SQLCIPHER_OMIT_TRIGGER
85370   int isView;                  /* True if attempting to delete from a view */
85371   Trigger *pTrigger;           /* List of table triggers, if required */
85372 #endif
85373
85374   memset(&sContext, 0, sizeof(sContext));
85375   db = pParse->db;
85376   if( pParse->nErr || db->mallocFailed ){
85377     goto delete_from_cleanup;
85378   }
85379   assert( pTabList->nSrc==1 );
85380
85381   /* Locate the table which we want to delete.  This table has to be
85382   ** put in an SrcList structure because some of the subroutines we
85383   ** will be calling are designed to work with multiple tables and expect
85384   ** an SrcList* parameter instead of just a Table* parameter.
85385   */
85386   pTab = sqlcipher3SrcListLookup(pParse, pTabList);
85387   if( pTab==0 )  goto delete_from_cleanup;
85388
85389   /* Figure out if we have any triggers and if the table being
85390   ** deleted from is a view
85391   */
85392 #ifndef SQLCIPHER_OMIT_TRIGGER
85393   pTrigger = sqlcipher3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85394   isView = pTab->pSelect!=0;
85395 #else
85396 # define pTrigger 0
85397 # define isView 0
85398 #endif
85399 #ifdef SQLCIPHER_OMIT_VIEW
85400 # undef isView
85401 # define isView 0
85402 #endif
85403
85404   /* If pTab is really a view, make sure it has been initialized.
85405   */
85406   if( sqlcipher3ViewGetColumnNames(pParse, pTab) ){
85407     goto delete_from_cleanup;
85408   }
85409
85410   if( sqlcipher3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
85411     goto delete_from_cleanup;
85412   }
85413   iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
85414   assert( iDb<db->nDb );
85415   zDb = db->aDb[iDb].zName;
85416   rcauth = sqlcipher3AuthCheck(pParse, SQLCIPHER_DELETE, pTab->zName, 0, zDb);
85417   assert( rcauth==SQLCIPHER_OK || rcauth==SQLCIPHER_DENY || rcauth==SQLCIPHER_IGNORE );
85418   if( rcauth==SQLCIPHER_DENY ){
85419     goto delete_from_cleanup;
85420   }
85421   assert(!isView || pTrigger);
85422
85423   /* Assign  cursor number to the table and all its indices.
85424   */
85425   assert( pTabList->nSrc==1 );
85426   iCur = pTabList->a[0].iCursor = pParse->nTab++;
85427   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85428     pParse->nTab++;
85429   }
85430
85431   /* Start the view context
85432   */
85433   if( isView ){
85434     sqlcipher3AuthContextPush(pParse, &sContext, pTab->zName);
85435   }
85436
85437   /* Begin generating code.
85438   */
85439   v = sqlcipher3GetVdbe(pParse);
85440   if( v==0 ){
85441     goto delete_from_cleanup;
85442   }
85443   if( pParse->nested==0 ) sqlcipher3VdbeCountChanges(v);
85444   sqlcipher3BeginWriteOperation(pParse, 1, iDb);
85445
85446   /* If we are trying to delete from a view, realize that view into
85447   ** a ephemeral table.
85448   */
85449 #if !defined(SQLCIPHER_OMIT_VIEW) && !defined(SQLCIPHER_OMIT_TRIGGER)
85450   if( isView ){
85451     sqlcipher3MaterializeView(pParse, pTab, pWhere, iCur);
85452   }
85453 #endif
85454
85455   /* Resolve the column names in the WHERE clause.
85456   */
85457   memset(&sNC, 0, sizeof(sNC));
85458   sNC.pParse = pParse;
85459   sNC.pSrcList = pTabList;
85460   if( sqlcipher3ResolveExprNames(&sNC, pWhere) ){
85461     goto delete_from_cleanup;
85462   }
85463
85464   /* Initialize the counter of the number of rows deleted, if
85465   ** we are counting rows.
85466   */
85467   if( db->flags & SQLCIPHER_CountRows ){
85468     memCnt = ++pParse->nMem;
85469     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, memCnt);
85470   }
85471
85472 #ifndef SQLCIPHER_OMIT_TRUNCATE_OPTIMIZATION
85473   /* Special case: A DELETE without a WHERE clause deletes everything.
85474   ** It is easier just to erase the whole table. Prior to version 3.6.5,
85475   ** this optimization caused the row change count (the value returned by 
85476   ** API function sqlcipher3_count_changes) to be set incorrectly.  */
85477   if( rcauth==SQLCIPHER_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
85478    && 0==sqlcipher3FkRequired(pParse, pTab, 0, 0)
85479   ){
85480     assert( !isView );
85481     sqlcipher3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
85482                       pTab->zName, P4_STATIC);
85483     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85484       assert( pIdx->pSchema==pTab->pSchema );
85485       sqlcipher3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
85486     }
85487   }else
85488 #endif /* SQLCIPHER_OMIT_TRUNCATE_OPTIMIZATION */
85489   /* The usual case: There is a WHERE clause so we have to scan through
85490   ** the table and pick which records to delete.
85491   */
85492   {
85493     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
85494     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
85495     int regRowid;                   /* Actual register containing rowids */
85496
85497     /* Collect rowids of every row to be deleted.
85498     */
85499     sqlcipher3VdbeAddOp2(v, OP_Null, 0, iRowSet);
85500     pWInfo = sqlcipher3WhereBegin(
85501         pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK
85502     );
85503     if( pWInfo==0 ) goto delete_from_cleanup;
85504     regRowid = sqlcipher3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
85505     sqlcipher3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
85506     if( db->flags & SQLCIPHER_CountRows ){
85507       sqlcipher3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
85508     }
85509     sqlcipher3WhereEnd(pWInfo);
85510
85511     /* Delete every item whose key was written to the list during the
85512     ** database scan.  We have to delete items after the scan is complete
85513     ** because deleting an item can change the scan order.  */
85514     end = sqlcipher3VdbeMakeLabel(v);
85515
85516     /* Unless this is a view, open cursors for the table we are 
85517     ** deleting from and all its indices. If this is a view, then the
85518     ** only effect this statement has is to fire the INSTEAD OF 
85519     ** triggers.  */
85520     if( !isView ){
85521       sqlcipher3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
85522     }
85523
85524     addr = sqlcipher3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
85525
85526     /* Delete the row */
85527 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
85528     if( IsVirtual(pTab) ){
85529       const char *pVTab = (const char *)sqlcipher3GetVTable(db, pTab);
85530       sqlcipher3VtabMakeWritable(pParse, pTab);
85531       sqlcipher3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
85532       sqlcipher3VdbeChangeP5(v, OE_Abort);
85533       sqlcipher3MayAbort(pParse);
85534     }else
85535 #endif
85536     {
85537       int count = (pParse->nested==0);    /* True to count changes */
85538       sqlcipher3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
85539     }
85540
85541     /* End of the delete loop */
85542     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addr);
85543     sqlcipher3VdbeResolveLabel(v, end);
85544
85545     /* Close the cursors open on the table and its indexes. */
85546     if( !isView && !IsVirtual(pTab) ){
85547       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
85548         sqlcipher3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
85549       }
85550       sqlcipher3VdbeAddOp1(v, OP_Close, iCur);
85551     }
85552   }
85553
85554   /* Update the sqlcipher_sequence table by storing the content of the
85555   ** maximum rowid counter values recorded while inserting into
85556   ** autoincrement tables.
85557   */
85558   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85559     sqlcipher3AutoincrementEnd(pParse);
85560   }
85561
85562   /* Return the number of rows that were deleted. If this routine is 
85563   ** generating code because of a call to sqlcipher3NestedParse(), do not
85564   ** invoke the callback function.
85565   */
85566   if( (db->flags&SQLCIPHER_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
85567     sqlcipher3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
85568     sqlcipher3VdbeSetNumCols(v, 1);
85569     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLCIPHER_STATIC);
85570   }
85571
85572 delete_from_cleanup:
85573   sqlcipher3AuthContextPop(&sContext);
85574   sqlcipher3SrcListDelete(db, pTabList);
85575   sqlcipher3ExprDelete(db, pWhere);
85576   return;
85577 }
85578 /* Make sure "isView" and other macros defined above are undefined. Otherwise
85579 ** thely may interfere with compilation of other functions in this file
85580 ** (or in another file, if this file becomes part of the amalgamation).  */
85581 #ifdef isView
85582  #undef isView
85583 #endif
85584 #ifdef pTrigger
85585  #undef pTrigger
85586 #endif
85587
85588 /*
85589 ** This routine generates VDBE code that causes a single row of a
85590 ** single table to be deleted.
85591 **
85592 ** The VDBE must be in a particular state when this routine is called.
85593 ** These are the requirements:
85594 **
85595 **   1.  A read/write cursor pointing to pTab, the table containing the row
85596 **       to be deleted, must be opened as cursor number $iCur.
85597 **
85598 **   2.  Read/write cursors for all indices of pTab must be open as
85599 **       cursor number base+i for the i-th index.
85600 **
85601 **   3.  The record number of the row to be deleted must be stored in
85602 **       memory cell iRowid.
85603 **
85604 ** This routine generates code to remove both the table record and all 
85605 ** index entries that point to that record.
85606 */
85607 SQLCIPHER_PRIVATE void sqlcipher3GenerateRowDelete(
85608   Parse *pParse,     /* Parsing context */
85609   Table *pTab,       /* Table containing the row to be deleted */
85610   int iCur,          /* Cursor number for the table */
85611   int iRowid,        /* Memory cell that contains the rowid to delete */
85612   int count,         /* If non-zero, increment the row change counter */
85613   Trigger *pTrigger, /* List of triggers to (potentially) fire */
85614   int onconf         /* Default ON CONFLICT policy for triggers */
85615 ){
85616   Vdbe *v = pParse->pVdbe;        /* Vdbe */
85617   int iOld = 0;                   /* First register in OLD.* array */
85618   int iLabel;                     /* Label resolved to end of generated code */
85619
85620   /* Vdbe is guaranteed to have been allocated by this stage. */
85621   assert( v );
85622
85623   /* Seek cursor iCur to the row to delete. If this row no longer exists 
85624   ** (this can happen if a trigger program has already deleted it), do
85625   ** not attempt to delete it or fire any DELETE triggers.  */
85626   iLabel = sqlcipher3VdbeMakeLabel(v);
85627   sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
85628  
85629   /* If there are any triggers to fire, allocate a range of registers to
85630   ** use for the old.* references in the triggers.  */
85631   if( sqlcipher3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
85632     u32 mask;                     /* Mask of OLD.* columns in use */
85633     int iCol;                     /* Iterator used while populating OLD.* */
85634
85635     /* TODO: Could use temporary registers here. Also could attempt to
85636     ** avoid copying the contents of the rowid register.  */
85637     mask = sqlcipher3TriggerColmask(
85638         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
85639     );
85640     mask |= sqlcipher3FkOldmask(pParse, pTab);
85641     iOld = pParse->nMem+1;
85642     pParse->nMem += (1 + pTab->nCol);
85643
85644     /* Populate the OLD.* pseudo-table register array. These values will be 
85645     ** used by any BEFORE and AFTER triggers that exist.  */
85646     sqlcipher3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
85647     for(iCol=0; iCol<pTab->nCol; iCol++){
85648       if( mask==0xffffffff || mask&(1<<iCol) ){
85649         sqlcipher3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
85650       }
85651     }
85652
85653     /* Invoke BEFORE DELETE trigger programs. */
85654     sqlcipher3CodeRowTrigger(pParse, pTrigger, 
85655         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
85656     );
85657
85658     /* Seek the cursor to the row to be deleted again. It may be that
85659     ** the BEFORE triggers coded above have already removed the row
85660     ** being deleted. Do not attempt to delete the row a second time, and 
85661     ** do not fire AFTER triggers.  */
85662     sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
85663
85664     /* Do FK processing. This call checks that any FK constraints that
85665     ** refer to this table (i.e. constraints attached to other tables) 
85666     ** are not violated by deleting this row.  */
85667     sqlcipher3FkCheck(pParse, pTab, iOld, 0);
85668   }
85669
85670   /* Delete the index and table entries. Skip this step if pTab is really
85671   ** a view (in which case the only effect of the DELETE statement is to
85672   ** fire the INSTEAD OF triggers).  */ 
85673   if( pTab->pSelect==0 ){
85674     sqlcipher3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
85675     sqlcipher3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
85676     if( count ){
85677       sqlcipher3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
85678     }
85679   }
85680
85681   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
85682   ** handle rows (possibly in other tables) that refer via a foreign key
85683   ** to the row just deleted. */ 
85684   sqlcipher3FkActions(pParse, pTab, 0, iOld);
85685
85686   /* Invoke AFTER DELETE trigger programs. */
85687   sqlcipher3CodeRowTrigger(pParse, pTrigger, 
85688       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
85689   );
85690
85691   /* Jump here if the row had already been deleted before any BEFORE
85692   ** trigger programs were invoked. Or if a trigger program throws a 
85693   ** RAISE(IGNORE) exception.  */
85694   sqlcipher3VdbeResolveLabel(v, iLabel);
85695 }
85696
85697 /*
85698 ** This routine generates VDBE code that causes the deletion of all
85699 ** index entries associated with a single row of a single table.
85700 **
85701 ** The VDBE must be in a particular state when this routine is called.
85702 ** These are the requirements:
85703 **
85704 **   1.  A read/write cursor pointing to pTab, the table containing the row
85705 **       to be deleted, must be opened as cursor number "iCur".
85706 **
85707 **   2.  Read/write cursors for all indices of pTab must be open as
85708 **       cursor number iCur+i for the i-th index.
85709 **
85710 **   3.  The "iCur" cursor must be pointing to the row that is to be
85711 **       deleted.
85712 */
85713 SQLCIPHER_PRIVATE void sqlcipher3GenerateRowIndexDelete(
85714   Parse *pParse,     /* Parsing and code generating context */
85715   Table *pTab,       /* Table containing the row to be deleted */
85716   int iCur,          /* Cursor number for the table */
85717   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
85718 ){
85719   int i;
85720   Index *pIdx;
85721   int r1;
85722
85723   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
85724     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
85725     r1 = sqlcipher3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
85726     sqlcipher3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
85727   }
85728 }
85729
85730 /*
85731 ** Generate code that will assemble an index key and put it in register
85732 ** regOut.  The key with be for index pIdx which is an index on pTab.
85733 ** iCur is the index of a cursor open on the pTab table and pointing to
85734 ** the entry that needs indexing.
85735 **
85736 ** Return a register number which is the first in a block of
85737 ** registers that holds the elements of the index key.  The
85738 ** block of registers has already been deallocated by the time
85739 ** this routine returns.
85740 */
85741 SQLCIPHER_PRIVATE int sqlcipher3GenerateIndexKey(
85742   Parse *pParse,     /* Parsing context */
85743   Index *pIdx,       /* The index for which to generate a key */
85744   int iCur,          /* Cursor number for the pIdx->pTable table */
85745   int regOut,        /* Write the new index key to this register */
85746   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
85747 ){
85748   Vdbe *v = pParse->pVdbe;
85749   int j;
85750   Table *pTab = pIdx->pTable;
85751   int regBase;
85752   int nCol;
85753
85754   nCol = pIdx->nColumn;
85755   regBase = sqlcipher3GetTempRange(pParse, nCol+1);
85756   sqlcipher3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
85757   for(j=0; j<nCol; j++){
85758     int idx = pIdx->aiColumn[j];
85759     if( idx==pTab->iPKey ){
85760       sqlcipher3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
85761     }else{
85762       sqlcipher3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
85763       sqlcipher3ColumnDefault(v, pTab, idx, -1);
85764     }
85765   }
85766   if( doMakeRec ){
85767     const char *zAff;
85768     if( pTab->pSelect || (pParse->db->flags & SQLCIPHER_IdxRealAsInt)!=0 ){
85769       zAff = 0;
85770     }else{
85771       zAff = sqlcipher3IndexAffinityStr(v, pIdx);
85772     }
85773     sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
85774     sqlcipher3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
85775   }
85776   sqlcipher3ReleaseTempRange(pParse, regBase, nCol+1);
85777   return regBase;
85778 }
85779
85780 /************** End of delete.c **********************************************/
85781 /************** Begin file func.c ********************************************/
85782 /*
85783 ** 2002 February 23
85784 **
85785 ** The author disclaims copyright to this source code.  In place of
85786 ** a legal notice, here is a blessing:
85787 **
85788 **    May you do good and not evil.
85789 **    May you find forgiveness for yourself and forgive others.
85790 **    May you share freely, never taking more than you give.
85791 **
85792 *************************************************************************
85793 ** This file contains the C functions that implement various SQL
85794 ** functions of SQLite.  
85795 **
85796 ** There is only one exported symbol in this file - the function
85797 ** sqlcipherRegisterBuildinFunctions() found at the bottom of the file.
85798 ** All other code has file scope.
85799 */
85800 /* #include <stdlib.h> */
85801 /* #include <assert.h> */
85802
85803 /*
85804 ** Return the collating function associated with a function.
85805 */
85806 static CollSeq *sqlcipher3GetFuncCollSeq(sqlcipher3_context *context){
85807   return context->pColl;
85808 }
85809
85810 /*
85811 ** Implementation of the non-aggregate min() and max() functions
85812 */
85813 static void minmaxFunc(
85814   sqlcipher3_context *context,
85815   int argc,
85816   sqlcipher3_value **argv
85817 ){
85818   int i;
85819   int mask;    /* 0 for min() or 0xffffffff for max() */
85820   int iBest;
85821   CollSeq *pColl;
85822
85823   assert( argc>1 );
85824   mask = sqlcipher3_user_data(context)==0 ? 0 : -1;
85825   pColl = sqlcipher3GetFuncCollSeq(context);
85826   assert( pColl );
85827   assert( mask==-1 || mask==0 );
85828   iBest = 0;
85829   if( sqlcipher3_value_type(argv[0])==SQLCIPHER_NULL ) return;
85830   for(i=1; i<argc; i++){
85831     if( sqlcipher3_value_type(argv[i])==SQLCIPHER_NULL ) return;
85832     if( (sqlcipher3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
85833       testcase( mask==0 );
85834       iBest = i;
85835     }
85836   }
85837   sqlcipher3_result_value(context, argv[iBest]);
85838 }
85839
85840 /*
85841 ** Return the type of the argument.
85842 */
85843 static void typeofFunc(
85844   sqlcipher3_context *context,
85845   int NotUsed,
85846   sqlcipher3_value **argv
85847 ){
85848   const char *z = 0;
85849   UNUSED_PARAMETER(NotUsed);
85850   switch( sqlcipher3_value_type(argv[0]) ){
85851     case SQLCIPHER_INTEGER: z = "integer"; break;
85852     case SQLCIPHER_TEXT:    z = "text";    break;
85853     case SQLCIPHER_FLOAT:   z = "real";    break;
85854     case SQLCIPHER_BLOB:    z = "blob";    break;
85855     default:             z = "null";    break;
85856   }
85857   sqlcipher3_result_text(context, z, -1, SQLCIPHER_STATIC);
85858 }
85859
85860
85861 /*
85862 ** Implementation of the length() function
85863 */
85864 static void lengthFunc(
85865   sqlcipher3_context *context,
85866   int argc,
85867   sqlcipher3_value **argv
85868 ){
85869   int len;
85870
85871   assert( argc==1 );
85872   UNUSED_PARAMETER(argc);
85873   switch( sqlcipher3_value_type(argv[0]) ){
85874     case SQLCIPHER_BLOB:
85875     case SQLCIPHER_INTEGER:
85876     case SQLCIPHER_FLOAT: {
85877       sqlcipher3_result_int(context, sqlcipher3_value_bytes(argv[0]));
85878       break;
85879     }
85880     case SQLCIPHER_TEXT: {
85881       const unsigned char *z = sqlcipher3_value_text(argv[0]);
85882       if( z==0 ) return;
85883       len = 0;
85884       while( *z ){
85885         len++;
85886         SQLCIPHER_SKIP_UTF8(z);
85887       }
85888       sqlcipher3_result_int(context, len);
85889       break;
85890     }
85891     default: {
85892       sqlcipher3_result_null(context);
85893       break;
85894     }
85895   }
85896 }
85897
85898 /*
85899 ** Implementation of the abs() function.
85900 **
85901 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
85902 ** the numeric argument X. 
85903 */
85904 static void absFunc(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
85905   assert( argc==1 );
85906   UNUSED_PARAMETER(argc);
85907   switch( sqlcipher3_value_type(argv[0]) ){
85908     case SQLCIPHER_INTEGER: {
85909       i64 iVal = sqlcipher3_value_int64(argv[0]);
85910       if( iVal<0 ){
85911         if( (iVal<<1)==0 ){
85912           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
85913           ** abs(X) throws an integer overflow error since there is no
85914           ** equivalent positive 64-bit two complement value. */
85915           sqlcipher3_result_error(context, "integer overflow", -1);
85916           return;
85917         }
85918         iVal = -iVal;
85919       } 
85920       sqlcipher3_result_int64(context, iVal);
85921       break;
85922     }
85923     case SQLCIPHER_NULL: {
85924       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
85925       sqlcipher3_result_null(context);
85926       break;
85927     }
85928     default: {
85929       /* Because sqlcipher3_value_double() returns 0.0 if the argument is not
85930       ** something that can be converted into a number, we have:
85931       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
85932       ** cannot be converted to a numeric value. 
85933       */
85934       double rVal = sqlcipher3_value_double(argv[0]);
85935       if( rVal<0 ) rVal = -rVal;
85936       sqlcipher3_result_double(context, rVal);
85937       break;
85938     }
85939   }
85940 }
85941
85942 /*
85943 ** Implementation of the substr() function.
85944 **
85945 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
85946 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
85947 ** of x.  If x is text, then we actually count UTF-8 characters.
85948 ** If x is a blob, then we count bytes.
85949 **
85950 ** If p1 is negative, then we begin abs(p1) from the end of x[].
85951 **
85952 ** If p2 is negative, return the p2 characters preceeding p1.
85953 */
85954 static void substrFunc(
85955   sqlcipher3_context *context,
85956   int argc,
85957   sqlcipher3_value **argv
85958 ){
85959   const unsigned char *z;
85960   const unsigned char *z2;
85961   int len;
85962   int p0type;
85963   i64 p1, p2;
85964   int negP2 = 0;
85965
85966   assert( argc==3 || argc==2 );
85967   if( sqlcipher3_value_type(argv[1])==SQLCIPHER_NULL
85968    || (argc==3 && sqlcipher3_value_type(argv[2])==SQLCIPHER_NULL)
85969   ){
85970     return;
85971   }
85972   p0type = sqlcipher3_value_type(argv[0]);
85973   p1 = sqlcipher3_value_int(argv[1]);
85974   if( p0type==SQLCIPHER_BLOB ){
85975     len = sqlcipher3_value_bytes(argv[0]);
85976     z = sqlcipher3_value_blob(argv[0]);
85977     if( z==0 ) return;
85978     assert( len==sqlcipher3_value_bytes(argv[0]) );
85979   }else{
85980     z = sqlcipher3_value_text(argv[0]);
85981     if( z==0 ) return;
85982     len = 0;
85983     if( p1<0 ){
85984       for(z2=z; *z2; len++){
85985         SQLCIPHER_SKIP_UTF8(z2);
85986       }
85987     }
85988   }
85989   if( argc==3 ){
85990     p2 = sqlcipher3_value_int(argv[2]);
85991     if( p2<0 ){
85992       p2 = -p2;
85993       negP2 = 1;
85994     }
85995   }else{
85996     p2 = sqlcipher3_context_db_handle(context)->aLimit[SQLCIPHER_LIMIT_LENGTH];
85997   }
85998   if( p1<0 ){
85999     p1 += len;
86000     if( p1<0 ){
86001       p2 += p1;
86002       if( p2<0 ) p2 = 0;
86003       p1 = 0;
86004     }
86005   }else if( p1>0 ){
86006     p1--;
86007   }else if( p2>0 ){
86008     p2--;
86009   }
86010   if( negP2 ){
86011     p1 -= p2;
86012     if( p1<0 ){
86013       p2 += p1;
86014       p1 = 0;
86015     }
86016   }
86017   assert( p1>=0 && p2>=0 );
86018   if( p0type!=SQLCIPHER_BLOB ){
86019     while( *z && p1 ){
86020       SQLCIPHER_SKIP_UTF8(z);
86021       p1--;
86022     }
86023     for(z2=z; *z2 && p2; p2--){
86024       SQLCIPHER_SKIP_UTF8(z2);
86025     }
86026     sqlcipher3_result_text(context, (char*)z, (int)(z2-z), SQLCIPHER_TRANSIENT);
86027   }else{
86028     if( p1+p2>len ){
86029       p2 = len-p1;
86030       if( p2<0 ) p2 = 0;
86031     }
86032     sqlcipher3_result_blob(context, (char*)&z[p1], (int)p2, SQLCIPHER_TRANSIENT);
86033   }
86034 }
86035
86036 /*
86037 ** Implementation of the round() function
86038 */
86039 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
86040 static void roundFunc(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
86041   int n = 0;
86042   double r;
86043   char *zBuf;
86044   assert( argc==1 || argc==2 );
86045   if( argc==2 ){
86046     if( SQLCIPHER_NULL==sqlcipher3_value_type(argv[1]) ) return;
86047     n = sqlcipher3_value_int(argv[1]);
86048     if( n>30 ) n = 30;
86049     if( n<0 ) n = 0;
86050   }
86051   if( sqlcipher3_value_type(argv[0])==SQLCIPHER_NULL ) return;
86052   r = sqlcipher3_value_double(argv[0]);
86053   /* If Y==0 and X will fit in a 64-bit int,
86054   ** handle the rounding directly,
86055   ** otherwise use printf.
86056   */
86057   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
86058     r = (double)((sqlcipher_int64)(r+0.5));
86059   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
86060     r = -(double)((sqlcipher_int64)((-r)+0.5));
86061   }else{
86062     zBuf = sqlcipher3_mprintf("%.*f",n,r);
86063     if( zBuf==0 ){
86064       sqlcipher3_result_error_nomem(context);
86065       return;
86066     }
86067     sqlcipher3AtoF(zBuf, &r, sqlcipher3Strlen30(zBuf), SQLCIPHER_UTF8);
86068     sqlcipher3_free(zBuf);
86069   }
86070   sqlcipher3_result_double(context, r);
86071 }
86072 #endif
86073
86074 /*
86075 ** Allocate nByte bytes of space using sqlcipher3_malloc(). If the
86076 ** allocation fails, call sqlcipher3_result_error_nomem() to notify
86077 ** the database handle that malloc() has failed and return NULL.
86078 ** If nByte is larger than the maximum string or blob length, then
86079 ** raise an SQLCIPHER_TOOBIG exception and return NULL.
86080 */
86081 static void *contextMalloc(sqlcipher3_context *context, i64 nByte){
86082   char *z;
86083   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86084   assert( nByte>0 );
86085   testcase( nByte==db->aLimit[SQLCIPHER_LIMIT_LENGTH] );
86086   testcase( nByte==db->aLimit[SQLCIPHER_LIMIT_LENGTH]+1 );
86087   if( nByte>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
86088     sqlcipher3_result_error_toobig(context);
86089     z = 0;
86090   }else{
86091     z = sqlcipher3Malloc((int)nByte);
86092     if( !z ){
86093       sqlcipher3_result_error_nomem(context);
86094     }
86095   }
86096   return z;
86097 }
86098
86099 /*
86100 ** Implementation of the upper() and lower() SQL functions.
86101 */
86102 static void upperFunc(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
86103   char *z1;
86104   const char *z2;
86105   int i, n;
86106   UNUSED_PARAMETER(argc);
86107   z2 = (char*)sqlcipher3_value_text(argv[0]);
86108   n = sqlcipher3_value_bytes(argv[0]);
86109   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86110   assert( z2==(char*)sqlcipher3_value_text(argv[0]) );
86111   if( z2 ){
86112     z1 = contextMalloc(context, ((i64)n)+1);
86113     if( z1 ){
86114       for(i=0; i<n; i++){
86115         z1[i] = (char)sqlcipher3Toupper(z2[i]);
86116       }
86117       sqlcipher3_result_text(context, z1, n, sqlcipher3_free);
86118     }
86119   }
86120 }
86121 static void lowerFunc(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
86122   char *z1;
86123   const char *z2;
86124   int i, n;
86125   UNUSED_PARAMETER(argc);
86126   z2 = (char*)sqlcipher3_value_text(argv[0]);
86127   n = sqlcipher3_value_bytes(argv[0]);
86128   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86129   assert( z2==(char*)sqlcipher3_value_text(argv[0]) );
86130   if( z2 ){
86131     z1 = contextMalloc(context, ((i64)n)+1);
86132     if( z1 ){
86133       for(i=0; i<n; i++){
86134         z1[i] = sqlcipher3Tolower(z2[i]);
86135       }
86136       sqlcipher3_result_text(context, z1, n, sqlcipher3_free);
86137     }
86138   }
86139 }
86140
86141
86142 #if 0  /* This function is never used. */
86143 /*
86144 ** The COALESCE() and IFNULL() functions used to be implemented as shown
86145 ** here.  But now they are implemented as VDBE code so that unused arguments
86146 ** do not have to be computed.  This legacy implementation is retained as
86147 ** comment.
86148 */
86149 /*
86150 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
86151 ** All three do the same thing.  They return the first non-NULL
86152 ** argument.
86153 */
86154 static void ifnullFunc(
86155   sqlcipher3_context *context,
86156   int argc,
86157   sqlcipher3_value **argv
86158 ){
86159   int i;
86160   for(i=0; i<argc; i++){
86161     if( SQLCIPHER_NULL!=sqlcipher3_value_type(argv[i]) ){
86162       sqlcipher3_result_value(context, argv[i]);
86163       break;
86164     }
86165   }
86166 }
86167 #endif /* NOT USED */
86168 #define ifnullFunc versionFunc   /* Substitute function - never called */
86169
86170 /*
86171 ** Implementation of random().  Return a random integer.  
86172 */
86173 static void randomFunc(
86174   sqlcipher3_context *context,
86175   int NotUsed,
86176   sqlcipher3_value **NotUsed2
86177 ){
86178   sqlcipher_int64 r;
86179   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86180   sqlcipher3_randomness(sizeof(r), &r);
86181   if( r<0 ){
86182     /* We need to prevent a random number of 0x8000000000000000 
86183     ** (or -9223372036854775808) since when you do abs() of that
86184     ** number of you get the same value back again.  To do this
86185     ** in a way that is testable, mask the sign bit off of negative
86186     ** values, resulting in a positive value.  Then take the 
86187     ** 2s complement of that positive value.  The end result can
86188     ** therefore be no less than -9223372036854775807.
86189     */
86190     r = -(r ^ (((sqlcipher3_int64)1)<<63));
86191   }
86192   sqlcipher3_result_int64(context, r);
86193 }
86194
86195 /*
86196 ** Implementation of randomblob(N).  Return a random blob
86197 ** that is N bytes long.
86198 */
86199 static void randomBlob(
86200   sqlcipher3_context *context,
86201   int argc,
86202   sqlcipher3_value **argv
86203 ){
86204   int n;
86205   unsigned char *p;
86206   assert( argc==1 );
86207   UNUSED_PARAMETER(argc);
86208   n = sqlcipher3_value_int(argv[0]);
86209   if( n<1 ){
86210     n = 1;
86211   }
86212   p = contextMalloc(context, n);
86213   if( p ){
86214     sqlcipher3_randomness(n, p);
86215     sqlcipher3_result_blob(context, (char*)p, n, sqlcipher3_free);
86216   }
86217 }
86218
86219 /*
86220 ** Implementation of the last_insert_rowid() SQL function.  The return
86221 ** value is the same as the sqlcipher3_last_insert_rowid() API function.
86222 */
86223 static void last_insert_rowid(
86224   sqlcipher3_context *context, 
86225   int NotUsed, 
86226   sqlcipher3_value **NotUsed2
86227 ){
86228   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86229   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86230   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
86231   ** wrapper around the sqlcipher3_last_insert_rowid() C/C++ interface
86232   ** function. */
86233   sqlcipher3_result_int64(context, sqlcipher3_last_insert_rowid(db));
86234 }
86235
86236 /*
86237 ** Implementation of the changes() SQL function.
86238 **
86239 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
86240 ** around the sqlcipher3_changes() C/C++ function and hence follows the same
86241 ** rules for counting changes.
86242 */
86243 static void changes(
86244   sqlcipher3_context *context,
86245   int NotUsed,
86246   sqlcipher3_value **NotUsed2
86247 ){
86248   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86249   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86250   sqlcipher3_result_int(context, sqlcipher3_changes(db));
86251 }
86252
86253 /*
86254 ** Implementation of the total_changes() SQL function.  The return value is
86255 ** the same as the sqlcipher3_total_changes() API function.
86256 */
86257 static void total_changes(
86258   sqlcipher3_context *context,
86259   int NotUsed,
86260   sqlcipher3_value **NotUsed2
86261 ){
86262   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86263   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86264   /* IMP: R-52756-41993 This function is a wrapper around the
86265   ** sqlcipher3_total_changes() C/C++ interface. */
86266   sqlcipher3_result_int(context, sqlcipher3_total_changes(db));
86267 }
86268
86269 /*
86270 ** A structure defining how to do GLOB-style comparisons.
86271 */
86272 struct compareInfo {
86273   u8 matchAll;
86274   u8 matchOne;
86275   u8 matchSet;
86276   u8 noCase;
86277 };
86278
86279 /*
86280 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
86281 ** character is exactly one byte in size.  Also, all characters are
86282 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
86283 ** whereas only characters less than 0x80 do in ASCII.
86284 */
86285 #if defined(SQLCIPHER_EBCDIC)
86286 # define sqlcipher3Utf8Read(A,C)  (*(A++))
86287 # define GlogUpperToLower(A)   A = sqlcipher3UpperToLower[A]
86288 #else
86289 # define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlcipher3UpperToLower[A]; }
86290 #endif
86291
86292 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
86293 /* The correct SQL-92 behavior is for the LIKE operator to ignore
86294 ** case.  Thus  'a' LIKE 'A' would be true. */
86295 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
86296 /* If SQLCIPHER_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
86297 ** is case sensitive causing 'a' LIKE 'A' to be false */
86298 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
86299
86300 /*
86301 ** Compare two UTF-8 strings for equality where the first string can
86302 ** potentially be a "glob" expression.  Return true (1) if they
86303 ** are the same and false (0) if they are different.
86304 **
86305 ** Globbing rules:
86306 **
86307 **      '*'       Matches any sequence of zero or more characters.
86308 **
86309 **      '?'       Matches exactly one character.
86310 **
86311 **     [...]      Matches one character from the enclosed list of
86312 **                characters.
86313 **
86314 **     [^...]     Matches one character not in the enclosed list.
86315 **
86316 ** With the [...] and [^...] matching, a ']' character can be included
86317 ** in the list by making it the first character after '[' or '^'.  A
86318 ** range of characters can be specified using '-'.  Example:
86319 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
86320 ** it the last character in the list.
86321 **
86322 ** This routine is usually quick, but can be N**2 in the worst case.
86323 **
86324 ** Hints: to match '*' or '?', put them in "[]".  Like this:
86325 **
86326 **         abc[*]xyz        Matches "abc*xyz" only
86327 */
86328 static int patternCompare(
86329   const u8 *zPattern,              /* The glob pattern */
86330   const u8 *zString,               /* The string to compare against the glob */
86331   const struct compareInfo *pInfo, /* Information about how to do the compare */
86332   u32 esc                          /* The escape character */
86333 ){
86334   u32 c, c2;
86335   int invert;
86336   int seen;
86337   u8 matchOne = pInfo->matchOne;
86338   u8 matchAll = pInfo->matchAll;
86339   u8 matchSet = pInfo->matchSet;
86340   u8 noCase = pInfo->noCase; 
86341   int prevEscape = 0;     /* True if the previous character was 'escape' */
86342
86343   while( (c = sqlcipher3Utf8Read(zPattern,&zPattern))!=0 ){
86344     if( !prevEscape && c==matchAll ){
86345       while( (c=sqlcipher3Utf8Read(zPattern,&zPattern)) == matchAll
86346                || c == matchOne ){
86347         if( c==matchOne && sqlcipher3Utf8Read(zString, &zString)==0 ){
86348           return 0;
86349         }
86350       }
86351       if( c==0 ){
86352         return 1;
86353       }else if( c==esc ){
86354         c = sqlcipher3Utf8Read(zPattern, &zPattern);
86355         if( c==0 ){
86356           return 0;
86357         }
86358       }else if( c==matchSet ){
86359         assert( esc==0 );         /* This is GLOB, not LIKE */
86360         assert( matchSet<0x80 );  /* '[' is a single-byte character */
86361         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
86362           SQLCIPHER_SKIP_UTF8(zString);
86363         }
86364         return *zString!=0;
86365       }
86366       while( (c2 = sqlcipher3Utf8Read(zString,&zString))!=0 ){
86367         if( noCase ){
86368           GlogUpperToLower(c2);
86369           GlogUpperToLower(c);
86370           while( c2 != 0 && c2 != c ){
86371             c2 = sqlcipher3Utf8Read(zString, &zString);
86372             GlogUpperToLower(c2);
86373           }
86374         }else{
86375           while( c2 != 0 && c2 != c ){
86376             c2 = sqlcipher3Utf8Read(zString, &zString);
86377           }
86378         }
86379         if( c2==0 ) return 0;
86380         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
86381       }
86382       return 0;
86383     }else if( !prevEscape && c==matchOne ){
86384       if( sqlcipher3Utf8Read(zString, &zString)==0 ){
86385         return 0;
86386       }
86387     }else if( c==matchSet ){
86388       u32 prior_c = 0;
86389       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
86390       seen = 0;
86391       invert = 0;
86392       c = sqlcipher3Utf8Read(zString, &zString);
86393       if( c==0 ) return 0;
86394       c2 = sqlcipher3Utf8Read(zPattern, &zPattern);
86395       if( c2=='^' ){
86396         invert = 1;
86397         c2 = sqlcipher3Utf8Read(zPattern, &zPattern);
86398       }
86399       if( c2==']' ){
86400         if( c==']' ) seen = 1;
86401         c2 = sqlcipher3Utf8Read(zPattern, &zPattern);
86402       }
86403       while( c2 && c2!=']' ){
86404         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
86405           c2 = sqlcipher3Utf8Read(zPattern, &zPattern);
86406           if( c>=prior_c && c<=c2 ) seen = 1;
86407           prior_c = 0;
86408         }else{
86409           if( c==c2 ){
86410             seen = 1;
86411           }
86412           prior_c = c2;
86413         }
86414         c2 = sqlcipher3Utf8Read(zPattern, &zPattern);
86415       }
86416       if( c2==0 || (seen ^ invert)==0 ){
86417         return 0;
86418       }
86419     }else if( esc==c && !prevEscape ){
86420       prevEscape = 1;
86421     }else{
86422       c2 = sqlcipher3Utf8Read(zString, &zString);
86423       if( noCase ){
86424         GlogUpperToLower(c);
86425         GlogUpperToLower(c2);
86426       }
86427       if( c!=c2 ){
86428         return 0;
86429       }
86430       prevEscape = 0;
86431     }
86432   }
86433   return *zString==0;
86434 }
86435
86436 /*
86437 ** Count the number of times that the LIKE operator (or GLOB which is
86438 ** just a variation of LIKE) gets called.  This is used for testing
86439 ** only.
86440 */
86441 #ifdef SQLCIPHER_TEST
86442 SQLCIPHER_API int sqlcipher3_like_count = 0;
86443 #endif
86444
86445
86446 /*
86447 ** Implementation of the like() SQL function.  This function implements
86448 ** the build-in LIKE operator.  The first argument to the function is the
86449 ** pattern and the second argument is the string.  So, the SQL statements:
86450 **
86451 **       A LIKE B
86452 **
86453 ** is implemented as like(B,A).
86454 **
86455 ** This same function (with a different compareInfo structure) computes
86456 ** the GLOB operator.
86457 */
86458 static void likeFunc(
86459   sqlcipher3_context *context, 
86460   int argc, 
86461   sqlcipher3_value **argv
86462 ){
86463   const unsigned char *zA, *zB;
86464   u32 escape = 0;
86465   int nPat;
86466   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86467
86468   zB = sqlcipher3_value_text(argv[0]);
86469   zA = sqlcipher3_value_text(argv[1]);
86470
86471   /* Limit the length of the LIKE or GLOB pattern to avoid problems
86472   ** of deep recursion and N*N behavior in patternCompare().
86473   */
86474   nPat = sqlcipher3_value_bytes(argv[0]);
86475   testcase( nPat==db->aLimit[SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH] );
86476   testcase( nPat==db->aLimit[SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH]+1 );
86477   if( nPat > db->aLimit[SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH] ){
86478     sqlcipher3_result_error(context, "LIKE or GLOB pattern too complex", -1);
86479     return;
86480   }
86481   assert( zB==sqlcipher3_value_text(argv[0]) );  /* Encoding did not change */
86482
86483   if( argc==3 ){
86484     /* The escape character string must consist of a single UTF-8 character.
86485     ** Otherwise, return an error.
86486     */
86487     const unsigned char *zEsc = sqlcipher3_value_text(argv[2]);
86488     if( zEsc==0 ) return;
86489     if( sqlcipher3Utf8CharLen((char*)zEsc, -1)!=1 ){
86490       sqlcipher3_result_error(context, 
86491           "ESCAPE expression must be a single character", -1);
86492       return;
86493     }
86494     escape = sqlcipher3Utf8Read(zEsc, &zEsc);
86495   }
86496   if( zA && zB ){
86497     struct compareInfo *pInfo = sqlcipher3_user_data(context);
86498 #ifdef SQLCIPHER_TEST
86499     sqlcipher3_like_count++;
86500 #endif
86501     
86502     sqlcipher3_result_int(context, patternCompare(zB, zA, pInfo, escape));
86503   }
86504 }
86505
86506 /*
86507 ** Implementation of the NULLIF(x,y) function.  The result is the first
86508 ** argument if the arguments are different.  The result is NULL if the
86509 ** arguments are equal to each other.
86510 */
86511 static void nullifFunc(
86512   sqlcipher3_context *context,
86513   int NotUsed,
86514   sqlcipher3_value **argv
86515 ){
86516   CollSeq *pColl = sqlcipher3GetFuncCollSeq(context);
86517   UNUSED_PARAMETER(NotUsed);
86518   if( sqlcipher3MemCompare(argv[0], argv[1], pColl)!=0 ){
86519     sqlcipher3_result_value(context, argv[0]);
86520   }
86521 }
86522
86523 /*
86524 ** Implementation of the sqlcipher_version() function.  The result is the version
86525 ** of the SQLite library that is running.
86526 */
86527 static void versionFunc(
86528   sqlcipher3_context *context,
86529   int NotUsed,
86530   sqlcipher3_value **NotUsed2
86531 ){
86532   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86533   /* IMP: R-48699-48617 This function is an SQL wrapper around the
86534   ** sqlcipher3_libversion() C-interface. */
86535   sqlcipher3_result_text(context, sqlcipher3_libversion(), -1, SQLCIPHER_STATIC);
86536 }
86537
86538 /*
86539 ** Implementation of the sqlcipher_source_id() function. The result is a string
86540 ** that identifies the particular version of the source code used to build
86541 ** SQLite.
86542 */
86543 static void sourceidFunc(
86544   sqlcipher3_context *context,
86545   int NotUsed,
86546   sqlcipher3_value **NotUsed2
86547 ){
86548   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86549   /* IMP: R-24470-31136 This function is an SQL wrapper around the
86550   ** sqlcipher3_sourceid() C interface. */
86551   sqlcipher3_result_text(context, sqlcipher3_sourceid(), -1, SQLCIPHER_STATIC);
86552 }
86553
86554 /*
86555 ** Implementation of the sqlcipher_log() function.  This is a wrapper around
86556 ** sqlcipher3_log().  The return value is NULL.  The function exists purely for
86557 ** its side-effects.
86558 */
86559 static void errlogFunc(
86560   sqlcipher3_context *context,
86561   int argc,
86562   sqlcipher3_value **argv
86563 ){
86564   UNUSED_PARAMETER(argc);
86565   UNUSED_PARAMETER(context);
86566   sqlcipher3_log(sqlcipher3_value_int(argv[0]), "%s", sqlcipher3_value_text(argv[1]));
86567 }
86568
86569 /*
86570 ** Implementation of the sqlcipher_compileoption_used() function.
86571 ** The result is an integer that identifies if the compiler option
86572 ** was used to build SQLite.
86573 */
86574 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
86575 static void compileoptionusedFunc(
86576   sqlcipher3_context *context,
86577   int argc,
86578   sqlcipher3_value **argv
86579 ){
86580   const char *zOptName;
86581   assert( argc==1 );
86582   UNUSED_PARAMETER(argc);
86583   /* IMP: R-39564-36305 The sqlcipher_compileoption_used() SQL
86584   ** function is a wrapper around the sqlcipher3_compileoption_used() C/C++
86585   ** function.
86586   */
86587   if( (zOptName = (const char*)sqlcipher3_value_text(argv[0]))!=0 ){
86588     sqlcipher3_result_int(context, sqlcipher3_compileoption_used(zOptName));
86589   }
86590 }
86591 #endif /* SQLCIPHER_OMIT_COMPILEOPTION_DIAGS */
86592
86593 /*
86594 ** Implementation of the sqlcipher_compileoption_get() function. 
86595 ** The result is a string that identifies the compiler options 
86596 ** used to build SQLite.
86597 */
86598 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
86599 static void compileoptiongetFunc(
86600   sqlcipher3_context *context,
86601   int argc,
86602   sqlcipher3_value **argv
86603 ){
86604   int n;
86605   assert( argc==1 );
86606   UNUSED_PARAMETER(argc);
86607   /* IMP: R-04922-24076 The sqlcipher_compileoption_get() SQL function
86608   ** is a wrapper around the sqlcipher3_compileoption_get() C/C++ function.
86609   */
86610   n = sqlcipher3_value_int(argv[0]);
86611   sqlcipher3_result_text(context, sqlcipher3_compileoption_get(n), -1, SQLCIPHER_STATIC);
86612 }
86613 #endif /* SQLCIPHER_OMIT_COMPILEOPTION_DIAGS */
86614
86615 /* Array for converting from half-bytes (nybbles) into ASCII hex
86616 ** digits. */
86617 static const char hexdigits[] = {
86618   '0', '1', '2', '3', '4', '5', '6', '7',
86619   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
86620 };
86621
86622 /*
86623 ** EXPERIMENTAL - This is not an official function.  The interface may
86624 ** change.  This function may disappear.  Do not write code that depends
86625 ** on this function.
86626 **
86627 ** Implementation of the QUOTE() function.  This function takes a single
86628 ** argument.  If the argument is numeric, the return value is the same as
86629 ** the argument.  If the argument is NULL, the return value is the string
86630 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
86631 ** single-quote escapes.
86632 */
86633 static void quoteFunc(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
86634   assert( argc==1 );
86635   UNUSED_PARAMETER(argc);
86636   switch( sqlcipher3_value_type(argv[0]) ){
86637     case SQLCIPHER_INTEGER:
86638     case SQLCIPHER_FLOAT: {
86639       sqlcipher3_result_value(context, argv[0]);
86640       break;
86641     }
86642     case SQLCIPHER_BLOB: {
86643       char *zText = 0;
86644       char const *zBlob = sqlcipher3_value_blob(argv[0]);
86645       int nBlob = sqlcipher3_value_bytes(argv[0]);
86646       assert( zBlob==sqlcipher3_value_blob(argv[0]) ); /* No encoding change */
86647       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
86648       if( zText ){
86649         int i;
86650         for(i=0; i<nBlob; i++){
86651           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
86652           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
86653         }
86654         zText[(nBlob*2)+2] = '\'';
86655         zText[(nBlob*2)+3] = '\0';
86656         zText[0] = 'X';
86657         zText[1] = '\'';
86658         sqlcipher3_result_text(context, zText, -1, SQLCIPHER_TRANSIENT);
86659         sqlcipher3_free(zText);
86660       }
86661       break;
86662     }
86663     case SQLCIPHER_TEXT: {
86664       int i,j;
86665       u64 n;
86666       const unsigned char *zArg = sqlcipher3_value_text(argv[0]);
86667       char *z;
86668
86669       if( zArg==0 ) return;
86670       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
86671       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
86672       if( z ){
86673         z[0] = '\'';
86674         for(i=0, j=1; zArg[i]; i++){
86675           z[j++] = zArg[i];
86676           if( zArg[i]=='\'' ){
86677             z[j++] = '\'';
86678           }
86679         }
86680         z[j++] = '\'';
86681         z[j] = 0;
86682         sqlcipher3_result_text(context, z, j, sqlcipher3_free);
86683       }
86684       break;
86685     }
86686     default: {
86687       assert( sqlcipher3_value_type(argv[0])==SQLCIPHER_NULL );
86688       sqlcipher3_result_text(context, "NULL", 4, SQLCIPHER_STATIC);
86689       break;
86690     }
86691   }
86692 }
86693
86694 /*
86695 ** The hex() function.  Interpret the argument as a blob.  Return
86696 ** a hexadecimal rendering as text.
86697 */
86698 static void hexFunc(
86699   sqlcipher3_context *context,
86700   int argc,
86701   sqlcipher3_value **argv
86702 ){
86703   int i, n;
86704   const unsigned char *pBlob;
86705   char *zHex, *z;
86706   assert( argc==1 );
86707   UNUSED_PARAMETER(argc);
86708   pBlob = sqlcipher3_value_blob(argv[0]);
86709   n = sqlcipher3_value_bytes(argv[0]);
86710   assert( pBlob==sqlcipher3_value_blob(argv[0]) );  /* No encoding change */
86711   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
86712   if( zHex ){
86713     for(i=0; i<n; i++, pBlob++){
86714       unsigned char c = *pBlob;
86715       *(z++) = hexdigits[(c>>4)&0xf];
86716       *(z++) = hexdigits[c&0xf];
86717     }
86718     *z = 0;
86719     sqlcipher3_result_text(context, zHex, n*2, sqlcipher3_free);
86720   }
86721 }
86722
86723 /*
86724 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
86725 */
86726 static void zeroblobFunc(
86727   sqlcipher3_context *context,
86728   int argc,
86729   sqlcipher3_value **argv
86730 ){
86731   i64 n;
86732   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86733   assert( argc==1 );
86734   UNUSED_PARAMETER(argc);
86735   n = sqlcipher3_value_int64(argv[0]);
86736   testcase( n==db->aLimit[SQLCIPHER_LIMIT_LENGTH] );
86737   testcase( n==db->aLimit[SQLCIPHER_LIMIT_LENGTH]+1 );
86738   if( n>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
86739     sqlcipher3_result_error_toobig(context);
86740   }else{
86741     sqlcipher3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
86742   }
86743 }
86744
86745 /*
86746 ** The replace() function.  Three arguments are all strings: call
86747 ** them A, B, and C. The result is also a string which is derived
86748 ** from A by replacing every occurance of B with C.  The match
86749 ** must be exact.  Collating sequences are not used.
86750 */
86751 static void replaceFunc(
86752   sqlcipher3_context *context,
86753   int argc,
86754   sqlcipher3_value **argv
86755 ){
86756   const unsigned char *zStr;        /* The input string A */
86757   const unsigned char *zPattern;    /* The pattern string B */
86758   const unsigned char *zRep;        /* The replacement string C */
86759   unsigned char *zOut;              /* The output */
86760   int nStr;                /* Size of zStr */
86761   int nPattern;            /* Size of zPattern */
86762   int nRep;                /* Size of zRep */
86763   i64 nOut;                /* Maximum size of zOut */
86764   int loopLimit;           /* Last zStr[] that might match zPattern[] */
86765   int i, j;                /* Loop counters */
86766
86767   assert( argc==3 );
86768   UNUSED_PARAMETER(argc);
86769   zStr = sqlcipher3_value_text(argv[0]);
86770   if( zStr==0 ) return;
86771   nStr = sqlcipher3_value_bytes(argv[0]);
86772   assert( zStr==sqlcipher3_value_text(argv[0]) );  /* No encoding change */
86773   zPattern = sqlcipher3_value_text(argv[1]);
86774   if( zPattern==0 ){
86775     assert( sqlcipher3_value_type(argv[1])==SQLCIPHER_NULL
86776             || sqlcipher3_context_db_handle(context)->mallocFailed );
86777     return;
86778   }
86779   if( zPattern[0]==0 ){
86780     assert( sqlcipher3_value_type(argv[1])!=SQLCIPHER_NULL );
86781     sqlcipher3_result_value(context, argv[0]);
86782     return;
86783   }
86784   nPattern = sqlcipher3_value_bytes(argv[1]);
86785   assert( zPattern==sqlcipher3_value_text(argv[1]) );  /* No encoding change */
86786   zRep = sqlcipher3_value_text(argv[2]);
86787   if( zRep==0 ) return;
86788   nRep = sqlcipher3_value_bytes(argv[2]);
86789   assert( zRep==sqlcipher3_value_text(argv[2]) );
86790   nOut = nStr + 1;
86791   assert( nOut<SQLCIPHER_MAX_LENGTH );
86792   zOut = contextMalloc(context, (i64)nOut);
86793   if( zOut==0 ){
86794     return;
86795   }
86796   loopLimit = nStr - nPattern;  
86797   for(i=j=0; i<=loopLimit; i++){
86798     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
86799       zOut[j++] = zStr[i];
86800     }else{
86801       u8 *zOld;
86802       sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86803       nOut += nRep - nPattern;
86804       testcase( nOut-1==db->aLimit[SQLCIPHER_LIMIT_LENGTH] );
86805       testcase( nOut-2==db->aLimit[SQLCIPHER_LIMIT_LENGTH] );
86806       if( nOut-1>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
86807         sqlcipher3_result_error_toobig(context);
86808         sqlcipher3_free(zOut);
86809         return;
86810       }
86811       zOld = zOut;
86812       zOut = sqlcipher3_realloc(zOut, (int)nOut);
86813       if( zOut==0 ){
86814         sqlcipher3_result_error_nomem(context);
86815         sqlcipher3_free(zOld);
86816         return;
86817       }
86818       memcpy(&zOut[j], zRep, nRep);
86819       j += nRep;
86820       i += nPattern-1;
86821     }
86822   }
86823   assert( j+nStr-i+1==nOut );
86824   memcpy(&zOut[j], &zStr[i], nStr-i);
86825   j += nStr - i;
86826   assert( j<=nOut );
86827   zOut[j] = 0;
86828   sqlcipher3_result_text(context, (char*)zOut, j, sqlcipher3_free);
86829 }
86830
86831 /*
86832 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
86833 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
86834 */
86835 static void trimFunc(
86836   sqlcipher3_context *context,
86837   int argc,
86838   sqlcipher3_value **argv
86839 ){
86840   const unsigned char *zIn;         /* Input string */
86841   const unsigned char *zCharSet;    /* Set of characters to trim */
86842   int nIn;                          /* Number of bytes in input */
86843   int flags;                        /* 1: trimleft  2: trimright  3: trim */
86844   int i;                            /* Loop counter */
86845   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
86846   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
86847   int nChar;                        /* Number of characters in zCharSet */
86848
86849   if( sqlcipher3_value_type(argv[0])==SQLCIPHER_NULL ){
86850     return;
86851   }
86852   zIn = sqlcipher3_value_text(argv[0]);
86853   if( zIn==0 ) return;
86854   nIn = sqlcipher3_value_bytes(argv[0]);
86855   assert( zIn==sqlcipher3_value_text(argv[0]) );
86856   if( argc==1 ){
86857     static const unsigned char lenOne[] = { 1 };
86858     static unsigned char * const azOne[] = { (u8*)" " };
86859     nChar = 1;
86860     aLen = (u8*)lenOne;
86861     azChar = (unsigned char **)azOne;
86862     zCharSet = 0;
86863   }else if( (zCharSet = sqlcipher3_value_text(argv[1]))==0 ){
86864     return;
86865   }else{
86866     const unsigned char *z;
86867     for(z=zCharSet, nChar=0; *z; nChar++){
86868       SQLCIPHER_SKIP_UTF8(z);
86869     }
86870     if( nChar>0 ){
86871       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
86872       if( azChar==0 ){
86873         return;
86874       }
86875       aLen = (unsigned char*)&azChar[nChar];
86876       for(z=zCharSet, nChar=0; *z; nChar++){
86877         azChar[nChar] = (unsigned char *)z;
86878         SQLCIPHER_SKIP_UTF8(z);
86879         aLen[nChar] = (u8)(z - azChar[nChar]);
86880       }
86881     }
86882   }
86883   if( nChar>0 ){
86884     flags = SQLCIPHER_PTR_TO_INT(sqlcipher3_user_data(context));
86885     if( flags & 1 ){
86886       while( nIn>0 ){
86887         int len = 0;
86888         for(i=0; i<nChar; i++){
86889           len = aLen[i];
86890           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
86891         }
86892         if( i>=nChar ) break;
86893         zIn += len;
86894         nIn -= len;
86895       }
86896     }
86897     if( flags & 2 ){
86898       while( nIn>0 ){
86899         int len = 0;
86900         for(i=0; i<nChar; i++){
86901           len = aLen[i];
86902           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
86903         }
86904         if( i>=nChar ) break;
86905         nIn -= len;
86906       }
86907     }
86908     if( zCharSet ){
86909       sqlcipher3_free(azChar);
86910     }
86911   }
86912   sqlcipher3_result_text(context, (char*)zIn, nIn, SQLCIPHER_TRANSIENT);
86913 }
86914
86915
86916 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
86917 ** is only available if the SQLCIPHER_SOUNDEX compile-time option is used
86918 ** when SQLite is built.
86919 */
86920 #ifdef SQLCIPHER_SOUNDEX
86921 /*
86922 ** Compute the soundex encoding of a word.
86923 **
86924 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
86925 ** soundex encoding of the string X. 
86926 */
86927 static void soundexFunc(
86928   sqlcipher3_context *context,
86929   int argc,
86930   sqlcipher3_value **argv
86931 ){
86932   char zResult[8];
86933   const u8 *zIn;
86934   int i, j;
86935   static const unsigned char iCode[] = {
86936     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86937     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86938     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86939     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86940     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
86941     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
86942     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
86943     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
86944   };
86945   assert( argc==1 );
86946   zIn = (u8*)sqlcipher3_value_text(argv[0]);
86947   if( zIn==0 ) zIn = (u8*)"";
86948   for(i=0; zIn[i] && !sqlcipher3Isalpha(zIn[i]); i++){}
86949   if( zIn[i] ){
86950     u8 prevcode = iCode[zIn[i]&0x7f];
86951     zResult[0] = sqlcipher3Toupper(zIn[i]);
86952     for(j=1; j<4 && zIn[i]; i++){
86953       int code = iCode[zIn[i]&0x7f];
86954       if( code>0 ){
86955         if( code!=prevcode ){
86956           prevcode = code;
86957           zResult[j++] = code + '0';
86958         }
86959       }else{
86960         prevcode = 0;
86961       }
86962     }
86963     while( j<4 ){
86964       zResult[j++] = '0';
86965     }
86966     zResult[j] = 0;
86967     sqlcipher3_result_text(context, zResult, 4, SQLCIPHER_TRANSIENT);
86968   }else{
86969     /* IMP: R-64894-50321 The string "?000" is returned if the argument
86970     ** is NULL or contains no ASCII alphabetic characters. */
86971     sqlcipher3_result_text(context, "?000", 4, SQLCIPHER_STATIC);
86972   }
86973 }
86974 #endif /* SQLCIPHER_SOUNDEX */
86975
86976 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
86977 /*
86978 ** A function that loads a shared-library extension then returns NULL.
86979 */
86980 static void loadExt(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
86981   const char *zFile = (const char *)sqlcipher3_value_text(argv[0]);
86982   const char *zProc;
86983   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86984   char *zErrMsg = 0;
86985
86986   if( argc==2 ){
86987     zProc = (const char *)sqlcipher3_value_text(argv[1]);
86988   }else{
86989     zProc = 0;
86990   }
86991   if( zFile && sqlcipher3_load_extension(db, zFile, zProc, &zErrMsg) ){
86992     sqlcipher3_result_error(context, zErrMsg, -1);
86993     sqlcipher3_free(zErrMsg);
86994   }
86995 }
86996 #endif
86997
86998
86999 /*
87000 ** An instance of the following structure holds the context of a
87001 ** sum() or avg() aggregate computation.
87002 */
87003 typedef struct SumCtx SumCtx;
87004 struct SumCtx {
87005   double rSum;      /* Floating point sum */
87006   i64 iSum;         /* Integer sum */   
87007   i64 cnt;          /* Number of elements summed */
87008   u8 overflow;      /* True if integer overflow seen */
87009   u8 approx;        /* True if non-integer value was input to the sum */
87010 };
87011
87012 /*
87013 ** Routines used to compute the sum, average, and total.
87014 **
87015 ** The SUM() function follows the (broken) SQL standard which means
87016 ** that it returns NULL if it sums over no inputs.  TOTAL returns
87017 ** 0.0 in that case.  In addition, TOTAL always returns a float where
87018 ** SUM might return an integer if it never encounters a floating point
87019 ** value.  TOTAL never fails, but SUM might through an exception if
87020 ** it overflows an integer.
87021 */
87022 static void sumStep(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
87023   SumCtx *p;
87024   int type;
87025   assert( argc==1 );
87026   UNUSED_PARAMETER(argc);
87027   p = sqlcipher3_aggregate_context(context, sizeof(*p));
87028   type = sqlcipher3_value_numeric_type(argv[0]);
87029   if( p && type!=SQLCIPHER_NULL ){
87030     p->cnt++;
87031     if( type==SQLCIPHER_INTEGER ){
87032       i64 v = sqlcipher3_value_int64(argv[0]);
87033       p->rSum += v;
87034       if( (p->approx|p->overflow)==0 && sqlcipher3AddInt64(&p->iSum, v) ){
87035         p->overflow = 1;
87036       }
87037     }else{
87038       p->rSum += sqlcipher3_value_double(argv[0]);
87039       p->approx = 1;
87040     }
87041   }
87042 }
87043 static void sumFinalize(sqlcipher3_context *context){
87044   SumCtx *p;
87045   p = sqlcipher3_aggregate_context(context, 0);
87046   if( p && p->cnt>0 ){
87047     if( p->overflow ){
87048       sqlcipher3_result_error(context,"integer overflow",-1);
87049     }else if( p->approx ){
87050       sqlcipher3_result_double(context, p->rSum);
87051     }else{
87052       sqlcipher3_result_int64(context, p->iSum);
87053     }
87054   }
87055 }
87056 static void avgFinalize(sqlcipher3_context *context){
87057   SumCtx *p;
87058   p = sqlcipher3_aggregate_context(context, 0);
87059   if( p && p->cnt>0 ){
87060     sqlcipher3_result_double(context, p->rSum/(double)p->cnt);
87061   }
87062 }
87063 static void totalFinalize(sqlcipher3_context *context){
87064   SumCtx *p;
87065   p = sqlcipher3_aggregate_context(context, 0);
87066   /* (double)0 In case of SQLCIPHER_OMIT_FLOATING_POINT... */
87067   sqlcipher3_result_double(context, p ? p->rSum : (double)0);
87068 }
87069
87070 /*
87071 ** The following structure keeps track of state information for the
87072 ** count() aggregate function.
87073 */
87074 typedef struct CountCtx CountCtx;
87075 struct CountCtx {
87076   i64 n;
87077 };
87078
87079 /*
87080 ** Routines to implement the count() aggregate function.
87081 */
87082 static void countStep(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
87083   CountCtx *p;
87084   p = sqlcipher3_aggregate_context(context, sizeof(*p));
87085   if( (argc==0 || SQLCIPHER_NULL!=sqlcipher3_value_type(argv[0])) && p ){
87086     p->n++;
87087   }
87088
87089 #ifndef SQLCIPHER_OMIT_DEPRECATED
87090   /* The sqlcipher3_aggregate_count() function is deprecated.  But just to make
87091   ** sure it still operates correctly, verify that its count agrees with our 
87092   ** internal count when using count(*) and when the total count can be
87093   ** expressed as a 32-bit integer. */
87094   assert( argc==1 || p==0 || p->n>0x7fffffff
87095           || p->n==sqlcipher3_aggregate_count(context) );
87096 #endif
87097 }   
87098 static void countFinalize(sqlcipher3_context *context){
87099   CountCtx *p;
87100   p = sqlcipher3_aggregate_context(context, 0);
87101   sqlcipher3_result_int64(context, p ? p->n : 0);
87102 }
87103
87104 /*
87105 ** Routines to implement min() and max() aggregate functions.
87106 */
87107 static void minmaxStep(
87108   sqlcipher3_context *context, 
87109   int NotUsed, 
87110   sqlcipher3_value **argv
87111 ){
87112   Mem *pArg  = (Mem *)argv[0];
87113   Mem *pBest;
87114   UNUSED_PARAMETER(NotUsed);
87115
87116   if( sqlcipher3_value_type(argv[0])==SQLCIPHER_NULL ) return;
87117   pBest = (Mem *)sqlcipher3_aggregate_context(context, sizeof(*pBest));
87118   if( !pBest ) return;
87119
87120   if( pBest->flags ){
87121     int max;
87122     int cmp;
87123     CollSeq *pColl = sqlcipher3GetFuncCollSeq(context);
87124     /* This step function is used for both the min() and max() aggregates,
87125     ** the only difference between the two being that the sense of the
87126     ** comparison is inverted. For the max() aggregate, the
87127     ** sqlcipher3_user_data() function returns (void *)-1. For min() it
87128     ** returns (void *)db, where db is the sqlcipher3* database pointer.
87129     ** Therefore the next statement sets variable 'max' to 1 for the max()
87130     ** aggregate, or 0 for min().
87131     */
87132     max = sqlcipher3_user_data(context)!=0;
87133     cmp = sqlcipher3MemCompare(pBest, pArg, pColl);
87134     if( (max && cmp<0) || (!max && cmp>0) ){
87135       sqlcipher3VdbeMemCopy(pBest, pArg);
87136     }
87137   }else{
87138     sqlcipher3VdbeMemCopy(pBest, pArg);
87139   }
87140 }
87141 static void minMaxFinalize(sqlcipher3_context *context){
87142   sqlcipher3_value *pRes;
87143   pRes = (sqlcipher3_value *)sqlcipher3_aggregate_context(context, 0);
87144   if( pRes ){
87145     if( ALWAYS(pRes->flags) ){
87146       sqlcipher3_result_value(context, pRes);
87147     }
87148     sqlcipher3VdbeMemRelease(pRes);
87149   }
87150 }
87151
87152 /*
87153 ** group_concat(EXPR, ?SEPARATOR?)
87154 */
87155 static void groupConcatStep(
87156   sqlcipher3_context *context,
87157   int argc,
87158   sqlcipher3_value **argv
87159 ){
87160   const char *zVal;
87161   StrAccum *pAccum;
87162   const char *zSep;
87163   int nVal, nSep;
87164   assert( argc==1 || argc==2 );
87165   if( sqlcipher3_value_type(argv[0])==SQLCIPHER_NULL ) return;
87166   pAccum = (StrAccum*)sqlcipher3_aggregate_context(context, sizeof(*pAccum));
87167
87168   if( pAccum ){
87169     sqlcipher3 *db = sqlcipher3_context_db_handle(context);
87170     int firstTerm = pAccum->useMalloc==0;
87171     pAccum->useMalloc = 2;
87172     pAccum->mxAlloc = db->aLimit[SQLCIPHER_LIMIT_LENGTH];
87173     if( !firstTerm ){
87174       if( argc==2 ){
87175         zSep = (char*)sqlcipher3_value_text(argv[1]);
87176         nSep = sqlcipher3_value_bytes(argv[1]);
87177       }else{
87178         zSep = ",";
87179         nSep = 1;
87180       }
87181       sqlcipher3StrAccumAppend(pAccum, zSep, nSep);
87182     }
87183     zVal = (char*)sqlcipher3_value_text(argv[0]);
87184     nVal = sqlcipher3_value_bytes(argv[0]);
87185     sqlcipher3StrAccumAppend(pAccum, zVal, nVal);
87186   }
87187 }
87188 static void groupConcatFinalize(sqlcipher3_context *context){
87189   StrAccum *pAccum;
87190   pAccum = sqlcipher3_aggregate_context(context, 0);
87191   if( pAccum ){
87192     if( pAccum->tooBig ){
87193       sqlcipher3_result_error_toobig(context);
87194     }else if( pAccum->mallocFailed ){
87195       sqlcipher3_result_error_nomem(context);
87196     }else{    
87197       sqlcipher3_result_text(context, sqlcipher3StrAccumFinish(pAccum), -1, 
87198                           sqlcipher3_free);
87199     }
87200   }
87201 }
87202
87203 /*
87204 ** This routine does per-connection function registration.  Most
87205 ** of the built-in functions above are part of the global function set.
87206 ** This routine only deals with those that are not global.
87207 */
87208 SQLCIPHER_PRIVATE void sqlcipher3RegisterBuiltinFunctions(sqlcipher3 *db){
87209   int rc = sqlcipher3_overload_function(db, "MATCH", 2);
87210 #ifndef OMIT_EXPORT
87211   extern void sqlcipher_exportFunc(sqlcipher3_context *, int, sqlcipher3_value **);
87212 #endif
87213   assert( rc==SQLCIPHER_NOMEM || rc==SQLCIPHER_OK );
87214   if( rc==SQLCIPHER_NOMEM ){
87215     db->mallocFailed = 1;
87216   }
87217 #ifndef OMIT_EXPORT
87218   sqlcipher3CreateFunc(db, "sqlcipher_export", 1, SQLCIPHER_TEXT, 0, sqlcipher_exportFunc, 0, 0, 0);
87219 #endif
87220 }
87221
87222 /*
87223 ** Set the LIKEOPT flag on the 2-argument function with the given name.
87224 */
87225 static void setLikeOptFlag(sqlcipher3 *db, const char *zName, u8 flagVal){
87226   FuncDef *pDef;
87227   pDef = sqlcipher3FindFunction(db, zName, sqlcipher3Strlen30(zName),
87228                              2, SQLCIPHER_UTF8, 0);
87229   if( ALWAYS(pDef) ){
87230     pDef->flags = flagVal;
87231   }
87232 }
87233
87234 /*
87235 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
87236 ** parameter determines whether or not the LIKE operator is case
87237 ** sensitive.  GLOB is always case sensitive.
87238 */
87239 SQLCIPHER_PRIVATE void sqlcipher3RegisterLikeFunctions(sqlcipher3 *db, int caseSensitive){
87240   struct compareInfo *pInfo;
87241   if( caseSensitive ){
87242     pInfo = (struct compareInfo*)&likeInfoAlt;
87243   }else{
87244     pInfo = (struct compareInfo*)&likeInfoNorm;
87245   }
87246   sqlcipher3CreateFunc(db, "like", 2, SQLCIPHER_UTF8, pInfo, likeFunc, 0, 0, 0);
87247   sqlcipher3CreateFunc(db, "like", 3, SQLCIPHER_UTF8, pInfo, likeFunc, 0, 0, 0);
87248   sqlcipher3CreateFunc(db, "glob", 2, SQLCIPHER_UTF8, 
87249       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
87250   setLikeOptFlag(db, "glob", SQLCIPHER_FUNC_LIKE | SQLCIPHER_FUNC_CASE);
87251   setLikeOptFlag(db, "like", 
87252       caseSensitive ? (SQLCIPHER_FUNC_LIKE | SQLCIPHER_FUNC_CASE) : SQLCIPHER_FUNC_LIKE);
87253 }
87254
87255 /*
87256 ** pExpr points to an expression which implements a function.  If
87257 ** it is appropriate to apply the LIKE optimization to that function
87258 ** then set aWc[0] through aWc[2] to the wildcard characters and
87259 ** return TRUE.  If the function is not a LIKE-style function then
87260 ** return FALSE.
87261 */
87262 SQLCIPHER_PRIVATE int sqlcipher3IsLikeFunction(sqlcipher3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
87263   FuncDef *pDef;
87264   if( pExpr->op!=TK_FUNCTION 
87265    || !pExpr->x.pList 
87266    || pExpr->x.pList->nExpr!=2
87267   ){
87268     return 0;
87269   }
87270   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
87271   pDef = sqlcipher3FindFunction(db, pExpr->u.zToken, 
87272                              sqlcipher3Strlen30(pExpr->u.zToken),
87273                              2, SQLCIPHER_UTF8, 0);
87274   if( NEVER(pDef==0) || (pDef->flags & SQLCIPHER_FUNC_LIKE)==0 ){
87275     return 0;
87276   }
87277
87278   /* The memcpy() statement assumes that the wildcard characters are
87279   ** the first three statements in the compareInfo structure.  The
87280   ** asserts() that follow verify that assumption
87281   */
87282   memcpy(aWc, pDef->pUserData, 3);
87283   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
87284   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
87285   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
87286   *pIsNocase = (pDef->flags & SQLCIPHER_FUNC_CASE)==0;
87287   return 1;
87288 }
87289
87290 /*
87291 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
87292 ** to the global function hash table.  This occurs at start-time (as
87293 ** a consequence of calling sqlcipher3_initialize()).
87294 **
87295 ** After this routine runs
87296 */
87297 SQLCIPHER_PRIVATE void sqlcipher3RegisterGlobalFunctions(void){
87298   /*
87299   ** The following array holds FuncDef structures for all of the functions
87300   ** defined in this file.
87301   **
87302   ** The array cannot be constant since changes are made to the
87303   ** FuncDef.pHash elements at start-time.  The elements of this array
87304   ** are read-only after initialization is complete.
87305   */
87306   static SQLCIPHER_WSD FuncDef aBuiltinFunc[] = {
87307     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
87308     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
87309     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
87310     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
87311     FUNCTION(trim,               1, 3, 0, trimFunc         ),
87312     FUNCTION(trim,               2, 3, 0, trimFunc         ),
87313     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
87314     FUNCTION(min,                0, 0, 1, 0                ),
87315     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
87316     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
87317     FUNCTION(max,                0, 1, 1, 0                ),
87318     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
87319     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
87320     FUNCTION(length,             1, 0, 0, lengthFunc       ),
87321     FUNCTION(substr,             2, 0, 0, substrFunc       ),
87322     FUNCTION(substr,             3, 0, 0, substrFunc       ),
87323     FUNCTION(abs,                1, 0, 0, absFunc          ),
87324 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
87325     FUNCTION(round,              1, 0, 0, roundFunc        ),
87326     FUNCTION(round,              2, 0, 0, roundFunc        ),
87327 #endif
87328     FUNCTION(upper,              1, 0, 0, upperFunc        ),
87329     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
87330     FUNCTION(coalesce,           1, 0, 0, 0                ),
87331     FUNCTION(coalesce,           0, 0, 0, 0                ),
87332 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
87333     {-1,SQLCIPHER_UTF8,SQLCIPHER_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
87334     FUNCTION(hex,                1, 0, 0, hexFunc          ),
87335 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
87336     {2,SQLCIPHER_UTF8,SQLCIPHER_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
87337     FUNCTION(random,             0, 0, 0, randomFunc       ),
87338     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
87339     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
87340     FUNCTION(sqlcipher_version,     0, 0, 0, versionFunc      ),
87341     FUNCTION(sqlcipher_source_id,   0, 0, 0, sourceidFunc     ),
87342     FUNCTION(sqlcipher_log,         2, 0, 0, errlogFunc       ),
87343 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
87344     FUNCTION(sqlcipher_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
87345     FUNCTION(sqlcipher_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
87346 #endif /* SQLCIPHER_OMIT_COMPILEOPTION_DIAGS */
87347     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
87348     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
87349     FUNCTION(changes,            0, 0, 0, changes          ),
87350     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
87351     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
87352     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
87353   #ifdef SQLCIPHER_SOUNDEX
87354     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
87355   #endif
87356   #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
87357     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
87358     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
87359   #endif
87360     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
87361     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
87362     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
87363  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
87364     {0,SQLCIPHER_UTF8,SQLCIPHER_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
87365     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
87366     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
87367     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
87368   
87369     LIKEFUNC(glob, 2, &globInfo, SQLCIPHER_FUNC_LIKE|SQLCIPHER_FUNC_CASE),
87370   #ifdef SQLCIPHER_CASE_SENSITIVE_LIKE
87371     LIKEFUNC(like, 2, &likeInfoAlt, SQLCIPHER_FUNC_LIKE|SQLCIPHER_FUNC_CASE),
87372     LIKEFUNC(like, 3, &likeInfoAlt, SQLCIPHER_FUNC_LIKE|SQLCIPHER_FUNC_CASE),
87373   #else
87374     LIKEFUNC(like, 2, &likeInfoNorm, SQLCIPHER_FUNC_LIKE),
87375     LIKEFUNC(like, 3, &likeInfoNorm, SQLCIPHER_FUNC_LIKE),
87376   #endif
87377   };
87378
87379   int i;
87380   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlcipher3GlobalFunctions);
87381   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
87382
87383   for(i=0; i<ArraySize(aBuiltinFunc); i++){
87384     sqlcipher3FuncDefInsert(pHash, &aFunc[i]);
87385   }
87386   sqlcipher3RegisterDateTimeFunctions();
87387 #ifndef SQLCIPHER_OMIT_ALTERTABLE
87388   sqlcipher3AlterFunctions();
87389 #endif
87390 }
87391
87392 /************** End of func.c ************************************************/
87393 /************** Begin file fkey.c ********************************************/
87394 /*
87395 **
87396 ** The author disclaims copyright to this source code.  In place of
87397 ** a legal notice, here is a blessing:
87398 **
87399 **    May you do good and not evil.
87400 **    May you find forgiveness for yourself and forgive others.
87401 **    May you share freely, never taking more than you give.
87402 **
87403 *************************************************************************
87404 ** This file contains code used by the compiler to add foreign key
87405 ** support to compiled SQL statements.
87406 */
87407
87408 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
87409 #ifndef SQLCIPHER_OMIT_TRIGGER
87410
87411 /*
87412 ** Deferred and Immediate FKs
87413 ** --------------------------
87414 **
87415 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
87416 ** If an immediate foreign key constraint is violated, SQLCIPHER_CONSTRAINT
87417 ** is returned and the current statement transaction rolled back. If a 
87418 ** deferred foreign key constraint is violated, no action is taken 
87419 ** immediately. However if the application attempts to commit the 
87420 ** transaction before fixing the constraint violation, the attempt fails.
87421 **
87422 ** Deferred constraints are implemented using a simple counter associated
87423 ** with the database handle. The counter is set to zero each time a 
87424 ** database transaction is opened. Each time a statement is executed 
87425 ** that causes a foreign key violation, the counter is incremented. Each
87426 ** time a statement is executed that removes an existing violation from
87427 ** the database, the counter is decremented. When the transaction is
87428 ** committed, the commit fails if the current value of the counter is
87429 ** greater than zero. This scheme has two big drawbacks:
87430 **
87431 **   * When a commit fails due to a deferred foreign key constraint, 
87432 **     there is no way to tell which foreign constraint is not satisfied,
87433 **     or which row it is not satisfied for.
87434 **
87435 **   * If the database contains foreign key violations when the 
87436 **     transaction is opened, this may cause the mechanism to malfunction.
87437 **
87438 ** Despite these problems, this approach is adopted as it seems simpler
87439 ** than the alternatives.
87440 **
87441 ** INSERT operations:
87442 **
87443 **   I.1) For each FK for which the table is the child table, search
87444 **        the parent table for a match. If none is found increment the
87445 **        constraint counter.
87446 **
87447 **   I.2) For each FK for which the table is the parent table, 
87448 **        search the child table for rows that correspond to the new
87449 **        row in the parent table. Decrement the counter for each row
87450 **        found (as the constraint is now satisfied).
87451 **
87452 ** DELETE operations:
87453 **
87454 **   D.1) For each FK for which the table is the child table, 
87455 **        search the parent table for a row that corresponds to the 
87456 **        deleted row in the child table. If such a row is not found, 
87457 **        decrement the counter.
87458 **
87459 **   D.2) For each FK for which the table is the parent table, search 
87460 **        the child table for rows that correspond to the deleted row 
87461 **        in the parent table. For each found increment the counter.
87462 **
87463 ** UPDATE operations:
87464 **
87465 **   An UPDATE command requires that all 4 steps above are taken, but only
87466 **   for FK constraints for which the affected columns are actually 
87467 **   modified (values must be compared at runtime).
87468 **
87469 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
87470 ** This simplifies the implementation a bit.
87471 **
87472 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
87473 ** resolution is considered to delete rows before the new row is inserted.
87474 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
87475 ** is thrown, even if the FK constraint would be satisfied after the new 
87476 ** row is inserted.
87477 **
87478 ** Immediate constraints are usually handled similarly. The only difference 
87479 ** is that the counter used is stored as part of each individual statement
87480 ** object (struct Vdbe). If, after the statement has run, its immediate
87481 ** constraint counter is greater than zero, it returns SQLCIPHER_CONSTRAINT
87482 ** and the statement transaction is rolled back. An exception is an INSERT
87483 ** statement that inserts a single row only (no triggers). In this case,
87484 ** instead of using a counter, an exception is thrown immediately if the
87485 ** INSERT violates a foreign key constraint. This is necessary as such
87486 ** an INSERT does not open a statement transaction.
87487 **
87488 ** TODO: How should dropping a table be handled? How should renaming a 
87489 ** table be handled?
87490 **
87491 **
87492 ** Query API Notes
87493 ** ---------------
87494 **
87495 ** Before coding an UPDATE or DELETE row operation, the code-generator
87496 ** for those two operations needs to know whether or not the operation
87497 ** requires any FK processing and, if so, which columns of the original
87498 ** row are required by the FK processing VDBE code (i.e. if FKs were
87499 ** implemented using triggers, which of the old.* columns would be 
87500 ** accessed). No information is required by the code-generator before
87501 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
87502 ** generation code to query for this information are:
87503 **
87504 **   sqlcipher3FkRequired() - Test to see if FK processing is required.
87505 **   sqlcipher3FkOldmask()  - Query for the set of required old.* columns.
87506 **
87507 **
87508 ** Externally accessible module functions
87509 ** --------------------------------------
87510 **
87511 **   sqlcipher3FkCheck()    - Check for foreign key violations.
87512 **   sqlcipher3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
87513 **   sqlcipher3FkDelete()   - Delete an FKey structure.
87514 */
87515
87516 /*
87517 ** VDBE Calling Convention
87518 ** -----------------------
87519 **
87520 ** Example:
87521 **
87522 **   For the following INSERT statement:
87523 **
87524 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
87525 **     INSERT INTO t1 VALUES(1, 2, 3.1);
87526 **
87527 **   Register (x):        2    (type integer)
87528 **   Register (x+1):      1    (type integer)
87529 **   Register (x+2):      NULL (type NULL)
87530 **   Register (x+3):      3.1  (type real)
87531 */
87532
87533 /*
87534 ** A foreign key constraint requires that the key columns in the parent
87535 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
87536 ** Given that pParent is the parent table for foreign key constraint pFKey, 
87537 ** search the schema a unique index on the parent key columns. 
87538 **
87539 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
87540 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
87541 ** is set to point to the unique index. 
87542 ** 
87543 ** If the parent key consists of a single column (the foreign key constraint
87544 ** is not a composite foreign key), output variable *paiCol is set to NULL.
87545 ** Otherwise, it is set to point to an allocated array of size N, where
87546 ** N is the number of columns in the parent key. The first element of the
87547 ** array is the index of the child table column that is mapped by the FK
87548 ** constraint to the parent table column stored in the left-most column
87549 ** of index *ppIdx. The second element of the array is the index of the
87550 ** child table column that corresponds to the second left-most column of
87551 ** *ppIdx, and so on.
87552 **
87553 ** If the required index cannot be found, either because:
87554 **
87555 **   1) The named parent key columns do not exist, or
87556 **
87557 **   2) The named parent key columns do exist, but are not subject to a
87558 **      UNIQUE or PRIMARY KEY constraint, or
87559 **
87560 **   3) No parent key columns were provided explicitly as part of the
87561 **      foreign key definition, and the parent table does not have a
87562 **      PRIMARY KEY, or
87563 **
87564 **   4) No parent key columns were provided explicitly as part of the
87565 **      foreign key definition, and the PRIMARY KEY of the parent table 
87566 **      consists of a a different number of columns to the child key in 
87567 **      the child table.
87568 **
87569 ** then non-zero is returned, and a "foreign key mismatch" error loaded
87570 ** into pParse. If an OOM error occurs, non-zero is returned and the
87571 ** pParse->db->mallocFailed flag is set.
87572 */
87573 static int locateFkeyIndex(
87574   Parse *pParse,                  /* Parse context to store any error in */
87575   Table *pParent,                 /* Parent table of FK constraint pFKey */
87576   FKey *pFKey,                    /* Foreign key to find index for */
87577   Index **ppIdx,                  /* OUT: Unique index on parent table */
87578   int **paiCol                    /* OUT: Map of index columns in pFKey */
87579 ){
87580   Index *pIdx = 0;                    /* Value to return via *ppIdx */
87581   int *aiCol = 0;                     /* Value to return via *paiCol */
87582   int nCol = pFKey->nCol;             /* Number of columns in parent key */
87583   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
87584
87585   /* The caller is responsible for zeroing output parameters. */
87586   assert( ppIdx && *ppIdx==0 );
87587   assert( !paiCol || *paiCol==0 );
87588   assert( pParse );
87589
87590   /* If this is a non-composite (single column) foreign key, check if it 
87591   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
87592   ** and *paiCol set to zero and return early. 
87593   **
87594   ** Otherwise, for a composite foreign key (more than one column), allocate
87595   ** space for the aiCol array (returned via output parameter *paiCol).
87596   ** Non-composite foreign keys do not require the aiCol array.
87597   */
87598   if( nCol==1 ){
87599     /* The FK maps to the IPK if any of the following are true:
87600     **
87601     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
87602     **      mapped to the primary key of table pParent, or
87603     **   2) The FK is explicitly mapped to a column declared as INTEGER
87604     **      PRIMARY KEY.
87605     */
87606     if( pParent->iPKey>=0 ){
87607       if( !zKey ) return 0;
87608       if( !sqlcipher3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
87609     }
87610   }else if( paiCol ){
87611     assert( nCol>1 );
87612     aiCol = (int *)sqlcipher3DbMallocRaw(pParse->db, nCol*sizeof(int));
87613     if( !aiCol ) return 1;
87614     *paiCol = aiCol;
87615   }
87616
87617   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
87618     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
87619       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
87620       ** of columns. If each indexed column corresponds to a foreign key
87621       ** column of pFKey, then this index is a winner.  */
87622
87623       if( zKey==0 ){
87624         /* If zKey is NULL, then this foreign key is implicitly mapped to 
87625         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
87626         ** identified by the test (Index.autoIndex==2).  */
87627         if( pIdx->autoIndex==2 ){
87628           if( aiCol ){
87629             int i;
87630             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
87631           }
87632           break;
87633         }
87634       }else{
87635         /* If zKey is non-NULL, then this foreign key was declared to
87636         ** map to an explicit list of columns in table pParent. Check if this
87637         ** index matches those columns. Also, check that the index uses
87638         ** the default collation sequences for each column. */
87639         int i, j;
87640         for(i=0; i<nCol; i++){
87641           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
87642           char *zDfltColl;                  /* Def. collation for column */
87643           char *zIdxCol;                    /* Name of indexed column */
87644
87645           /* If the index uses a collation sequence that is different from
87646           ** the default collation sequence for the column, this index is
87647           ** unusable. Bail out early in this case.  */
87648           zDfltColl = pParent->aCol[iCol].zColl;
87649           if( !zDfltColl ){
87650             zDfltColl = "BINARY";
87651           }
87652           if( sqlcipher3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
87653
87654           zIdxCol = pParent->aCol[iCol].zName;
87655           for(j=0; j<nCol; j++){
87656             if( sqlcipher3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
87657               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
87658               break;
87659             }
87660           }
87661           if( j==nCol ) break;
87662         }
87663         if( i==nCol ) break;      /* pIdx is usable */
87664       }
87665     }
87666   }
87667
87668   if( !pIdx ){
87669     if( !pParse->disableTriggers ){
87670       sqlcipher3ErrorMsg(pParse, "foreign key mismatch");
87671     }
87672     sqlcipher3DbFree(pParse->db, aiCol);
87673     return 1;
87674   }
87675
87676   *ppIdx = pIdx;
87677   return 0;
87678 }
87679
87680 /*
87681 ** This function is called when a row is inserted into or deleted from the 
87682 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
87683 ** on the child table of pFKey, this function is invoked twice for each row
87684 ** affected - once to "delete" the old row, and then again to "insert" the
87685 ** new row.
87686 **
87687 ** Each time it is called, this function generates VDBE code to locate the
87688 ** row in the parent table that corresponds to the row being inserted into 
87689 ** or deleted from the child table. If the parent row can be found, no 
87690 ** special action is taken. Otherwise, if the parent row can *not* be
87691 ** found in the parent table:
87692 **
87693 **   Operation | FK type   | Action taken
87694 **   --------------------------------------------------------------------------
87695 **   INSERT      immediate   Increment the "immediate constraint counter".
87696 **
87697 **   DELETE      immediate   Decrement the "immediate constraint counter".
87698 **
87699 **   INSERT      deferred    Increment the "deferred constraint counter".
87700 **
87701 **   DELETE      deferred    Decrement the "deferred constraint counter".
87702 **
87703 ** These operations are identified in the comment at the top of this file 
87704 ** (fkey.c) as "I.1" and "D.1".
87705 */
87706 static void fkLookupParent(
87707   Parse *pParse,        /* Parse context */
87708   int iDb,              /* Index of database housing pTab */
87709   Table *pTab,          /* Parent table of FK pFKey */
87710   Index *pIdx,          /* Unique index on parent key columns in pTab */
87711   FKey *pFKey,          /* Foreign key constraint */
87712   int *aiCol,           /* Map from parent key columns to child table columns */
87713   int regData,          /* Address of array containing child table row */
87714   int nIncr,            /* Increment constraint counter by this */
87715   int isIgnore          /* If true, pretend pTab contains all NULL values */
87716 ){
87717   int i;                                    /* Iterator variable */
87718   Vdbe *v = sqlcipher3GetVdbe(pParse);         /* Vdbe to add code to */
87719   int iCur = pParse->nTab - 1;              /* Cursor number to use */
87720   int iOk = sqlcipher3VdbeMakeLabel(v);        /* jump here if parent key found */
87721
87722   /* If nIncr is less than zero, then check at runtime if there are any
87723   ** outstanding constraints to resolve. If there are not, there is no need
87724   ** to check if deleting this row resolves any outstanding violations.
87725   **
87726   ** Check if any of the key columns in the child table row are NULL. If 
87727   ** any are, then the constraint is considered satisfied. No need to 
87728   ** search for a matching row in the parent table.  */
87729   if( nIncr<0 ){
87730     sqlcipher3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
87731   }
87732   for(i=0; i<pFKey->nCol; i++){
87733     int iReg = aiCol[i] + regData + 1;
87734     sqlcipher3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
87735   }
87736
87737   if( isIgnore==0 ){
87738     if( pIdx==0 ){
87739       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
87740       ** column of the parent table (table pTab).  */
87741       int iMustBeInt;               /* Address of MustBeInt instruction */
87742       int regTemp = sqlcipher3GetTempReg(pParse);
87743   
87744       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
87745       ** apply the affinity of the parent key). If this fails, then there
87746       ** is no matching parent key. Before using MustBeInt, make a copy of
87747       ** the value. Otherwise, the value inserted into the child key column
87748       ** will have INTEGER affinity applied to it, which may not be correct.  */
87749       sqlcipher3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
87750       iMustBeInt = sqlcipher3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
87751   
87752       /* If the parent table is the same as the child table, and we are about
87753       ** to increment the constraint-counter (i.e. this is an INSERT operation),
87754       ** then check if the row being inserted matches itself. If so, do not
87755       ** increment the constraint-counter.  */
87756       if( pTab==pFKey->pFrom && nIncr==1 ){
87757         sqlcipher3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
87758       }
87759   
87760       sqlcipher3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
87761       sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
87762       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, iOk);
87763       sqlcipher3VdbeJumpHere(v, sqlcipher3VdbeCurrentAddr(v)-2);
87764       sqlcipher3VdbeJumpHere(v, iMustBeInt);
87765       sqlcipher3ReleaseTempReg(pParse, regTemp);
87766     }else{
87767       int nCol = pFKey->nCol;
87768       int regTemp = sqlcipher3GetTempRange(pParse, nCol);
87769       int regRec = sqlcipher3GetTempReg(pParse);
87770       KeyInfo *pKey = sqlcipher3IndexKeyinfo(pParse, pIdx);
87771   
87772       sqlcipher3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
87773       sqlcipher3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
87774       for(i=0; i<nCol; i++){
87775         sqlcipher3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
87776       }
87777   
87778       /* If the parent table is the same as the child table, and we are about
87779       ** to increment the constraint-counter (i.e. this is an INSERT operation),
87780       ** then check if the row being inserted matches itself. If so, do not
87781       ** increment the constraint-counter. 
87782       **
87783       ** If any of the parent-key values are NULL, then the row cannot match 
87784       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
87785       ** of the parent-key values are NULL (at this point it is known that
87786       ** none of the child key values are).
87787       */
87788       if( pTab==pFKey->pFrom && nIncr==1 ){
87789         int iJump = sqlcipher3VdbeCurrentAddr(v) + nCol + 1;
87790         for(i=0; i<nCol; i++){
87791           int iChild = aiCol[i]+1+regData;
87792           int iParent = pIdx->aiColumn[i]+1+regData;
87793           assert( aiCol[i]!=pTab->iPKey );
87794           if( pIdx->aiColumn[i]==pTab->iPKey ){
87795             /* The parent key is a composite key that includes the IPK column */
87796             iParent = regData;
87797           }
87798           sqlcipher3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
87799           sqlcipher3VdbeChangeP5(v, SQLCIPHER_JUMPIFNULL);
87800         }
87801         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, iOk);
87802       }
87803   
87804       sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
87805       sqlcipher3VdbeChangeP4(v, -1, sqlcipher3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
87806       sqlcipher3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
87807   
87808       sqlcipher3ReleaseTempReg(pParse, regRec);
87809       sqlcipher3ReleaseTempRange(pParse, regTemp, nCol);
87810     }
87811   }
87812
87813   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
87814     /* Special case: If this is an INSERT statement that will insert exactly
87815     ** one row into the table, raise a constraint immediately instead of
87816     ** incrementing a counter. This is necessary as the VM code is being
87817     ** generated for will not open a statement transaction.  */
87818     assert( nIncr==1 );
87819     sqlcipher3HaltConstraint(
87820         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
87821     );
87822   }else{
87823     if( nIncr>0 && pFKey->isDeferred==0 ){
87824       sqlcipher3ParseToplevel(pParse)->mayAbort = 1;
87825     }
87826     sqlcipher3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
87827   }
87828
87829   sqlcipher3VdbeResolveLabel(v, iOk);
87830   sqlcipher3VdbeAddOp1(v, OP_Close, iCur);
87831 }
87832
87833 /*
87834 ** This function is called to generate code executed when a row is deleted
87835 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
87836 ** deferred, when a row is inserted into the same table. When generating
87837 ** code for an SQL UPDATE operation, this function may be called twice -
87838 ** once to "delete" the old row and once to "insert" the new row.
87839 **
87840 ** The code generated by this function scans through the rows in the child
87841 ** table that correspond to the parent table row being deleted or inserted.
87842 ** For each child row found, one of the following actions is taken:
87843 **
87844 **   Operation | FK type   | Action taken
87845 **   --------------------------------------------------------------------------
87846 **   DELETE      immediate   Increment the "immediate constraint counter".
87847 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
87848 **                           throw a "foreign key constraint failed" exception.
87849 **
87850 **   INSERT      immediate   Decrement the "immediate constraint counter".
87851 **
87852 **   DELETE      deferred    Increment the "deferred constraint counter".
87853 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
87854 **                           throw a "foreign key constraint failed" exception.
87855 **
87856 **   INSERT      deferred    Decrement the "deferred constraint counter".
87857 **
87858 ** These operations are identified in the comment at the top of this file 
87859 ** (fkey.c) as "I.2" and "D.2".
87860 */
87861 static void fkScanChildren(
87862   Parse *pParse,                  /* Parse context */
87863   SrcList *pSrc,                  /* SrcList containing the table to scan */
87864   Table *pTab,
87865   Index *pIdx,                    /* Foreign key index */
87866   FKey *pFKey,                    /* Foreign key relationship */
87867   int *aiCol,                     /* Map from pIdx cols to child table cols */
87868   int regData,                    /* Referenced table data starts here */
87869   int nIncr                       /* Amount to increment deferred counter by */
87870 ){
87871   sqlcipher3 *db = pParse->db;       /* Database handle */
87872   int i;                          /* Iterator variable */
87873   Expr *pWhere = 0;               /* WHERE clause to scan with */
87874   NameContext sNameContext;       /* Context used to resolve WHERE clause */
87875   WhereInfo *pWInfo;              /* Context used by sqlcipher3WhereXXX() */
87876   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
87877   Vdbe *v = sqlcipher3GetVdbe(pParse);
87878
87879   assert( !pIdx || pIdx->pTable==pTab );
87880
87881   if( nIncr<0 ){
87882     iFkIfZero = sqlcipher3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
87883   }
87884
87885   /* Create an Expr object representing an SQL expression like:
87886   **
87887   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
87888   **
87889   ** The collation sequence used for the comparison should be that of
87890   ** the parent key columns. The affinity of the parent key column should
87891   ** be applied to each child key value before the comparison takes place.
87892   */
87893   for(i=0; i<pFKey->nCol; i++){
87894     Expr *pLeft;                  /* Value from parent table row */
87895     Expr *pRight;                 /* Column ref to child table */
87896     Expr *pEq;                    /* Expression (pLeft = pRight) */
87897     int iCol;                     /* Index of column in child table */ 
87898     const char *zCol;             /* Name of column in child table */
87899
87900     pLeft = sqlcipher3Expr(db, TK_REGISTER, 0);
87901     if( pLeft ){
87902       /* Set the collation sequence and affinity of the LHS of each TK_EQ
87903       ** expression to the parent key column defaults.  */
87904       if( pIdx ){
87905         Column *pCol;
87906         iCol = pIdx->aiColumn[i];
87907         pCol = &pTab->aCol[iCol];
87908         if( pTab->iPKey==iCol ) iCol = -1;
87909         pLeft->iTable = regData+iCol+1;
87910         pLeft->affinity = pCol->affinity;
87911         pLeft->pColl = sqlcipher3LocateCollSeq(pParse, pCol->zColl);
87912       }else{
87913         pLeft->iTable = regData;
87914         pLeft->affinity = SQLCIPHER_AFF_INTEGER;
87915       }
87916     }
87917     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
87918     assert( iCol>=0 );
87919     zCol = pFKey->pFrom->aCol[iCol].zName;
87920     pRight = sqlcipher3Expr(db, TK_ID, zCol);
87921     pEq = sqlcipher3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
87922     pWhere = sqlcipher3ExprAnd(db, pWhere, pEq);
87923   }
87924
87925   /* If the child table is the same as the parent table, and this scan
87926   ** is taking place as part of a DELETE operation (operation D.2), omit the
87927   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
87928   ** clause, where $rowid is the rowid of the row being deleted.  */
87929   if( pTab==pFKey->pFrom && nIncr>0 ){
87930     Expr *pEq;                    /* Expression (pLeft = pRight) */
87931     Expr *pLeft;                  /* Value from parent table row */
87932     Expr *pRight;                 /* Column ref to child table */
87933     pLeft = sqlcipher3Expr(db, TK_REGISTER, 0);
87934     pRight = sqlcipher3Expr(db, TK_COLUMN, 0);
87935     if( pLeft && pRight ){
87936       pLeft->iTable = regData;
87937       pLeft->affinity = SQLCIPHER_AFF_INTEGER;
87938       pRight->iTable = pSrc->a[0].iCursor;
87939       pRight->iColumn = -1;
87940     }
87941     pEq = sqlcipher3PExpr(pParse, TK_NE, pLeft, pRight, 0);
87942     pWhere = sqlcipher3ExprAnd(db, pWhere, pEq);
87943   }
87944
87945   /* Resolve the references in the WHERE clause. */
87946   memset(&sNameContext, 0, sizeof(NameContext));
87947   sNameContext.pSrcList = pSrc;
87948   sNameContext.pParse = pParse;
87949   sqlcipher3ResolveExprNames(&sNameContext, pWhere);
87950
87951   /* Create VDBE to loop through the entries in pSrc that match the WHERE
87952   ** clause. If the constraint is not deferred, throw an exception for
87953   ** each row found. Otherwise, for deferred constraints, increment the
87954   ** deferred constraint counter by nIncr for each row selected.  */
87955   pWInfo = sqlcipher3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0);
87956   if( nIncr>0 && pFKey->isDeferred==0 ){
87957     sqlcipher3ParseToplevel(pParse)->mayAbort = 1;
87958   }
87959   sqlcipher3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
87960   if( pWInfo ){
87961     sqlcipher3WhereEnd(pWInfo);
87962   }
87963
87964   /* Clean up the WHERE clause constructed above. */
87965   sqlcipher3ExprDelete(db, pWhere);
87966   if( iFkIfZero ){
87967     sqlcipher3VdbeJumpHere(v, iFkIfZero);
87968   }
87969 }
87970
87971 /*
87972 ** This function returns a pointer to the head of a linked list of FK
87973 ** constraints for which table pTab is the parent table. For example,
87974 ** given the following schema:
87975 **
87976 **   CREATE TABLE t1(a PRIMARY KEY);
87977 **   CREATE TABLE t2(b REFERENCES t1(a);
87978 **
87979 ** Calling this function with table "t1" as an argument returns a pointer
87980 ** to the FKey structure representing the foreign key constraint on table
87981 ** "t2". Calling this function with "t2" as the argument would return a
87982 ** NULL pointer (as there are no FK constraints for which t2 is the parent
87983 ** table).
87984 */
87985 SQLCIPHER_PRIVATE FKey *sqlcipher3FkReferences(Table *pTab){
87986   int nName = sqlcipher3Strlen30(pTab->zName);
87987   return (FKey *)sqlcipher3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
87988 }
87989
87990 /*
87991 ** The second argument is a Trigger structure allocated by the 
87992 ** fkActionTrigger() routine. This function deletes the Trigger structure
87993 ** and all of its sub-components.
87994 **
87995 ** The Trigger structure or any of its sub-components may be allocated from
87996 ** the lookaside buffer belonging to database handle dbMem.
87997 */
87998 static void fkTriggerDelete(sqlcipher3 *dbMem, Trigger *p){
87999   if( p ){
88000     TriggerStep *pStep = p->step_list;
88001     sqlcipher3ExprDelete(dbMem, pStep->pWhere);
88002     sqlcipher3ExprListDelete(dbMem, pStep->pExprList);
88003     sqlcipher3SelectDelete(dbMem, pStep->pSelect);
88004     sqlcipher3ExprDelete(dbMem, p->pWhen);
88005     sqlcipher3DbFree(dbMem, p);
88006   }
88007 }
88008
88009 /*
88010 ** This function is called to generate code that runs when table pTab is
88011 ** being dropped from the database. The SrcList passed as the second argument
88012 ** to this function contains a single entry guaranteed to resolve to
88013 ** table pTab.
88014 **
88015 ** Normally, no code is required. However, if either
88016 **
88017 **   (a) The table is the parent table of a FK constraint, or
88018 **   (b) The table is the child table of a deferred FK constraint and it is
88019 **       determined at runtime that there are outstanding deferred FK 
88020 **       constraint violations in the database,
88021 **
88022 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
88023 ** the table from the database. Triggers are disabled while running this
88024 ** DELETE, but foreign key actions are not.
88025 */
88026 SQLCIPHER_PRIVATE void sqlcipher3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
88027   sqlcipher3 *db = pParse->db;
88028   if( (db->flags&SQLCIPHER_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
88029     int iSkip = 0;
88030     Vdbe *v = sqlcipher3GetVdbe(pParse);
88031
88032     assert( v );                  /* VDBE has already been allocated */
88033     if( sqlcipher3FkReferences(pTab)==0 ){
88034       /* Search for a deferred foreign key constraint for which this table
88035       ** is the child table. If one cannot be found, return without 
88036       ** generating any VDBE code. If one can be found, then jump over
88037       ** the entire DELETE if there are no outstanding deferred constraints
88038       ** when this statement is run.  */
88039       FKey *p;
88040       for(p=pTab->pFKey; p; p=p->pNextFrom){
88041         if( p->isDeferred ) break;
88042       }
88043       if( !p ) return;
88044       iSkip = sqlcipher3VdbeMakeLabel(v);
88045       sqlcipher3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
88046     }
88047
88048     pParse->disableTriggers = 1;
88049     sqlcipher3DeleteFrom(pParse, sqlcipher3SrcListDup(db, pName, 0), 0);
88050     pParse->disableTriggers = 0;
88051
88052     /* If the DELETE has generated immediate foreign key constraint 
88053     ** violations, halt the VDBE and return an error at this point, before
88054     ** any modifications to the schema are made. This is because statement
88055     ** transactions are not able to rollback schema changes.  */
88056     sqlcipher3VdbeAddOp2(v, OP_FkIfZero, 0, sqlcipher3VdbeCurrentAddr(v)+2);
88057     sqlcipher3HaltConstraint(
88058         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
88059     );
88060
88061     if( iSkip ){
88062       sqlcipher3VdbeResolveLabel(v, iSkip);
88063     }
88064   }
88065 }
88066
88067 /*
88068 ** This function is called when inserting, deleting or updating a row of
88069 ** table pTab to generate VDBE code to perform foreign key constraint 
88070 ** processing for the operation.
88071 **
88072 ** For a DELETE operation, parameter regOld is passed the index of the
88073 ** first register in an array of (pTab->nCol+1) registers containing the
88074 ** rowid of the row being deleted, followed by each of the column values
88075 ** of the row being deleted, from left to right. Parameter regNew is passed
88076 ** zero in this case.
88077 **
88078 ** For an INSERT operation, regOld is passed zero and regNew is passed the
88079 ** first register of an array of (pTab->nCol+1) registers containing the new
88080 ** row data.
88081 **
88082 ** For an UPDATE operation, this function is called twice. Once before
88083 ** the original record is deleted from the table using the calling convention
88084 ** described for DELETE. Then again after the original record is deleted
88085 ** but before the new record is inserted using the INSERT convention. 
88086 */
88087 SQLCIPHER_PRIVATE void sqlcipher3FkCheck(
88088   Parse *pParse,                  /* Parse context */
88089   Table *pTab,                    /* Row is being deleted from this table */ 
88090   int regOld,                     /* Previous row data is stored here */
88091   int regNew                      /* New row data is stored here */
88092 ){
88093   sqlcipher3 *db = pParse->db;       /* Database handle */
88094   FKey *pFKey;                    /* Used to iterate through FKs */
88095   int iDb;                        /* Index of database containing pTab */
88096   const char *zDb;                /* Name of database containing pTab */
88097   int isIgnoreErrors = pParse->disableTriggers;
88098
88099   /* Exactly one of regOld and regNew should be non-zero. */
88100   assert( (regOld==0)!=(regNew==0) );
88101
88102   /* If foreign-keys are disabled, this function is a no-op. */
88103   if( (db->flags&SQLCIPHER_ForeignKeys)==0 ) return;
88104
88105   iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
88106   zDb = db->aDb[iDb].zName;
88107
88108   /* Loop through all the foreign key constraints for which pTab is the
88109   ** child table (the table that the foreign key definition is part of).  */
88110   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
88111     Table *pTo;                   /* Parent table of foreign key pFKey */
88112     Index *pIdx = 0;              /* Index on key columns in pTo */
88113     int *aiFree = 0;
88114     int *aiCol;
88115     int iCol;
88116     int i;
88117     int isIgnore = 0;
88118
88119     /* Find the parent table of this foreign key. Also find a unique index 
88120     ** on the parent key columns in the parent table. If either of these 
88121     ** schema items cannot be located, set an error in pParse and return 
88122     ** early.  */
88123     if( pParse->disableTriggers ){
88124       pTo = sqlcipher3FindTable(db, pFKey->zTo, zDb);
88125     }else{
88126       pTo = sqlcipher3LocateTable(pParse, 0, pFKey->zTo, zDb);
88127     }
88128     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
88129       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
88130       if( !isIgnoreErrors || db->mallocFailed ) return;
88131       if( pTo==0 ){
88132         /* If isIgnoreErrors is true, then a table is being dropped. In this
88133         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
88134         ** before actually dropping it in order to check FK constraints.
88135         ** If the parent table of an FK constraint on the current table is
88136         ** missing, behave as if it is empty. i.e. decrement the relevant
88137         ** FK counter for each row of the current table with non-NULL keys.
88138         */
88139         Vdbe *v = sqlcipher3GetVdbe(pParse);
88140         int iJump = sqlcipher3VdbeCurrentAddr(v) + pFKey->nCol + 1;
88141         for(i=0; i<pFKey->nCol; i++){
88142           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
88143           sqlcipher3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
88144         }
88145         sqlcipher3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
88146       }
88147       continue;
88148     }
88149     assert( pFKey->nCol==1 || (aiFree && pIdx) );
88150
88151     if( aiFree ){
88152       aiCol = aiFree;
88153     }else{
88154       iCol = pFKey->aCol[0].iFrom;
88155       aiCol = &iCol;
88156     }
88157     for(i=0; i<pFKey->nCol; i++){
88158       if( aiCol[i]==pTab->iPKey ){
88159         aiCol[i] = -1;
88160       }
88161 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
88162       /* Request permission to read the parent key columns. If the 
88163       ** authorization callback returns SQLCIPHER_IGNORE, behave as if any
88164       ** values read from the parent table are NULL. */
88165       if( db->xAuth ){
88166         int rcauth;
88167         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
88168         rcauth = sqlcipher3AuthReadCol(pParse, pTo->zName, zCol, iDb);
88169         isIgnore = (rcauth==SQLCIPHER_IGNORE);
88170       }
88171 #endif
88172     }
88173
88174     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
88175     ** a cursor to use to search the unique index on the parent key columns 
88176     ** in the parent table.  */
88177     sqlcipher3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
88178     pParse->nTab++;
88179
88180     if( regOld!=0 ){
88181       /* A row is being removed from the child table. Search for the parent.
88182       ** If the parent does not exist, removing the child row resolves an 
88183       ** outstanding foreign key constraint violation. */
88184       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
88185     }
88186     if( regNew!=0 ){
88187       /* A row is being added to the child table. If a parent row cannot
88188       ** be found, adding the child row has violated the FK constraint. */ 
88189       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
88190     }
88191
88192     sqlcipher3DbFree(db, aiFree);
88193   }
88194
88195   /* Loop through all the foreign key constraints that refer to this table */
88196   for(pFKey = sqlcipher3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88197     Index *pIdx = 0;              /* Foreign key index for pFKey */
88198     SrcList *pSrc;
88199     int *aiCol = 0;
88200
88201     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
88202       assert( regOld==0 && regNew!=0 );
88203       /* Inserting a single row into a parent table cannot cause an immediate
88204       ** foreign key violation. So do nothing in this case.  */
88205       continue;
88206     }
88207
88208     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
88209       if( !isIgnoreErrors || db->mallocFailed ) return;
88210       continue;
88211     }
88212     assert( aiCol || pFKey->nCol==1 );
88213
88214     /* Create a SrcList structure containing a single table (the table 
88215     ** the foreign key that refers to this table is attached to). This
88216     ** is required for the sqlcipher3WhereXXX() interface.  */
88217     pSrc = sqlcipher3SrcListAppend(db, 0, 0, 0);
88218     if( pSrc ){
88219       struct SrcList_item *pItem = pSrc->a;
88220       pItem->pTab = pFKey->pFrom;
88221       pItem->zName = pFKey->pFrom->zName;
88222       pItem->pTab->nRef++;
88223       pItem->iCursor = pParse->nTab++;
88224   
88225       if( regNew!=0 ){
88226         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
88227       }
88228       if( regOld!=0 ){
88229         /* If there is a RESTRICT action configured for the current operation
88230         ** on the parent table of this FK, then throw an exception 
88231         ** immediately if the FK constraint is violated, even if this is a
88232         ** deferred trigger. That's what RESTRICT means. To defer checking
88233         ** the constraint, the FK should specify NO ACTION (represented
88234         ** using OE_None). NO ACTION is the default.  */
88235         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
88236       }
88237       pItem->zName = 0;
88238       sqlcipher3SrcListDelete(db, pSrc);
88239     }
88240     sqlcipher3DbFree(db, aiCol);
88241   }
88242 }
88243
88244 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
88245
88246 /*
88247 ** This function is called before generating code to update or delete a 
88248 ** row contained in table pTab.
88249 */
88250 SQLCIPHER_PRIVATE u32 sqlcipher3FkOldmask(
88251   Parse *pParse,                  /* Parse context */
88252   Table *pTab                     /* Table being modified */
88253 ){
88254   u32 mask = 0;
88255   if( pParse->db->flags&SQLCIPHER_ForeignKeys ){
88256     FKey *p;
88257     int i;
88258     for(p=pTab->pFKey; p; p=p->pNextFrom){
88259       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
88260     }
88261     for(p=sqlcipher3FkReferences(pTab); p; p=p->pNextTo){
88262       Index *pIdx = 0;
88263       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
88264       if( pIdx ){
88265         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
88266       }
88267     }
88268   }
88269   return mask;
88270 }
88271
88272 /*
88273 ** This function is called before generating code to update or delete a 
88274 ** row contained in table pTab. If the operation is a DELETE, then
88275 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
88276 ** to an array of size N, where N is the number of columns in table pTab.
88277 ** If the i'th column is not modified by the UPDATE, then the corresponding 
88278 ** entry in the aChange[] array is set to -1. If the column is modified,
88279 ** the value is 0 or greater. Parameter chngRowid is set to true if the
88280 ** UPDATE statement modifies the rowid fields of the table.
88281 **
88282 ** If any foreign key processing will be required, this function returns
88283 ** true. If there is no foreign key related processing, this function 
88284 ** returns false.
88285 */
88286 SQLCIPHER_PRIVATE int sqlcipher3FkRequired(
88287   Parse *pParse,                  /* Parse context */
88288   Table *pTab,                    /* Table being modified */
88289   int *aChange,                   /* Non-NULL for UPDATE operations */
88290   int chngRowid                   /* True for UPDATE that affects rowid */
88291 ){
88292   if( pParse->db->flags&SQLCIPHER_ForeignKeys ){
88293     if( !aChange ){
88294       /* A DELETE operation. Foreign key processing is required if the 
88295       ** table in question is either the child or parent table for any 
88296       ** foreign key constraint.  */
88297       return (sqlcipher3FkReferences(pTab) || pTab->pFKey);
88298     }else{
88299       /* This is an UPDATE. Foreign key processing is only required if the
88300       ** operation modifies one or more child or parent key columns. */
88301       int i;
88302       FKey *p;
88303
88304       /* Check if any child key columns are being modified. */
88305       for(p=pTab->pFKey; p; p=p->pNextFrom){
88306         for(i=0; i<p->nCol; i++){
88307           int iChildKey = p->aCol[i].iFrom;
88308           if( aChange[iChildKey]>=0 ) return 1;
88309           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
88310         }
88311       }
88312
88313       /* Check if any parent key columns are being modified. */
88314       for(p=sqlcipher3FkReferences(pTab); p; p=p->pNextTo){
88315         for(i=0; i<p->nCol; i++){
88316           char *zKey = p->aCol[i].zCol;
88317           int iKey;
88318           for(iKey=0; iKey<pTab->nCol; iKey++){
88319             Column *pCol = &pTab->aCol[iKey];
88320             if( (zKey ? !sqlcipher3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
88321               if( aChange[iKey]>=0 ) return 1;
88322               if( iKey==pTab->iPKey && chngRowid ) return 1;
88323             }
88324           }
88325         }
88326       }
88327     }
88328   }
88329   return 0;
88330 }
88331
88332 /*
88333 ** This function is called when an UPDATE or DELETE operation is being 
88334 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
88335 ** If the current operation is an UPDATE, then the pChanges parameter is
88336 ** passed a pointer to the list of columns being modified. If it is a
88337 ** DELETE, pChanges is passed a NULL pointer.
88338 **
88339 ** It returns a pointer to a Trigger structure containing a trigger
88340 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
88341 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
88342 ** returned (these actions require no special handling by the triggers
88343 ** sub-system, code for them is created by fkScanChildren()).
88344 **
88345 ** For example, if pFKey is the foreign key and pTab is table "p" in 
88346 ** the following schema:
88347 **
88348 **   CREATE TABLE p(pk PRIMARY KEY);
88349 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
88350 **
88351 ** then the returned trigger structure is equivalent to:
88352 **
88353 **   CREATE TRIGGER ... DELETE ON p BEGIN
88354 **     DELETE FROM c WHERE ck = old.pk;
88355 **   END;
88356 **
88357 ** The returned pointer is cached as part of the foreign key object. It
88358 ** is eventually freed along with the rest of the foreign key object by 
88359 ** sqlcipher3FkDelete().
88360 */
88361 static Trigger *fkActionTrigger(
88362   Parse *pParse,                  /* Parse context */
88363   Table *pTab,                    /* Table being updated or deleted from */
88364   FKey *pFKey,                    /* Foreign key to get action for */
88365   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
88366 ){
88367   sqlcipher3 *db = pParse->db;       /* Database handle */
88368   int action;                     /* One of OE_None, OE_Cascade etc. */
88369   Trigger *pTrigger;              /* Trigger definition to return */
88370   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
88371
88372   action = pFKey->aAction[iAction];
88373   pTrigger = pFKey->apTrigger[iAction];
88374
88375   if( action!=OE_None && !pTrigger ){
88376     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
88377     char const *zFrom;            /* Name of child table */
88378     int nFrom;                    /* Length in bytes of zFrom */
88379     Index *pIdx = 0;              /* Parent key index for this FK */
88380     int *aiCol = 0;               /* child table cols -> parent key cols */
88381     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
88382     Expr *pWhere = 0;             /* WHERE clause of trigger step */
88383     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
88384     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
88385     int i;                        /* Iterator variable */
88386     Expr *pWhen = 0;              /* WHEN clause for the trigger */
88387
88388     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
88389     assert( aiCol || pFKey->nCol==1 );
88390
88391     for(i=0; i<pFKey->nCol; i++){
88392       Token tOld = { "old", 3 };  /* Literal "old" token */
88393       Token tNew = { "new", 3 };  /* Literal "new" token */
88394       Token tFromCol;             /* Name of column in child table */
88395       Token tToCol;               /* Name of column in parent table */
88396       int iFromCol;               /* Idx of column in child table */
88397       Expr *pEq;                  /* tFromCol = OLD.tToCol */
88398
88399       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
88400       assert( iFromCol>=0 );
88401       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
88402       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
88403
88404       tToCol.n = sqlcipher3Strlen30(tToCol.z);
88405       tFromCol.n = sqlcipher3Strlen30(tFromCol.z);
88406
88407       /* Create the expression "OLD.zToCol = zFromCol". It is important
88408       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
88409       ** that the affinity and collation sequence associated with the
88410       ** parent table are used for the comparison. */
88411       pEq = sqlcipher3PExpr(pParse, TK_EQ,
88412           sqlcipher3PExpr(pParse, TK_DOT, 
88413             sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tOld),
88414             sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88415           , 0),
88416           sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
88417       , 0);
88418       pWhere = sqlcipher3ExprAnd(db, pWhere, pEq);
88419
88420       /* For ON UPDATE, construct the next term of the WHEN clause.
88421       ** The final WHEN clause will be like this:
88422       **
88423       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
88424       */
88425       if( pChanges ){
88426         pEq = sqlcipher3PExpr(pParse, TK_IS,
88427             sqlcipher3PExpr(pParse, TK_DOT, 
88428               sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tOld),
88429               sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88430               0),
88431             sqlcipher3PExpr(pParse, TK_DOT, 
88432               sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tNew),
88433               sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88434               0),
88435             0);
88436         pWhen = sqlcipher3ExprAnd(db, pWhen, pEq);
88437       }
88438   
88439       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
88440         Expr *pNew;
88441         if( action==OE_Cascade ){
88442           pNew = sqlcipher3PExpr(pParse, TK_DOT, 
88443             sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tNew),
88444             sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88445           , 0);
88446         }else if( action==OE_SetDflt ){
88447           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
88448           if( pDflt ){
88449             pNew = sqlcipher3ExprDup(db, pDflt, 0);
88450           }else{
88451             pNew = sqlcipher3PExpr(pParse, TK_NULL, 0, 0, 0);
88452           }
88453         }else{
88454           pNew = sqlcipher3PExpr(pParse, TK_NULL, 0, 0, 0);
88455         }
88456         pList = sqlcipher3ExprListAppend(pParse, pList, pNew);
88457         sqlcipher3ExprListSetName(pParse, pList, &tFromCol, 0);
88458       }
88459     }
88460     sqlcipher3DbFree(db, aiCol);
88461
88462     zFrom = pFKey->pFrom->zName;
88463     nFrom = sqlcipher3Strlen30(zFrom);
88464
88465     if( action==OE_Restrict ){
88466       Token tFrom;
88467       Expr *pRaise; 
88468
88469       tFrom.z = zFrom;
88470       tFrom.n = nFrom;
88471       pRaise = sqlcipher3Expr(db, TK_RAISE, "foreign key constraint failed");
88472       if( pRaise ){
88473         pRaise->affinity = OE_Abort;
88474       }
88475       pSelect = sqlcipher3SelectNew(pParse, 
88476           sqlcipher3ExprListAppend(pParse, 0, pRaise),
88477           sqlcipher3SrcListAppend(db, 0, &tFrom, 0),
88478           pWhere,
88479           0, 0, 0, 0, 0, 0
88480       );
88481       pWhere = 0;
88482     }
88483
88484     /* Disable lookaside memory allocation */
88485     enableLookaside = db->lookaside.bEnabled;
88486     db->lookaside.bEnabled = 0;
88487
88488     pTrigger = (Trigger *)sqlcipher3DbMallocZero(db, 
88489         sizeof(Trigger) +         /* struct Trigger */
88490         sizeof(TriggerStep) +     /* Single step in trigger program */
88491         nFrom + 1                 /* Space for pStep->target.z */
88492     );
88493     if( pTrigger ){
88494       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
88495       pStep->target.z = (char *)&pStep[1];
88496       pStep->target.n = nFrom;
88497       memcpy((char *)pStep->target.z, zFrom, nFrom);
88498   
88499       pStep->pWhere = sqlcipher3ExprDup(db, pWhere, EXPRDUP_REDUCE);
88500       pStep->pExprList = sqlcipher3ExprListDup(db, pList, EXPRDUP_REDUCE);
88501       pStep->pSelect = sqlcipher3SelectDup(db, pSelect, EXPRDUP_REDUCE);
88502       if( pWhen ){
88503         pWhen = sqlcipher3PExpr(pParse, TK_NOT, pWhen, 0, 0);
88504         pTrigger->pWhen = sqlcipher3ExprDup(db, pWhen, EXPRDUP_REDUCE);
88505       }
88506     }
88507
88508     /* Re-enable the lookaside buffer, if it was disabled earlier. */
88509     db->lookaside.bEnabled = enableLookaside;
88510
88511     sqlcipher3ExprDelete(db, pWhere);
88512     sqlcipher3ExprDelete(db, pWhen);
88513     sqlcipher3ExprListDelete(db, pList);
88514     sqlcipher3SelectDelete(db, pSelect);
88515     if( db->mallocFailed==1 ){
88516       fkTriggerDelete(db, pTrigger);
88517       return 0;
88518     }
88519     assert( pStep!=0 );
88520
88521     switch( action ){
88522       case OE_Restrict:
88523         pStep->op = TK_SELECT; 
88524         break;
88525       case OE_Cascade: 
88526         if( !pChanges ){ 
88527           pStep->op = TK_DELETE; 
88528           break; 
88529         }
88530       default:
88531         pStep->op = TK_UPDATE;
88532     }
88533     pStep->pTrig = pTrigger;
88534     pTrigger->pSchema = pTab->pSchema;
88535     pTrigger->pTabSchema = pTab->pSchema;
88536     pFKey->apTrigger[iAction] = pTrigger;
88537     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
88538   }
88539
88540   return pTrigger;
88541 }
88542
88543 /*
88544 ** This function is called when deleting or updating a row to implement
88545 ** any required CASCADE, SET NULL or SET DEFAULT actions.
88546 */
88547 SQLCIPHER_PRIVATE void sqlcipher3FkActions(
88548   Parse *pParse,                  /* Parse context */
88549   Table *pTab,                    /* Table being updated or deleted from */
88550   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
88551   int regOld                      /* Address of array containing old row */
88552 ){
88553   /* If foreign-key support is enabled, iterate through all FKs that 
88554   ** refer to table pTab. If there is an action associated with the FK 
88555   ** for this operation (either update or delete), invoke the associated 
88556   ** trigger sub-program.  */
88557   if( pParse->db->flags&SQLCIPHER_ForeignKeys ){
88558     FKey *pFKey;                  /* Iterator variable */
88559     for(pFKey = sqlcipher3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88560       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
88561       if( pAction ){
88562         sqlcipher3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
88563       }
88564     }
88565   }
88566 }
88567
88568 #endif /* ifndef SQLCIPHER_OMIT_TRIGGER */
88569
88570 /*
88571 ** Free all memory associated with foreign key definitions attached to
88572 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
88573 ** hash table.
88574 */
88575 SQLCIPHER_PRIVATE void sqlcipher3FkDelete(sqlcipher3 *db, Table *pTab){
88576   FKey *pFKey;                    /* Iterator variable */
88577   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
88578
88579   assert( db==0 || sqlcipher3SchemaMutexHeld(db, 0, pTab->pSchema) );
88580   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
88581
88582     /* Remove the FK from the fkeyHash hash table. */
88583     if( !db || db->pnBytesFreed==0 ){
88584       if( pFKey->pPrevTo ){
88585         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
88586       }else{
88587         void *p = (void *)pFKey->pNextTo;
88588         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
88589         sqlcipher3HashInsert(&pTab->pSchema->fkeyHash, z, sqlcipher3Strlen30(z), p);
88590       }
88591       if( pFKey->pNextTo ){
88592         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
88593       }
88594     }
88595
88596     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
88597     ** classified as either immediate or deferred.
88598     */
88599     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
88600
88601     /* Delete any triggers created to implement actions for this FK. */
88602 #ifndef SQLCIPHER_OMIT_TRIGGER
88603     fkTriggerDelete(db, pFKey->apTrigger[0]);
88604     fkTriggerDelete(db, pFKey->apTrigger[1]);
88605 #endif
88606
88607     pNext = pFKey->pNextFrom;
88608     sqlcipher3DbFree(db, pFKey);
88609   }
88610 }
88611 #endif /* ifndef SQLCIPHER_OMIT_FOREIGN_KEY */
88612
88613 /************** End of fkey.c ************************************************/
88614 /************** Begin file insert.c ******************************************/
88615 /*
88616 ** 2001 September 15
88617 **
88618 ** The author disclaims copyright to this source code.  In place of
88619 ** a legal notice, here is a blessing:
88620 **
88621 **    May you do good and not evil.
88622 **    May you find forgiveness for yourself and forgive others.
88623 **    May you share freely, never taking more than you give.
88624 **
88625 *************************************************************************
88626 ** This file contains C code routines that are called by the parser
88627 ** to handle INSERT statements in SQLite.
88628 */
88629
88630 /*
88631 ** Generate code that will open a table for reading.
88632 */
88633 SQLCIPHER_PRIVATE void sqlcipher3OpenTable(
88634   Parse *p,       /* Generate code into this VDBE */
88635   int iCur,       /* The cursor number of the table */
88636   int iDb,        /* The database index in sqlcipher3.aDb[] */
88637   Table *pTab,    /* The table to be opened */
88638   int opcode      /* OP_OpenRead or OP_OpenWrite */
88639 ){
88640   Vdbe *v;
88641   if( IsVirtual(pTab) ) return;
88642   v = sqlcipher3GetVdbe(p);
88643   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
88644   sqlcipher3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
88645   sqlcipher3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
88646   sqlcipher3VdbeChangeP4(v, -1, SQLCIPHER_INT_TO_PTR(pTab->nCol), P4_INT32);
88647   VdbeComment((v, "%s", pTab->zName));
88648 }
88649
88650 /*
88651 ** Return a pointer to the column affinity string associated with index
88652 ** pIdx. A column affinity string has one character for each column in 
88653 ** the table, according to the affinity of the column:
88654 **
88655 **  Character      Column affinity
88656 **  ------------------------------
88657 **  'a'            TEXT
88658 **  'b'            NONE
88659 **  'c'            NUMERIC
88660 **  'd'            INTEGER
88661 **  'e'            REAL
88662 **
88663 ** An extra 'b' is appended to the end of the string to cover the
88664 ** rowid that appears as the last column in every index.
88665 **
88666 ** Memory for the buffer containing the column index affinity string
88667 ** is managed along with the rest of the Index structure. It will be
88668 ** released when sqlcipher3DeleteIndex() is called.
88669 */
88670 SQLCIPHER_PRIVATE const char *sqlcipher3IndexAffinityStr(Vdbe *v, Index *pIdx){
88671   if( !pIdx->zColAff ){
88672     /* The first time a column affinity string for a particular index is
88673     ** required, it is allocated and populated here. It is then stored as
88674     ** a member of the Index structure for subsequent use.
88675     **
88676     ** The column affinity string will eventually be deleted by
88677     ** sqlcipherDeleteIndex() when the Index structure itself is cleaned
88678     ** up.
88679     */
88680     int n;
88681     Table *pTab = pIdx->pTable;
88682     sqlcipher3 *db = sqlcipher3VdbeDb(v);
88683     pIdx->zColAff = (char *)sqlcipher3DbMallocRaw(0, pIdx->nColumn+2);
88684     if( !pIdx->zColAff ){
88685       db->mallocFailed = 1;
88686       return 0;
88687     }
88688     for(n=0; n<pIdx->nColumn; n++){
88689       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
88690     }
88691     pIdx->zColAff[n++] = SQLCIPHER_AFF_NONE;
88692     pIdx->zColAff[n] = 0;
88693   }
88694  
88695   return pIdx->zColAff;
88696 }
88697
88698 /*
88699 ** Set P4 of the most recently inserted opcode to a column affinity
88700 ** string for table pTab. A column affinity string has one character
88701 ** for each column indexed by the index, according to the affinity of the
88702 ** column:
88703 **
88704 **  Character      Column affinity
88705 **  ------------------------------
88706 **  'a'            TEXT
88707 **  'b'            NONE
88708 **  'c'            NUMERIC
88709 **  'd'            INTEGER
88710 **  'e'            REAL
88711 */
88712 SQLCIPHER_PRIVATE void sqlcipher3TableAffinityStr(Vdbe *v, Table *pTab){
88713   /* The first time a column affinity string for a particular table
88714   ** is required, it is allocated and populated here. It is then 
88715   ** stored as a member of the Table structure for subsequent use.
88716   **
88717   ** The column affinity string will eventually be deleted by
88718   ** sqlcipher3DeleteTable() when the Table structure itself is cleaned up.
88719   */
88720   if( !pTab->zColAff ){
88721     char *zColAff;
88722     int i;
88723     sqlcipher3 *db = sqlcipher3VdbeDb(v);
88724
88725     zColAff = (char *)sqlcipher3DbMallocRaw(0, pTab->nCol+1);
88726     if( !zColAff ){
88727       db->mallocFailed = 1;
88728       return;
88729     }
88730
88731     for(i=0; i<pTab->nCol; i++){
88732       zColAff[i] = pTab->aCol[i].affinity;
88733     }
88734     zColAff[pTab->nCol] = '\0';
88735
88736     pTab->zColAff = zColAff;
88737   }
88738
88739   sqlcipher3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
88740 }
88741
88742 /*
88743 ** Return non-zero if the table pTab in database iDb or any of its indices
88744 ** have been opened at any point in the VDBE program beginning at location
88745 ** iStartAddr throught the end of the program.  This is used to see if 
88746 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
88747 ** run without using temporary table for the results of the SELECT. 
88748 */
88749 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
88750   Vdbe *v = sqlcipher3GetVdbe(p);
88751   int i;
88752   int iEnd = sqlcipher3VdbeCurrentAddr(v);
88753 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
88754   VTable *pVTab = IsVirtual(pTab) ? sqlcipher3GetVTable(p->db, pTab) : 0;
88755 #endif
88756
88757   for(i=iStartAddr; i<iEnd; i++){
88758     VdbeOp *pOp = sqlcipher3VdbeGetOp(v, i);
88759     assert( pOp!=0 );
88760     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
88761       Index *pIndex;
88762       int tnum = pOp->p2;
88763       if( tnum==pTab->tnum ){
88764         return 1;
88765       }
88766       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
88767         if( tnum==pIndex->tnum ){
88768           return 1;
88769         }
88770       }
88771     }
88772 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
88773     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
88774       assert( pOp->p4.pVtab!=0 );
88775       assert( pOp->p4type==P4_VTAB );
88776       return 1;
88777     }
88778 #endif
88779   }
88780   return 0;
88781 }
88782
88783 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
88784 /*
88785 ** Locate or create an AutoincInfo structure associated with table pTab
88786 ** which is in database iDb.  Return the register number for the register
88787 ** that holds the maximum rowid.
88788 **
88789 ** There is at most one AutoincInfo structure per table even if the
88790 ** same table is autoincremented multiple times due to inserts within
88791 ** triggers.  A new AutoincInfo structure is created if this is the
88792 ** first use of table pTab.  On 2nd and subsequent uses, the original
88793 ** AutoincInfo structure is used.
88794 **
88795 ** Three memory locations are allocated:
88796 **
88797 **   (1)  Register to hold the name of the pTab table.
88798 **   (2)  Register to hold the maximum ROWID of pTab.
88799 **   (3)  Register to hold the rowid in sqlcipher_sequence of pTab
88800 **
88801 ** The 2nd register is the one that is returned.  That is all the
88802 ** insert routine needs to know about.
88803 */
88804 static int autoIncBegin(
88805   Parse *pParse,      /* Parsing context */
88806   int iDb,            /* Index of the database holding pTab */
88807   Table *pTab         /* The table we are writing to */
88808 ){
88809   int memId = 0;      /* Register holding maximum rowid */
88810   if( pTab->tabFlags & TF_Autoincrement ){
88811     Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
88812     AutoincInfo *pInfo;
88813
88814     pInfo = pToplevel->pAinc;
88815     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
88816     if( pInfo==0 ){
88817       pInfo = sqlcipher3DbMallocRaw(pParse->db, sizeof(*pInfo));
88818       if( pInfo==0 ) return 0;
88819       pInfo->pNext = pToplevel->pAinc;
88820       pToplevel->pAinc = pInfo;
88821       pInfo->pTab = pTab;
88822       pInfo->iDb = iDb;
88823       pToplevel->nMem++;                  /* Register to hold name of table */
88824       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
88825       pToplevel->nMem++;                  /* Rowid in sqlcipher_sequence */
88826     }
88827     memId = pInfo->regCtr;
88828   }
88829   return memId;
88830 }
88831
88832 /*
88833 ** This routine generates code that will initialize all of the
88834 ** register used by the autoincrement tracker.  
88835 */
88836 SQLCIPHER_PRIVATE void sqlcipher3AutoincrementBegin(Parse *pParse){
88837   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
88838   sqlcipher3 *db = pParse->db;  /* The database connection */
88839   Db *pDb;                   /* Database only autoinc table */
88840   int memId;                 /* Register holding max rowid */
88841   int addr;                  /* A VDBE address */
88842   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
88843
88844   /* This routine is never called during trigger-generation.  It is
88845   ** only called from the top-level */
88846   assert( pParse->pTriggerTab==0 );
88847   assert( pParse==sqlcipher3ParseToplevel(pParse) );
88848
88849   assert( v );   /* We failed long ago if this is not so */
88850   for(p = pParse->pAinc; p; p = p->pNext){
88851     pDb = &db->aDb[p->iDb];
88852     memId = p->regCtr;
88853     assert( sqlcipher3SchemaMutexHeld(db, 0, pDb->pSchema) );
88854     sqlcipher3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
88855     addr = sqlcipher3VdbeCurrentAddr(v);
88856     sqlcipher3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
88857     sqlcipher3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
88858     sqlcipher3VdbeAddOp3(v, OP_Column, 0, 0, memId);
88859     sqlcipher3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
88860     sqlcipher3VdbeChangeP5(v, SQLCIPHER_JUMPIFNULL);
88861     sqlcipher3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
88862     sqlcipher3VdbeAddOp3(v, OP_Column, 0, 1, memId);
88863     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addr+9);
88864     sqlcipher3VdbeAddOp2(v, OP_Next, 0, addr+2);
88865     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, memId);
88866     sqlcipher3VdbeAddOp0(v, OP_Close);
88867   }
88868 }
88869
88870 /*
88871 ** Update the maximum rowid for an autoincrement calculation.
88872 **
88873 ** This routine should be called when the top of the stack holds a
88874 ** new rowid that is about to be inserted.  If that new rowid is
88875 ** larger than the maximum rowid in the memId memory cell, then the
88876 ** memory cell is updated.  The stack is unchanged.
88877 */
88878 static void autoIncStep(Parse *pParse, int memId, int regRowid){
88879   if( memId>0 ){
88880     sqlcipher3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
88881   }
88882 }
88883
88884 /*
88885 ** This routine generates the code needed to write autoincrement
88886 ** maximum rowid values back into the sqlcipher_sequence register.
88887 ** Every statement that might do an INSERT into an autoincrement
88888 ** table (either directly or through triggers) needs to call this
88889 ** routine just before the "exit" code.
88890 */
88891 SQLCIPHER_PRIVATE void sqlcipher3AutoincrementEnd(Parse *pParse){
88892   AutoincInfo *p;
88893   Vdbe *v = pParse->pVdbe;
88894   sqlcipher3 *db = pParse->db;
88895
88896   assert( v );
88897   for(p = pParse->pAinc; p; p = p->pNext){
88898     Db *pDb = &db->aDb[p->iDb];
88899     int j1, j2, j3, j4, j5;
88900     int iRec;
88901     int memId = p->regCtr;
88902
88903     iRec = sqlcipher3GetTempReg(pParse);
88904     assert( sqlcipher3SchemaMutexHeld(db, 0, pDb->pSchema) );
88905     sqlcipher3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
88906     j1 = sqlcipher3VdbeAddOp1(v, OP_NotNull, memId+1);
88907     j2 = sqlcipher3VdbeAddOp0(v, OP_Rewind);
88908     j3 = sqlcipher3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
88909     j4 = sqlcipher3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
88910     sqlcipher3VdbeAddOp2(v, OP_Next, 0, j3);
88911     sqlcipher3VdbeJumpHere(v, j2);
88912     sqlcipher3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
88913     j5 = sqlcipher3VdbeAddOp0(v, OP_Goto);
88914     sqlcipher3VdbeJumpHere(v, j4);
88915     sqlcipher3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
88916     sqlcipher3VdbeJumpHere(v, j1);
88917     sqlcipher3VdbeJumpHere(v, j5);
88918     sqlcipher3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
88919     sqlcipher3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
88920     sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
88921     sqlcipher3VdbeAddOp0(v, OP_Close);
88922     sqlcipher3ReleaseTempReg(pParse, iRec);
88923   }
88924 }
88925 #else
88926 /*
88927 ** If SQLCIPHER_OMIT_AUTOINCREMENT is defined, then the three routines
88928 ** above are all no-ops
88929 */
88930 # define autoIncBegin(A,B,C) (0)
88931 # define autoIncStep(A,B,C)
88932 #endif /* SQLCIPHER_OMIT_AUTOINCREMENT */
88933
88934
88935 /* Forward declaration */
88936 static int xferOptimization(
88937   Parse *pParse,        /* Parser context */
88938   Table *pDest,         /* The table we are inserting into */
88939   Select *pSelect,      /* A SELECT statement to use as the data source */
88940   int onError,          /* How to handle constraint errors */
88941   int iDbDest           /* The database of pDest */
88942 );
88943
88944 /*
88945 ** This routine is call to handle SQL of the following forms:
88946 **
88947 **    insert into TABLE (IDLIST) values(EXPRLIST)
88948 **    insert into TABLE (IDLIST) select
88949 **
88950 ** The IDLIST following the table name is always optional.  If omitted,
88951 ** then a list of all columns for the table is substituted.  The IDLIST
88952 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
88953 **
88954 ** The pList parameter holds EXPRLIST in the first form of the INSERT
88955 ** statement above, and pSelect is NULL.  For the second form, pList is
88956 ** NULL and pSelect is a pointer to the select statement used to generate
88957 ** data for the insert.
88958 **
88959 ** The code generated follows one of four templates.  For a simple
88960 ** select with data coming from a VALUES clause, the code executes
88961 ** once straight down through.  Pseudo-code follows (we call this
88962 ** the "1st template"):
88963 **
88964 **         open write cursor to <table> and its indices
88965 **         puts VALUES clause expressions onto the stack
88966 **         write the resulting record into <table>
88967 **         cleanup
88968 **
88969 ** The three remaining templates assume the statement is of the form
88970 **
88971 **   INSERT INTO <table> SELECT ...
88972 **
88973 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
88974 ** in other words if the SELECT pulls all columns from a single table
88975 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
88976 ** if <table2> and <table1> are distinct tables but have identical
88977 ** schemas, including all the same indices, then a special optimization
88978 ** is invoked that copies raw records from <table2> over to <table1>.
88979 ** See the xferOptimization() function for the implementation of this
88980 ** template.  This is the 2nd template.
88981 **
88982 **         open a write cursor to <table>
88983 **         open read cursor on <table2>
88984 **         transfer all records in <table2> over to <table>
88985 **         close cursors
88986 **         foreach index on <table>
88987 **           open a write cursor on the <table> index
88988 **           open a read cursor on the corresponding <table2> index
88989 **           transfer all records from the read to the write cursors
88990 **           close cursors
88991 **         end foreach
88992 **
88993 ** The 3rd template is for when the second template does not apply
88994 ** and the SELECT clause does not read from <table> at any time.
88995 ** The generated code follows this template:
88996 **
88997 **         EOF <- 0
88998 **         X <- A
88999 **         goto B
89000 **      A: setup for the SELECT
89001 **         loop over the rows in the SELECT
89002 **           load values into registers R..R+n
89003 **           yield X
89004 **         end loop
89005 **         cleanup after the SELECT
89006 **         EOF <- 1
89007 **         yield X
89008 **         goto A
89009 **      B: open write cursor to <table> and its indices
89010 **      C: yield X
89011 **         if EOF goto D
89012 **         insert the select result into <table> from R..R+n
89013 **         goto C
89014 **      D: cleanup
89015 **
89016 ** The 4th template is used if the insert statement takes its
89017 ** values from a SELECT but the data is being inserted into a table
89018 ** that is also read as part of the SELECT.  In the third form,
89019 ** we have to use a intermediate table to store the results of
89020 ** the select.  The template is like this:
89021 **
89022 **         EOF <- 0
89023 **         X <- A
89024 **         goto B
89025 **      A: setup for the SELECT
89026 **         loop over the tables in the SELECT
89027 **           load value into register R..R+n
89028 **           yield X
89029 **         end loop
89030 **         cleanup after the SELECT
89031 **         EOF <- 1
89032 **         yield X
89033 **         halt-error
89034 **      B: open temp table
89035 **      L: yield X
89036 **         if EOF goto M
89037 **         insert row from R..R+n into temp table
89038 **         goto L
89039 **      M: open write cursor to <table> and its indices
89040 **         rewind temp table
89041 **      C: loop over rows of intermediate table
89042 **           transfer values form intermediate table into <table>
89043 **         end loop
89044 **      D: cleanup
89045 */
89046 SQLCIPHER_PRIVATE void sqlcipher3Insert(
89047   Parse *pParse,        /* Parser context */
89048   SrcList *pTabList,    /* Name of table into which we are inserting */
89049   ExprList *pList,      /* List of values to be inserted */
89050   Select *pSelect,      /* A SELECT statement to use as the data source */
89051   IdList *pColumn,      /* Column names corresponding to IDLIST. */
89052   int onError           /* How to handle constraint errors */
89053 ){
89054   sqlcipher3 *db;          /* The main database structure */
89055   Table *pTab;          /* The table to insert into.  aka TABLE */
89056   char *zTab;           /* Name of the table into which we are inserting */
89057   const char *zDb;      /* Name of the database holding this table */
89058   int i, j, idx;        /* Loop counters */
89059   Vdbe *v;              /* Generate code into this virtual machine */
89060   Index *pIdx;          /* For looping over indices of the table */
89061   int nColumn;          /* Number of columns in the data */
89062   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
89063   int baseCur = 0;      /* VDBE Cursor number for pTab */
89064   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
89065   int endOfLoop;        /* Label for the end of the insertion loop */
89066   int useTempTable = 0; /* Store SELECT results in intermediate table */
89067   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
89068   int addrInsTop = 0;   /* Jump to label "D" */
89069   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
89070   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
89071   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
89072   int iDb;              /* Index of database holding TABLE */
89073   Db *pDb;              /* The database containing table being inserted into */
89074   int appendFlag = 0;   /* True if the insert is likely to be an append */
89075
89076   /* Register allocations */
89077   int regFromSelect = 0;/* Base register for data coming from SELECT */
89078   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
89079   int regRowCount = 0;  /* Memory cell used for the row counter */
89080   int regIns;           /* Block of regs holding rowid+data being inserted */
89081   int regRowid;         /* registers holding insert rowid */
89082   int regData;          /* register holding first column to insert */
89083   int regEof = 0;       /* Register recording end of SELECT data */
89084   int *aRegIdx = 0;     /* One register allocated to each index */
89085
89086 #ifndef SQLCIPHER_OMIT_TRIGGER
89087   int isView;                 /* True if attempting to insert into a view */
89088   Trigger *pTrigger;          /* List of triggers on pTab, if required */
89089   int tmask;                  /* Mask of trigger times */
89090 #endif
89091
89092   db = pParse->db;
89093   memset(&dest, 0, sizeof(dest));
89094   if( pParse->nErr || db->mallocFailed ){
89095     goto insert_cleanup;
89096   }
89097
89098   /* Locate the table into which we will be inserting new information.
89099   */
89100   assert( pTabList->nSrc==1 );
89101   zTab = pTabList->a[0].zName;
89102   if( NEVER(zTab==0) ) goto insert_cleanup;
89103   pTab = sqlcipher3SrcListLookup(pParse, pTabList);
89104   if( pTab==0 ){
89105     goto insert_cleanup;
89106   }
89107   iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
89108   assert( iDb<db->nDb );
89109   pDb = &db->aDb[iDb];
89110   zDb = pDb->zName;
89111   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_INSERT, pTab->zName, 0, zDb) ){
89112     goto insert_cleanup;
89113   }
89114
89115   /* Figure out if we have any triggers and if the table being
89116   ** inserted into is a view
89117   */
89118 #ifndef SQLCIPHER_OMIT_TRIGGER
89119   pTrigger = sqlcipher3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
89120   isView = pTab->pSelect!=0;
89121 #else
89122 # define pTrigger 0
89123 # define tmask 0
89124 # define isView 0
89125 #endif
89126 #ifdef SQLCIPHER_OMIT_VIEW
89127 # undef isView
89128 # define isView 0
89129 #endif
89130   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
89131
89132   /* If pTab is really a view, make sure it has been initialized.
89133   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
89134   ** module table).
89135   */
89136   if( sqlcipher3ViewGetColumnNames(pParse, pTab) ){
89137     goto insert_cleanup;
89138   }
89139
89140   /* Ensure that:
89141   *  (a) the table is not read-only, 
89142   *  (b) that if it is a view then ON INSERT triggers exist
89143   */
89144   if( sqlcipher3IsReadOnly(pParse, pTab, tmask) ){
89145     goto insert_cleanup;
89146   }
89147
89148   /* Allocate a VDBE
89149   */
89150   v = sqlcipher3GetVdbe(pParse);
89151   if( v==0 ) goto insert_cleanup;
89152   if( pParse->nested==0 ) sqlcipher3VdbeCountChanges(v);
89153   sqlcipher3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
89154
89155 #ifndef SQLCIPHER_OMIT_XFER_OPT
89156   /* If the statement is of the form
89157   **
89158   **       INSERT INTO <table1> SELECT * FROM <table2>;
89159   **
89160   ** Then special optimizations can be applied that make the transfer
89161   ** very fast and which reduce fragmentation of indices.
89162   **
89163   ** This is the 2nd template.
89164   */
89165   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
89166     assert( !pTrigger );
89167     assert( pList==0 );
89168     goto insert_end;
89169   }
89170 #endif /* SQLCIPHER_OMIT_XFER_OPT */
89171
89172   /* If this is an AUTOINCREMENT table, look up the sequence number in the
89173   ** sqlcipher_sequence table and store it in memory cell regAutoinc.
89174   */
89175   regAutoinc = autoIncBegin(pParse, iDb, pTab);
89176
89177   /* Figure out how many columns of data are supplied.  If the data
89178   ** is coming from a SELECT statement, then generate a co-routine that
89179   ** produces a single row of the SELECT on each invocation.  The
89180   ** co-routine is the common header to the 3rd and 4th templates.
89181   */
89182   if( pSelect ){
89183     /* Data is coming from a SELECT.  Generate code to implement that SELECT
89184     ** as a co-routine.  The code is common to both the 3rd and 4th
89185     ** templates:
89186     **
89187     **         EOF <- 0
89188     **         X <- A
89189     **         goto B
89190     **      A: setup for the SELECT
89191     **         loop over the tables in the SELECT
89192     **           load value into register R..R+n
89193     **           yield X
89194     **         end loop
89195     **         cleanup after the SELECT
89196     **         EOF <- 1
89197     **         yield X
89198     **         halt-error
89199     **
89200     ** On each invocation of the co-routine, it puts a single row of the
89201     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
89202     ** (These output registers are allocated by sqlcipher3Select().)  When
89203     ** the SELECT completes, it sets the EOF flag stored in regEof.
89204     */
89205     int rc, j1;
89206
89207     regEof = ++pParse->nMem;
89208     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
89209     VdbeComment((v, "SELECT eof flag"));
89210     sqlcipher3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
89211     addrSelect = sqlcipher3VdbeCurrentAddr(v)+2;
89212     sqlcipher3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
89213     j1 = sqlcipher3VdbeAddOp2(v, OP_Goto, 0, 0);
89214     VdbeComment((v, "Jump over SELECT coroutine"));
89215
89216     /* Resolve the expressions in the SELECT statement and execute it. */
89217     rc = sqlcipher3Select(pParse, pSelect, &dest);
89218     assert( pParse->nErr==0 || rc );
89219     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
89220       goto insert_cleanup;
89221     }
89222     sqlcipher3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
89223     sqlcipher3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
89224     sqlcipher3VdbeAddOp2(v, OP_Halt, SQLCIPHER_INTERNAL, OE_Abort);
89225     VdbeComment((v, "End of SELECT coroutine"));
89226     sqlcipher3VdbeJumpHere(v, j1);                          /* label B: */
89227
89228     regFromSelect = dest.iMem;
89229     assert( pSelect->pEList );
89230     nColumn = pSelect->pEList->nExpr;
89231     assert( dest.nMem==nColumn );
89232
89233     /* Set useTempTable to TRUE if the result of the SELECT statement
89234     ** should be written into a temporary table (template 4).  Set to
89235     ** FALSE if each* row of the SELECT can be written directly into
89236     ** the destination table (template 3).
89237     **
89238     ** A temp table must be used if the table being updated is also one
89239     ** of the tables being read by the SELECT statement.  Also use a 
89240     ** temp table in the case of row triggers.
89241     */
89242     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
89243       useTempTable = 1;
89244     }
89245
89246     if( useTempTable ){
89247       /* Invoke the coroutine to extract information from the SELECT
89248       ** and add it to a transient table srcTab.  The code generated
89249       ** here is from the 4th template:
89250       **
89251       **      B: open temp table
89252       **      L: yield X
89253       **         if EOF goto M
89254       **         insert row from R..R+n into temp table
89255       **         goto L
89256       **      M: ...
89257       */
89258       int regRec;          /* Register to hold packed record */
89259       int regTempRowid;    /* Register to hold temp table ROWID */
89260       int addrTop;         /* Label "L" */
89261       int addrIf;          /* Address of jump to M */
89262
89263       srcTab = pParse->nTab++;
89264       regRec = sqlcipher3GetTempReg(pParse);
89265       regTempRowid = sqlcipher3GetTempReg(pParse);
89266       sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
89267       addrTop = sqlcipher3VdbeAddOp1(v, OP_Yield, dest.iParm);
89268       addrIf = sqlcipher3VdbeAddOp1(v, OP_If, regEof);
89269       sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
89270       sqlcipher3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
89271       sqlcipher3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
89272       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addrTop);
89273       sqlcipher3VdbeJumpHere(v, addrIf);
89274       sqlcipher3ReleaseTempReg(pParse, regRec);
89275       sqlcipher3ReleaseTempReg(pParse, regTempRowid);
89276     }
89277   }else{
89278     /* This is the case if the data for the INSERT is coming from a VALUES
89279     ** clause
89280     */
89281     NameContext sNC;
89282     memset(&sNC, 0, sizeof(sNC));
89283     sNC.pParse = pParse;
89284     srcTab = -1;
89285     assert( useTempTable==0 );
89286     nColumn = pList ? pList->nExpr : 0;
89287     for(i=0; i<nColumn; i++){
89288       if( sqlcipher3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
89289         goto insert_cleanup;
89290       }
89291     }
89292   }
89293
89294   /* Make sure the number of columns in the source data matches the number
89295   ** of columns to be inserted into the table.
89296   */
89297   if( IsVirtual(pTab) ){
89298     for(i=0; i<pTab->nCol; i++){
89299       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
89300     }
89301   }
89302   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
89303     sqlcipher3ErrorMsg(pParse, 
89304        "table %S has %d columns but %d values were supplied",
89305        pTabList, 0, pTab->nCol-nHidden, nColumn);
89306     goto insert_cleanup;
89307   }
89308   if( pColumn!=0 && nColumn!=pColumn->nId ){
89309     sqlcipher3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
89310     goto insert_cleanup;
89311   }
89312
89313   /* If the INSERT statement included an IDLIST term, then make sure
89314   ** all elements of the IDLIST really are columns of the table and 
89315   ** remember the column indices.
89316   **
89317   ** If the table has an INTEGER PRIMARY KEY column and that column
89318   ** is named in the IDLIST, then record in the keyColumn variable
89319   ** the index into IDLIST of the primary key column.  keyColumn is
89320   ** the index of the primary key as it appears in IDLIST, not as
89321   ** is appears in the original table.  (The index of the primary
89322   ** key in the original table is pTab->iPKey.)
89323   */
89324   if( pColumn ){
89325     for(i=0; i<pColumn->nId; i++){
89326       pColumn->a[i].idx = -1;
89327     }
89328     for(i=0; i<pColumn->nId; i++){
89329       for(j=0; j<pTab->nCol; j++){
89330         if( sqlcipher3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
89331           pColumn->a[i].idx = j;
89332           if( j==pTab->iPKey ){
89333             keyColumn = i;
89334           }
89335           break;
89336         }
89337       }
89338       if( j>=pTab->nCol ){
89339         if( sqlcipher3IsRowid(pColumn->a[i].zName) ){
89340           keyColumn = i;
89341         }else{
89342           sqlcipher3ErrorMsg(pParse, "table %S has no column named %s",
89343               pTabList, 0, pColumn->a[i].zName);
89344           pParse->checkSchema = 1;
89345           goto insert_cleanup;
89346         }
89347       }
89348     }
89349   }
89350
89351   /* If there is no IDLIST term but the table has an integer primary
89352   ** key, the set the keyColumn variable to the primary key column index
89353   ** in the original table definition.
89354   */
89355   if( pColumn==0 && nColumn>0 ){
89356     keyColumn = pTab->iPKey;
89357   }
89358     
89359   /* Initialize the count of rows to be inserted
89360   */
89361   if( db->flags & SQLCIPHER_CountRows ){
89362     regRowCount = ++pParse->nMem;
89363     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
89364   }
89365
89366   /* If this is not a view, open the table and and all indices */
89367   if( !isView ){
89368     int nIdx;
89369
89370     baseCur = pParse->nTab;
89371     nIdx = sqlcipher3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
89372     aRegIdx = sqlcipher3DbMallocRaw(db, sizeof(int)*(nIdx+1));
89373     if( aRegIdx==0 ){
89374       goto insert_cleanup;
89375     }
89376     for(i=0; i<nIdx; i++){
89377       aRegIdx[i] = ++pParse->nMem;
89378     }
89379   }
89380
89381   /* This is the top of the main insertion loop */
89382   if( useTempTable ){
89383     /* This block codes the top of loop only.  The complete loop is the
89384     ** following pseudocode (template 4):
89385     **
89386     **         rewind temp table
89387     **      C: loop over rows of intermediate table
89388     **           transfer values form intermediate table into <table>
89389     **         end loop
89390     **      D: ...
89391     */
89392     addrInsTop = sqlcipher3VdbeAddOp1(v, OP_Rewind, srcTab);
89393     addrCont = sqlcipher3VdbeCurrentAddr(v);
89394   }else if( pSelect ){
89395     /* This block codes the top of loop only.  The complete loop is the
89396     ** following pseudocode (template 3):
89397     **
89398     **      C: yield X
89399     **         if EOF goto D
89400     **         insert the select result into <table> from R..R+n
89401     **         goto C
89402     **      D: ...
89403     */
89404     addrCont = sqlcipher3VdbeAddOp1(v, OP_Yield, dest.iParm);
89405     addrInsTop = sqlcipher3VdbeAddOp1(v, OP_If, regEof);
89406   }
89407
89408   /* Allocate registers for holding the rowid of the new row,
89409   ** the content of the new row, and the assemblied row record.
89410   */
89411   regRowid = regIns = pParse->nMem+1;
89412   pParse->nMem += pTab->nCol + 1;
89413   if( IsVirtual(pTab) ){
89414     regRowid++;
89415     pParse->nMem++;
89416   }
89417   regData = regRowid+1;
89418
89419   /* Run the BEFORE and INSTEAD OF triggers, if there are any
89420   */
89421   endOfLoop = sqlcipher3VdbeMakeLabel(v);
89422   if( tmask & TRIGGER_BEFORE ){
89423     int regCols = sqlcipher3GetTempRange(pParse, pTab->nCol+1);
89424
89425     /* build the NEW.* reference row.  Note that if there is an INTEGER
89426     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
89427     ** translated into a unique ID for the row.  But on a BEFORE trigger,
89428     ** we do not know what the unique ID will be (because the insert has
89429     ** not happened yet) so we substitute a rowid of -1
89430     */
89431     if( keyColumn<0 ){
89432       sqlcipher3VdbeAddOp2(v, OP_Integer, -1, regCols);
89433     }else{
89434       int j1;
89435       if( useTempTable ){
89436         sqlcipher3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
89437       }else{
89438         assert( pSelect==0 );  /* Otherwise useTempTable is true */
89439         sqlcipher3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
89440       }
89441       j1 = sqlcipher3VdbeAddOp1(v, OP_NotNull, regCols);
89442       sqlcipher3VdbeAddOp2(v, OP_Integer, -1, regCols);
89443       sqlcipher3VdbeJumpHere(v, j1);
89444       sqlcipher3VdbeAddOp1(v, OP_MustBeInt, regCols);
89445     }
89446
89447     /* Cannot have triggers on a virtual table. If it were possible,
89448     ** this block would have to account for hidden column.
89449     */
89450     assert( !IsVirtual(pTab) );
89451
89452     /* Create the new column data
89453     */
89454     for(i=0; i<pTab->nCol; i++){
89455       if( pColumn==0 ){
89456         j = i;
89457       }else{
89458         for(j=0; j<pColumn->nId; j++){
89459           if( pColumn->a[j].idx==i ) break;
89460         }
89461       }
89462       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
89463         sqlcipher3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
89464       }else if( useTempTable ){
89465         sqlcipher3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
89466       }else{
89467         assert( pSelect==0 ); /* Otherwise useTempTable is true */
89468         sqlcipher3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
89469       }
89470     }
89471
89472     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
89473     ** do not attempt any conversions before assembling the record.
89474     ** If this is a real table, attempt conversions as required by the
89475     ** table column affinities.
89476     */
89477     if( !isView ){
89478       sqlcipher3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
89479       sqlcipher3TableAffinityStr(v, pTab);
89480     }
89481
89482     /* Fire BEFORE or INSTEAD OF triggers */
89483     sqlcipher3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
89484         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
89485
89486     sqlcipher3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
89487   }
89488
89489   /* Push the record number for the new entry onto the stack.  The
89490   ** record number is a randomly generate integer created by NewRowid
89491   ** except when the table has an INTEGER PRIMARY KEY column, in which
89492   ** case the record number is the same as that column. 
89493   */
89494   if( !isView ){
89495     if( IsVirtual(pTab) ){
89496       /* The row that the VUpdate opcode will delete: none */
89497       sqlcipher3VdbeAddOp2(v, OP_Null, 0, regIns);
89498     }
89499     if( keyColumn>=0 ){
89500       if( useTempTable ){
89501         sqlcipher3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
89502       }else if( pSelect ){
89503         sqlcipher3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
89504       }else{
89505         VdbeOp *pOp;
89506         sqlcipher3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
89507         pOp = sqlcipher3VdbeGetOp(v, -1);
89508         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
89509           appendFlag = 1;
89510           pOp->opcode = OP_NewRowid;
89511           pOp->p1 = baseCur;
89512           pOp->p2 = regRowid;
89513           pOp->p3 = regAutoinc;
89514         }
89515       }
89516       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
89517       ** to generate a unique primary key value.
89518       */
89519       if( !appendFlag ){
89520         int j1;
89521         if( !IsVirtual(pTab) ){
89522           j1 = sqlcipher3VdbeAddOp1(v, OP_NotNull, regRowid);
89523           sqlcipher3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89524           sqlcipher3VdbeJumpHere(v, j1);
89525         }else{
89526           j1 = sqlcipher3VdbeCurrentAddr(v);
89527           sqlcipher3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
89528         }
89529         sqlcipher3VdbeAddOp1(v, OP_MustBeInt, regRowid);
89530       }
89531     }else if( IsVirtual(pTab) ){
89532       sqlcipher3VdbeAddOp2(v, OP_Null, 0, regRowid);
89533     }else{
89534       sqlcipher3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89535       appendFlag = 1;
89536     }
89537     autoIncStep(pParse, regAutoinc, regRowid);
89538
89539     /* Push onto the stack, data for all columns of the new entry, beginning
89540     ** with the first column.
89541     */
89542     nHidden = 0;
89543     for(i=0; i<pTab->nCol; i++){
89544       int iRegStore = regRowid+1+i;
89545       if( i==pTab->iPKey ){
89546         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
89547         ** Whenever this column is read, the record number will be substituted
89548         ** in its place.  So will fill this column with a NULL to avoid
89549         ** taking up data space with information that will never be used. */
89550         sqlcipher3VdbeAddOp2(v, OP_Null, 0, iRegStore);
89551         continue;
89552       }
89553       if( pColumn==0 ){
89554         if( IsHiddenColumn(&pTab->aCol[i]) ){
89555           assert( IsVirtual(pTab) );
89556           j = -1;
89557           nHidden++;
89558         }else{
89559           j = i - nHidden;
89560         }
89561       }else{
89562         for(j=0; j<pColumn->nId; j++){
89563           if( pColumn->a[j].idx==i ) break;
89564         }
89565       }
89566       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
89567         sqlcipher3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
89568       }else if( useTempTable ){
89569         sqlcipher3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
89570       }else if( pSelect ){
89571         sqlcipher3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
89572       }else{
89573         sqlcipher3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
89574       }
89575     }
89576
89577     /* Generate code to check constraints and generate index keys and
89578     ** do the insertion.
89579     */
89580 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
89581     if( IsVirtual(pTab) ){
89582       const char *pVTab = (const char *)sqlcipher3GetVTable(db, pTab);
89583       sqlcipher3VtabMakeWritable(pParse, pTab);
89584       sqlcipher3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
89585       sqlcipher3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
89586       sqlcipher3MayAbort(pParse);
89587     }else
89588 #endif
89589     {
89590       int isReplace;    /* Set to true if constraints may cause a replace */
89591       sqlcipher3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
89592           keyColumn>=0, 0, onError, endOfLoop, &isReplace
89593       );
89594       sqlcipher3FkCheck(pParse, pTab, 0, regIns);
89595       sqlcipher3CompleteInsertion(
89596           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
89597       );
89598     }
89599   }
89600
89601   /* Update the count of rows that are inserted
89602   */
89603   if( (db->flags & SQLCIPHER_CountRows)!=0 ){
89604     sqlcipher3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
89605   }
89606
89607   if( pTrigger ){
89608     /* Code AFTER triggers */
89609     sqlcipher3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
89610         pTab, regData-2-pTab->nCol, onError, endOfLoop);
89611   }
89612
89613   /* The bottom of the main insertion loop, if the data source
89614   ** is a SELECT statement.
89615   */
89616   sqlcipher3VdbeResolveLabel(v, endOfLoop);
89617   if( useTempTable ){
89618     sqlcipher3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
89619     sqlcipher3VdbeJumpHere(v, addrInsTop);
89620     sqlcipher3VdbeAddOp1(v, OP_Close, srcTab);
89621   }else if( pSelect ){
89622     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addrCont);
89623     sqlcipher3VdbeJumpHere(v, addrInsTop);
89624   }
89625
89626   if( !IsVirtual(pTab) && !isView ){
89627     /* Close all tables opened */
89628     sqlcipher3VdbeAddOp1(v, OP_Close, baseCur);
89629     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
89630       sqlcipher3VdbeAddOp1(v, OP_Close, idx+baseCur);
89631     }
89632   }
89633
89634 insert_end:
89635   /* Update the sqlcipher_sequence table by storing the content of the
89636   ** maximum rowid counter values recorded while inserting into
89637   ** autoincrement tables.
89638   */
89639   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
89640     sqlcipher3AutoincrementEnd(pParse);
89641   }
89642
89643   /*
89644   ** Return the number of rows inserted. If this routine is 
89645   ** generating code because of a call to sqlcipher3NestedParse(), do not
89646   ** invoke the callback function.
89647   */
89648   if( (db->flags&SQLCIPHER_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
89649     sqlcipher3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
89650     sqlcipher3VdbeSetNumCols(v, 1);
89651     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLCIPHER_STATIC);
89652   }
89653
89654 insert_cleanup:
89655   sqlcipher3SrcListDelete(db, pTabList);
89656   sqlcipher3ExprListDelete(db, pList);
89657   sqlcipher3SelectDelete(db, pSelect);
89658   sqlcipher3IdListDelete(db, pColumn);
89659   sqlcipher3DbFree(db, aRegIdx);
89660 }
89661
89662 /* Make sure "isView" and other macros defined above are undefined. Otherwise
89663 ** thely may interfere with compilation of other functions in this file
89664 ** (or in another file, if this file becomes part of the amalgamation).  */
89665 #ifdef isView
89666  #undef isView
89667 #endif
89668 #ifdef pTrigger
89669  #undef pTrigger
89670 #endif
89671 #ifdef tmask
89672  #undef tmask
89673 #endif
89674
89675
89676 /*
89677 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
89678 **
89679 ** The input is a range of consecutive registers as follows:
89680 **
89681 **    1.  The rowid of the row after the update.
89682 **
89683 **    2.  The data in the first column of the entry after the update.
89684 **
89685 **    i.  Data from middle columns...
89686 **
89687 **    N.  The data in the last column of the entry after the update.
89688 **
89689 ** The regRowid parameter is the index of the register containing (1).
89690 **
89691 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
89692 ** the address of a register containing the rowid before the update takes
89693 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
89694 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
89695 ** indicates that the rowid was explicitly specified as part of the
89696 ** INSERT statement. If rowidChng is false, it means that  the rowid is
89697 ** computed automatically in an insert or that the rowid value is not 
89698 ** modified by an update.
89699 **
89700 ** The code generated by this routine store new index entries into
89701 ** registers identified by aRegIdx[].  No index entry is created for
89702 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
89703 ** the same as the order of indices on the linked list of indices
89704 ** attached to the table.
89705 **
89706 ** This routine also generates code to check constraints.  NOT NULL,
89707 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
89708 ** then the appropriate action is performed.  There are five possible
89709 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
89710 **
89711 **  Constraint type  Action       What Happens
89712 **  ---------------  ----------   ----------------------------------------
89713 **  any              ROLLBACK     The current transaction is rolled back and
89714 **                                sqlcipher3_exec() returns immediately with a
89715 **                                return code of SQLCIPHER_CONSTRAINT.
89716 **
89717 **  any              ABORT        Back out changes from the current command
89718 **                                only (do not do a complete rollback) then
89719 **                                cause sqlcipher3_exec() to return immediately
89720 **                                with SQLCIPHER_CONSTRAINT.
89721 **
89722 **  any              FAIL         Sqlite_exec() returns immediately with a
89723 **                                return code of SQLCIPHER_CONSTRAINT.  The
89724 **                                transaction is not rolled back and any
89725 **                                prior changes are retained.
89726 **
89727 **  any              IGNORE       The record number and data is popped from
89728 **                                the stack and there is an immediate jump
89729 **                                to label ignoreDest.
89730 **
89731 **  NOT NULL         REPLACE      The NULL value is replace by the default
89732 **                                value for that column.  If the default value
89733 **                                is NULL, the action is the same as ABORT.
89734 **
89735 **  UNIQUE           REPLACE      The other row that conflicts with the row
89736 **                                being inserted is removed.
89737 **
89738 **  CHECK            REPLACE      Illegal.  The results in an exception.
89739 **
89740 ** Which action to take is determined by the overrideError parameter.
89741 ** Or if overrideError==OE_Default, then the pParse->onError parameter
89742 ** is used.  Or if pParse->onError==OE_Default then the onError value
89743 ** for the constraint is used.
89744 **
89745 ** The calling routine must open a read/write cursor for pTab with
89746 ** cursor number "baseCur".  All indices of pTab must also have open
89747 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
89748 ** Except, if there is no possibility of a REPLACE action then
89749 ** cursors do not need to be open for indices where aRegIdx[i]==0.
89750 */
89751 SQLCIPHER_PRIVATE void sqlcipher3GenerateConstraintChecks(
89752   Parse *pParse,      /* The parser context */
89753   Table *pTab,        /* the table into which we are inserting */
89754   int baseCur,        /* Index of a read/write cursor pointing at pTab */
89755   int regRowid,       /* Index of the range of input registers */
89756   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
89757   int rowidChng,      /* True if the rowid might collide with existing entry */
89758   int isUpdate,       /* True for UPDATE, False for INSERT */
89759   int overrideError,  /* Override onError to this if not OE_Default */
89760   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
89761   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
89762 ){
89763   int i;              /* loop counter */
89764   Vdbe *v;            /* VDBE under constrution */
89765   int nCol;           /* Number of columns */
89766   int onError;        /* Conflict resolution strategy */
89767   int j1;             /* Addresss of jump instruction */
89768   int j2 = 0, j3;     /* Addresses of jump instructions */
89769   int regData;        /* Register containing first data column */
89770   int iCur;           /* Table cursor number */
89771   Index *pIdx;         /* Pointer to one of the indices */
89772   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
89773   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
89774
89775   v = sqlcipher3GetVdbe(pParse);
89776   assert( v!=0 );
89777   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
89778   nCol = pTab->nCol;
89779   regData = regRowid + 1;
89780
89781   /* Test all NOT NULL constraints.
89782   */
89783   for(i=0; i<nCol; i++){
89784     if( i==pTab->iPKey ){
89785       continue;
89786     }
89787     onError = pTab->aCol[i].notNull;
89788     if( onError==OE_None ) continue;
89789     if( overrideError!=OE_Default ){
89790       onError = overrideError;
89791     }else if( onError==OE_Default ){
89792       onError = OE_Abort;
89793     }
89794     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
89795       onError = OE_Abort;
89796     }
89797     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
89798         || onError==OE_Ignore || onError==OE_Replace );
89799     switch( onError ){
89800       case OE_Abort:
89801         sqlcipher3MayAbort(pParse);
89802       case OE_Rollback:
89803       case OE_Fail: {
89804         char *zMsg;
89805         sqlcipher3VdbeAddOp3(v, OP_HaltIfNull,
89806                                   SQLCIPHER_CONSTRAINT, onError, regData+i);
89807         zMsg = sqlcipher3MPrintf(pParse->db, "%s.%s may not be NULL",
89808                               pTab->zName, pTab->aCol[i].zName);
89809         sqlcipher3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
89810         break;
89811       }
89812       case OE_Ignore: {
89813         sqlcipher3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
89814         break;
89815       }
89816       default: {
89817         assert( onError==OE_Replace );
89818         j1 = sqlcipher3VdbeAddOp1(v, OP_NotNull, regData+i);
89819         sqlcipher3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
89820         sqlcipher3VdbeJumpHere(v, j1);
89821         break;
89822       }
89823     }
89824   }
89825
89826   /* Test all CHECK constraints
89827   */
89828 #ifndef SQLCIPHER_OMIT_CHECK
89829   if( pTab->pCheck && (pParse->db->flags & SQLCIPHER_IgnoreChecks)==0 ){
89830     int allOk = sqlcipher3VdbeMakeLabel(v);
89831     pParse->ckBase = regData;
89832     sqlcipher3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLCIPHER_JUMPIFNULL);
89833     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
89834     if( onError==OE_Ignore ){
89835       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
89836     }else{
89837       if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
89838       sqlcipher3HaltConstraint(pParse, onError, 0, 0);
89839     }
89840     sqlcipher3VdbeResolveLabel(v, allOk);
89841   }
89842 #endif /* !defined(SQLCIPHER_OMIT_CHECK) */
89843
89844   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
89845   ** of the new record does not previously exist.  Except, if this
89846   ** is an UPDATE and the primary key is not changing, that is OK.
89847   */
89848   if( rowidChng ){
89849     onError = pTab->keyConf;
89850     if( overrideError!=OE_Default ){
89851       onError = overrideError;
89852     }else if( onError==OE_Default ){
89853       onError = OE_Abort;
89854     }
89855     
89856     if( isUpdate ){
89857       j2 = sqlcipher3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
89858     }
89859     j3 = sqlcipher3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
89860     switch( onError ){
89861       default: {
89862         onError = OE_Abort;
89863         /* Fall thru into the next case */
89864       }
89865       case OE_Rollback:
89866       case OE_Abort:
89867       case OE_Fail: {
89868         sqlcipher3HaltConstraint(
89869           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
89870         break;
89871       }
89872       case OE_Replace: {
89873         /* If there are DELETE triggers on this table and the
89874         ** recursive-triggers flag is set, call GenerateRowDelete() to
89875         ** remove the conflicting row from the the table. This will fire
89876         ** the triggers and remove both the table and index b-tree entries.
89877         **
89878         ** Otherwise, if there are no triggers or the recursive-triggers
89879         ** flag is not set, but the table has one or more indexes, call 
89880         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
89881         ** only. The table b-tree entry will be replaced by the new entry 
89882         ** when it is inserted.  
89883         **
89884         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
89885         ** also invoke MultiWrite() to indicate that this VDBE may require
89886         ** statement rollback (if the statement is aborted after the delete
89887         ** takes place). Earlier versions called sqlcipher3MultiWrite() regardless,
89888         ** but being more selective here allows statements like:
89889         **
89890         **   REPLACE INTO t(rowid) VALUES($newrowid)
89891         **
89892         ** to run without a statement journal if there are no indexes on the
89893         ** table.
89894         */
89895         Trigger *pTrigger = 0;
89896         if( pParse->db->flags&SQLCIPHER_RecTriggers ){
89897           pTrigger = sqlcipher3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
89898         }
89899         if( pTrigger || sqlcipher3FkRequired(pParse, pTab, 0, 0) ){
89900           sqlcipher3MultiWrite(pParse);
89901           sqlcipher3GenerateRowDelete(
89902               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
89903           );
89904         }else if( pTab->pIndex ){
89905           sqlcipher3MultiWrite(pParse);
89906           sqlcipher3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
89907         }
89908         seenReplace = 1;
89909         break;
89910       }
89911       case OE_Ignore: {
89912         assert( seenReplace==0 );
89913         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
89914         break;
89915       }
89916     }
89917     sqlcipher3VdbeJumpHere(v, j3);
89918     if( isUpdate ){
89919       sqlcipher3VdbeJumpHere(v, j2);
89920     }
89921   }
89922
89923   /* Test all UNIQUE constraints by creating entries for each UNIQUE
89924   ** index and making sure that duplicate entries do not already exist.
89925   ** Add the new records to the indices as we go.
89926   */
89927   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
89928     int regIdx;
89929     int regR;
89930
89931     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
89932
89933     /* Create a key for accessing the index entry */
89934     regIdx = sqlcipher3GetTempRange(pParse, pIdx->nColumn+1);
89935     for(i=0; i<pIdx->nColumn; i++){
89936       int idx = pIdx->aiColumn[i];
89937       if( idx==pTab->iPKey ){
89938         sqlcipher3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
89939       }else{
89940         sqlcipher3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
89941       }
89942     }
89943     sqlcipher3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
89944     sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
89945     sqlcipher3VdbeChangeP4(v, -1, sqlcipher3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
89946     sqlcipher3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
89947
89948     /* Find out what action to take in case there is an indexing conflict */
89949     onError = pIdx->onError;
89950     if( onError==OE_None ){ 
89951       sqlcipher3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
89952       continue;  /* pIdx is not a UNIQUE index */
89953     }
89954     if( overrideError!=OE_Default ){
89955       onError = overrideError;
89956     }else if( onError==OE_Default ){
89957       onError = OE_Abort;
89958     }
89959     if( seenReplace ){
89960       if( onError==OE_Ignore ) onError = OE_Replace;
89961       else if( onError==OE_Fail ) onError = OE_Abort;
89962     }
89963     
89964     /* Check to see if the new index entry will be unique */
89965     regR = sqlcipher3GetTempReg(pParse);
89966     sqlcipher3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
89967     j3 = sqlcipher3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
89968                            regR, SQLCIPHER_INT_TO_PTR(regIdx),
89969                            P4_INT32);
89970     sqlcipher3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
89971
89972     /* Generate code that executes if the new index entry is not unique */
89973     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
89974         || onError==OE_Ignore || onError==OE_Replace );
89975     switch( onError ){
89976       case OE_Rollback:
89977       case OE_Abort:
89978       case OE_Fail: {
89979         int j;
89980         StrAccum errMsg;
89981         const char *zSep;
89982         char *zErr;
89983
89984         sqlcipher3StrAccumInit(&errMsg, 0, 0, 200);
89985         errMsg.db = pParse->db;
89986         zSep = pIdx->nColumn>1 ? "columns " : "column ";
89987         for(j=0; j<pIdx->nColumn; j++){
89988           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
89989           sqlcipher3StrAccumAppend(&errMsg, zSep, -1);
89990           zSep = ", ";
89991           sqlcipher3StrAccumAppend(&errMsg, zCol, -1);
89992         }
89993         sqlcipher3StrAccumAppend(&errMsg,
89994             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
89995         zErr = sqlcipher3StrAccumFinish(&errMsg);
89996         sqlcipher3HaltConstraint(pParse, onError, zErr, 0);
89997         sqlcipher3DbFree(errMsg.db, zErr);
89998         break;
89999       }
90000       case OE_Ignore: {
90001         assert( seenReplace==0 );
90002         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90003         break;
90004       }
90005       default: {
90006         Trigger *pTrigger = 0;
90007         assert( onError==OE_Replace );
90008         sqlcipher3MultiWrite(pParse);
90009         if( pParse->db->flags&SQLCIPHER_RecTriggers ){
90010           pTrigger = sqlcipher3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
90011         }
90012         sqlcipher3GenerateRowDelete(
90013             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
90014         );
90015         seenReplace = 1;
90016         break;
90017       }
90018     }
90019     sqlcipher3VdbeJumpHere(v, j3);
90020     sqlcipher3ReleaseTempReg(pParse, regR);
90021   }
90022   
90023   if( pbMayReplace ){
90024     *pbMayReplace = seenReplace;
90025   }
90026 }
90027
90028 /*
90029 ** This routine generates code to finish the INSERT or UPDATE operation
90030 ** that was started by a prior call to sqlcipher3GenerateConstraintChecks.
90031 ** A consecutive range of registers starting at regRowid contains the
90032 ** rowid and the content to be inserted.
90033 **
90034 ** The arguments to this routine should be the same as the first six
90035 ** arguments to sqlcipher3GenerateConstraintChecks.
90036 */
90037 SQLCIPHER_PRIVATE void sqlcipher3CompleteInsertion(
90038   Parse *pParse,      /* The parser context */
90039   Table *pTab,        /* the table into which we are inserting */
90040   int baseCur,        /* Index of a read/write cursor pointing at pTab */
90041   int regRowid,       /* Range of content */
90042   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
90043   int isUpdate,       /* True for UPDATE, False for INSERT */
90044   int appendBias,     /* True if this is likely to be an append */
90045   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
90046 ){
90047   int i;
90048   Vdbe *v;
90049   int nIdx;
90050   Index *pIdx;
90051   u8 pik_flags;
90052   int regData;
90053   int regRec;
90054
90055   v = sqlcipher3GetVdbe(pParse);
90056   assert( v!=0 );
90057   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
90058   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
90059   for(i=nIdx-1; i>=0; i--){
90060     if( aRegIdx[i]==0 ) continue;
90061     sqlcipher3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
90062     if( useSeekResult ){
90063       sqlcipher3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
90064     }
90065   }
90066   regData = regRowid + 1;
90067   regRec = sqlcipher3GetTempReg(pParse);
90068   sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
90069   sqlcipher3TableAffinityStr(v, pTab);
90070   sqlcipher3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
90071   if( pParse->nested ){
90072     pik_flags = 0;
90073   }else{
90074     pik_flags = OPFLAG_NCHANGE;
90075     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
90076   }
90077   if( appendBias ){
90078     pik_flags |= OPFLAG_APPEND;
90079   }
90080   if( useSeekResult ){
90081     pik_flags |= OPFLAG_USESEEKRESULT;
90082   }
90083   sqlcipher3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
90084   if( !pParse->nested ){
90085     sqlcipher3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
90086   }
90087   sqlcipher3VdbeChangeP5(v, pik_flags);
90088 }
90089
90090 /*
90091 ** Generate code that will open cursors for a table and for all
90092 ** indices of that table.  The "baseCur" parameter is the cursor number used
90093 ** for the table.  Indices are opened on subsequent cursors.
90094 **
90095 ** Return the number of indices on the table.
90096 */
90097 SQLCIPHER_PRIVATE int sqlcipher3OpenTableAndIndices(
90098   Parse *pParse,   /* Parsing context */
90099   Table *pTab,     /* Table to be opened */
90100   int baseCur,     /* Cursor number assigned to the table */
90101   int op           /* OP_OpenRead or OP_OpenWrite */
90102 ){
90103   int i;
90104   int iDb;
90105   Index *pIdx;
90106   Vdbe *v;
90107
90108   if( IsVirtual(pTab) ) return 0;
90109   iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
90110   v = sqlcipher3GetVdbe(pParse);
90111   assert( v!=0 );
90112   sqlcipher3OpenTable(pParse, baseCur, iDb, pTab, op);
90113   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
90114     KeyInfo *pKey = sqlcipher3IndexKeyinfo(pParse, pIdx);
90115     assert( pIdx->pSchema==pTab->pSchema );
90116     sqlcipher3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
90117                       (char*)pKey, P4_KEYINFO_HANDOFF);
90118     VdbeComment((v, "%s", pIdx->zName));
90119   }
90120   if( pParse->nTab<baseCur+i ){
90121     pParse->nTab = baseCur+i;
90122   }
90123   return i-1;
90124 }
90125
90126
90127 #ifdef SQLCIPHER_TEST
90128 /*
90129 ** The following global variable is incremented whenever the
90130 ** transfer optimization is used.  This is used for testing
90131 ** purposes only - to make sure the transfer optimization really
90132 ** is happening when it is suppose to.
90133 */
90134 SQLCIPHER_API int sqlcipher3_xferopt_count;
90135 #endif /* SQLCIPHER_TEST */
90136
90137
90138 #ifndef SQLCIPHER_OMIT_XFER_OPT
90139 /*
90140 ** Check to collation names to see if they are compatible.
90141 */
90142 static int xferCompatibleCollation(const char *z1, const char *z2){
90143   if( z1==0 ){
90144     return z2==0;
90145   }
90146   if( z2==0 ){
90147     return 0;
90148   }
90149   return sqlcipher3StrICmp(z1, z2)==0;
90150 }
90151
90152
90153 /*
90154 ** Check to see if index pSrc is compatible as a source of data
90155 ** for index pDest in an insert transfer optimization.  The rules
90156 ** for a compatible index:
90157 **
90158 **    *   The index is over the same set of columns
90159 **    *   The same DESC and ASC markings occurs on all columns
90160 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
90161 **    *   The same collating sequence on each column
90162 */
90163 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
90164   int i;
90165   assert( pDest && pSrc );
90166   assert( pDest->pTable!=pSrc->pTable );
90167   if( pDest->nColumn!=pSrc->nColumn ){
90168     return 0;   /* Different number of columns */
90169   }
90170   if( pDest->onError!=pSrc->onError ){
90171     return 0;   /* Different conflict resolution strategies */
90172   }
90173   for(i=0; i<pSrc->nColumn; i++){
90174     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
90175       return 0;   /* Different columns indexed */
90176     }
90177     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
90178       return 0;   /* Different sort orders */
90179     }
90180     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
90181       return 0;   /* Different collating sequences */
90182     }
90183   }
90184
90185   /* If no test above fails then the indices must be compatible */
90186   return 1;
90187 }
90188
90189 /*
90190 ** Attempt the transfer optimization on INSERTs of the form
90191 **
90192 **     INSERT INTO tab1 SELECT * FROM tab2;
90193 **
90194 ** This optimization is only attempted if
90195 **
90196 **    (1)  tab1 and tab2 have identical schemas including all the
90197 **         same indices and constraints
90198 **
90199 **    (2)  tab1 and tab2 are different tables
90200 **
90201 **    (3)  There must be no triggers on tab1
90202 **
90203 **    (4)  The result set of the SELECT statement is "*"
90204 **
90205 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
90206 **         or LIMIT clause.
90207 **
90208 **    (6)  The SELECT statement is a simple (not a compound) select that
90209 **         contains only tab2 in its FROM clause
90210 **
90211 ** This method for implementing the INSERT transfers raw records from
90212 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
90213 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
90214 ** the resulting tab1 has much less fragmentation.
90215 **
90216 ** This routine returns TRUE if the optimization is attempted.  If any
90217 ** of the conditions above fail so that the optimization should not
90218 ** be attempted, then this routine returns FALSE.
90219 */
90220 static int xferOptimization(
90221   Parse *pParse,        /* Parser context */
90222   Table *pDest,         /* The table we are inserting into */
90223   Select *pSelect,      /* A SELECT statement to use as the data source */
90224   int onError,          /* How to handle constraint errors */
90225   int iDbDest           /* The database of pDest */
90226 ){
90227   ExprList *pEList;                /* The result set of the SELECT */
90228   Table *pSrc;                     /* The table in the FROM clause of SELECT */
90229   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
90230   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
90231   int i;                           /* Loop counter */
90232   int iDbSrc;                      /* The database of pSrc */
90233   int iSrc, iDest;                 /* Cursors from source and destination */
90234   int addr1, addr2;                /* Loop addresses */
90235   int emptyDestTest;               /* Address of test for empty pDest */
90236   int emptySrcTest;                /* Address of test for empty pSrc */
90237   Vdbe *v;                         /* The VDBE we are building */
90238   KeyInfo *pKey;                   /* Key information for an index */
90239   int regAutoinc;                  /* Memory register used by AUTOINC */
90240   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
90241   int regData, regRowid;           /* Registers holding data and rowid */
90242
90243   if( pSelect==0 ){
90244     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
90245   }
90246   if( sqlcipher3TriggerList(pParse, pDest) ){
90247     return 0;   /* tab1 must not have triggers */
90248   }
90249 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
90250   if( pDest->tabFlags & TF_Virtual ){
90251     return 0;   /* tab1 must not be a virtual table */
90252   }
90253 #endif
90254   if( onError==OE_Default ){
90255     onError = OE_Abort;
90256   }
90257   if( onError!=OE_Abort && onError!=OE_Rollback ){
90258     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
90259   }
90260   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
90261   if( pSelect->pSrc->nSrc!=1 ){
90262     return 0;   /* FROM clause must have exactly one term */
90263   }
90264   if( pSelect->pSrc->a[0].pSelect ){
90265     return 0;   /* FROM clause cannot contain a subquery */
90266   }
90267   if( pSelect->pWhere ){
90268     return 0;   /* SELECT may not have a WHERE clause */
90269   }
90270   if( pSelect->pOrderBy ){
90271     return 0;   /* SELECT may not have an ORDER BY clause */
90272   }
90273   /* Do not need to test for a HAVING clause.  If HAVING is present but
90274   ** there is no ORDER BY, we will get an error. */
90275   if( pSelect->pGroupBy ){
90276     return 0;   /* SELECT may not have a GROUP BY clause */
90277   }
90278   if( pSelect->pLimit ){
90279     return 0;   /* SELECT may not have a LIMIT clause */
90280   }
90281   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
90282   if( pSelect->pPrior ){
90283     return 0;   /* SELECT may not be a compound query */
90284   }
90285   if( pSelect->selFlags & SF_Distinct ){
90286     return 0;   /* SELECT may not be DISTINCT */
90287   }
90288   pEList = pSelect->pEList;
90289   assert( pEList!=0 );
90290   if( pEList->nExpr!=1 ){
90291     return 0;   /* The result set must have exactly one column */
90292   }
90293   assert( pEList->a[0].pExpr );
90294   if( pEList->a[0].pExpr->op!=TK_ALL ){
90295     return 0;   /* The result set must be the special operator "*" */
90296   }
90297
90298   /* At this point we have established that the statement is of the
90299   ** correct syntactic form to participate in this optimization.  Now
90300   ** we have to check the semantics.
90301   */
90302   pItem = pSelect->pSrc->a;
90303   pSrc = sqlcipher3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
90304   if( pSrc==0 ){
90305     return 0;   /* FROM clause does not contain a real table */
90306   }
90307   if( pSrc==pDest ){
90308     return 0;   /* tab1 and tab2 may not be the same table */
90309   }
90310 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
90311   if( pSrc->tabFlags & TF_Virtual ){
90312     return 0;   /* tab2 must not be a virtual table */
90313   }
90314 #endif
90315   if( pSrc->pSelect ){
90316     return 0;   /* tab2 may not be a view */
90317   }
90318   if( pDest->nCol!=pSrc->nCol ){
90319     return 0;   /* Number of columns must be the same in tab1 and tab2 */
90320   }
90321   if( pDest->iPKey!=pSrc->iPKey ){
90322     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
90323   }
90324   for(i=0; i<pDest->nCol; i++){
90325     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
90326       return 0;    /* Affinity must be the same on all columns */
90327     }
90328     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
90329       return 0;    /* Collating sequence must be the same on all columns */
90330     }
90331     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
90332       return 0;    /* tab2 must be NOT NULL if tab1 is */
90333     }
90334   }
90335   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90336     if( pDestIdx->onError!=OE_None ){
90337       destHasUniqueIdx = 1;
90338     }
90339     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
90340       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90341     }
90342     if( pSrcIdx==0 ){
90343       return 0;    /* pDestIdx has no corresponding index in pSrc */
90344     }
90345   }
90346 #ifndef SQLCIPHER_OMIT_CHECK
90347   if( pDest->pCheck && sqlcipher3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
90348     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
90349   }
90350 #endif
90351 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
90352   /* Disallow the transfer optimization if the destination table constains
90353   ** any foreign key constraints.  This is more restrictive than necessary.
90354   ** But the main beneficiary of the transfer optimization is the VACUUM 
90355   ** command, and the VACUUM command disables foreign key constraints.  So
90356   ** the extra complication to make this rule less restrictive is probably
90357   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
90358   */
90359   if( (pParse->db->flags & SQLCIPHER_ForeignKeys)!=0 && pDest->pFKey!=0 ){
90360     return 0;
90361   }
90362 #endif
90363   if( (pParse->db->flags & SQLCIPHER_CountRows)!=0 ){
90364     return 0;
90365   }
90366
90367   /* If we get this far, it means either:
90368   **
90369   **    *   We can always do the transfer if the table contains an
90370   **        an integer primary key
90371   **
90372   **    *   We can conditionally do the transfer if the destination
90373   **        table is empty.
90374   */
90375 #ifdef SQLCIPHER_TEST
90376   sqlcipher3_xferopt_count++;
90377 #endif
90378   iDbSrc = sqlcipher3SchemaToIndex(pParse->db, pSrc->pSchema);
90379   v = sqlcipher3GetVdbe(pParse);
90380   sqlcipher3CodeVerifySchema(pParse, iDbSrc);
90381   iSrc = pParse->nTab++;
90382   iDest = pParse->nTab++;
90383   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
90384   sqlcipher3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
90385   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
90386     /* If tables do not have an INTEGER PRIMARY KEY and there
90387     ** are indices to be copied and the destination is not empty,
90388     ** we have to disallow the transfer optimization because the
90389     ** the rowids might change which will mess up indexing.
90390     **
90391     ** Or if the destination has a UNIQUE index and is not empty,
90392     ** we also disallow the transfer optimization because we cannot
90393     ** insure that all entries in the union of DEST and SRC will be
90394     ** unique.
90395     */
90396     addr1 = sqlcipher3VdbeAddOp2(v, OP_Rewind, iDest, 0);
90397     emptyDestTest = sqlcipher3VdbeAddOp2(v, OP_Goto, 0, 0);
90398     sqlcipher3VdbeJumpHere(v, addr1);
90399   }else{
90400     emptyDestTest = 0;
90401   }
90402   sqlcipher3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
90403   emptySrcTest = sqlcipher3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90404   regData = sqlcipher3GetTempReg(pParse);
90405   regRowid = sqlcipher3GetTempReg(pParse);
90406   if( pDest->iPKey>=0 ){
90407     addr1 = sqlcipher3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90408     addr2 = sqlcipher3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
90409     sqlcipher3HaltConstraint(
90410         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
90411     sqlcipher3VdbeJumpHere(v, addr2);
90412     autoIncStep(pParse, regAutoinc, regRowid);
90413   }else if( pDest->pIndex==0 ){
90414     addr1 = sqlcipher3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
90415   }else{
90416     addr1 = sqlcipher3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90417     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
90418   }
90419   sqlcipher3VdbeAddOp2(v, OP_RowData, iSrc, regData);
90420   sqlcipher3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
90421   sqlcipher3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
90422   sqlcipher3VdbeChangeP4(v, -1, pDest->zName, 0);
90423   sqlcipher3VdbeAddOp2(v, OP_Next, iSrc, addr1);
90424   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90425     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
90426       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90427     }
90428     assert( pSrcIdx );
90429     sqlcipher3VdbeAddOp2(v, OP_Close, iSrc, 0);
90430     sqlcipher3VdbeAddOp2(v, OP_Close, iDest, 0);
90431     pKey = sqlcipher3IndexKeyinfo(pParse, pSrcIdx);
90432     sqlcipher3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
90433                       (char*)pKey, P4_KEYINFO_HANDOFF);
90434     VdbeComment((v, "%s", pSrcIdx->zName));
90435     pKey = sqlcipher3IndexKeyinfo(pParse, pDestIdx);
90436     sqlcipher3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
90437                       (char*)pKey, P4_KEYINFO_HANDOFF);
90438     VdbeComment((v, "%s", pDestIdx->zName));
90439     addr1 = sqlcipher3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90440     sqlcipher3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
90441     sqlcipher3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
90442     sqlcipher3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
90443     sqlcipher3VdbeJumpHere(v, addr1);
90444   }
90445   sqlcipher3VdbeJumpHere(v, emptySrcTest);
90446   sqlcipher3ReleaseTempReg(pParse, regRowid);
90447   sqlcipher3ReleaseTempReg(pParse, regData);
90448   sqlcipher3VdbeAddOp2(v, OP_Close, iSrc, 0);
90449   sqlcipher3VdbeAddOp2(v, OP_Close, iDest, 0);
90450   if( emptyDestTest ){
90451     sqlcipher3VdbeAddOp2(v, OP_Halt, SQLCIPHER_OK, 0);
90452     sqlcipher3VdbeJumpHere(v, emptyDestTest);
90453     sqlcipher3VdbeAddOp2(v, OP_Close, iDest, 0);
90454     return 0;
90455   }else{
90456     return 1;
90457   }
90458 }
90459 #endif /* SQLCIPHER_OMIT_XFER_OPT */
90460
90461 /************** End of insert.c **********************************************/
90462 /************** Begin file legacy.c ******************************************/
90463 /*
90464 ** 2001 September 15
90465 **
90466 ** The author disclaims copyright to this source code.  In place of
90467 ** a legal notice, here is a blessing:
90468 **
90469 **    May you do good and not evil.
90470 **    May you find forgiveness for yourself and forgive others.
90471 **    May you share freely, never taking more than you give.
90472 **
90473 *************************************************************************
90474 ** Main file for the SQLite library.  The routines in this file
90475 ** implement the programmer interface to the library.  Routines in
90476 ** other files are for internal use by SQLite and should not be
90477 ** accessed by users of the library.
90478 */
90479
90480
90481 /*
90482 ** Execute SQL code.  Return one of the SQLCIPHER_ success/failure
90483 ** codes.  Also write an error message into memory obtained from
90484 ** malloc() and make *pzErrMsg point to that message.
90485 **
90486 ** If the SQL is a query, then for each row in the query result
90487 ** the xCallback() function is called.  pArg becomes the first
90488 ** argument to xCallback().  If xCallback=NULL then no callback
90489 ** is invoked, even for queries.
90490 */
90491 SQLCIPHER_API int sqlcipher3_exec(
90492   sqlcipher3 *db,                /* The database on which the SQL executes */
90493   const char *zSql,           /* The SQL to be executed */
90494   sqlcipher3_callback xCallback, /* Invoke this callback routine */
90495   void *pArg,                 /* First argument to xCallback() */
90496   char **pzErrMsg             /* Write error messages here */
90497 ){
90498   int rc = SQLCIPHER_OK;         /* Return code */
90499   const char *zLeftover;      /* Tail of unprocessed SQL */
90500   sqlcipher3_stmt *pStmt = 0;    /* The current SQL statement */
90501   char **azCols = 0;          /* Names of result columns */
90502   int nRetry = 0;             /* Number of retry attempts */
90503   int callbackIsInit;         /* True if callback data is initialized */
90504
90505   if( !sqlcipher3SafetyCheckOk(db) ) return SQLCIPHER_MISUSE_BKPT;
90506   if( zSql==0 ) zSql = "";
90507
90508   sqlcipher3_mutex_enter(db->mutex);
90509   sqlcipher3Error(db, SQLCIPHER_OK, 0);
90510   while( (rc==SQLCIPHER_OK || (rc==SQLCIPHER_SCHEMA && (++nRetry)<2)) && zSql[0] ){
90511     int nCol;
90512     char **azVals = 0;
90513
90514     pStmt = 0;
90515     rc = sqlcipher3_prepare(db, zSql, -1, &pStmt, &zLeftover);
90516     assert( rc==SQLCIPHER_OK || pStmt==0 );
90517     if( rc!=SQLCIPHER_OK ){
90518       continue;
90519     }
90520     if( !pStmt ){
90521       /* this happens for a comment or white-space */
90522       zSql = zLeftover;
90523       continue;
90524     }
90525
90526     callbackIsInit = 0;
90527     nCol = sqlcipher3_column_count(pStmt);
90528
90529     while( 1 ){
90530       int i;
90531       rc = sqlcipher3_step(pStmt);
90532
90533       /* Invoke the callback function if required */
90534       if( xCallback && (SQLCIPHER_ROW==rc || 
90535           (SQLCIPHER_DONE==rc && !callbackIsInit
90536                            && db->flags&SQLCIPHER_NullCallback)) ){
90537         if( !callbackIsInit ){
90538           azCols = sqlcipher3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
90539           if( azCols==0 ){
90540             goto exec_out;
90541           }
90542           for(i=0; i<nCol; i++){
90543             azCols[i] = (char *)sqlcipher3_column_name(pStmt, i);
90544             /* sqlcipher3VdbeSetColName() installs column names as UTF8
90545             ** strings so there is no way for sqlcipher3_column_name() to fail. */
90546             assert( azCols[i]!=0 );
90547           }
90548           callbackIsInit = 1;
90549         }
90550         if( rc==SQLCIPHER_ROW ){
90551           azVals = &azCols[nCol];
90552           for(i=0; i<nCol; i++){
90553             azVals[i] = (char *)sqlcipher3_column_text(pStmt, i);
90554             if( !azVals[i] && sqlcipher3_column_type(pStmt, i)!=SQLCIPHER_NULL ){
90555               db->mallocFailed = 1;
90556               goto exec_out;
90557             }
90558           }
90559         }
90560         if( xCallback(pArg, nCol, azVals, azCols) ){
90561           rc = SQLCIPHER_ABORT;
90562           sqlcipher3VdbeFinalize((Vdbe *)pStmt);
90563           pStmt = 0;
90564           sqlcipher3Error(db, SQLCIPHER_ABORT, 0);
90565           goto exec_out;
90566         }
90567       }
90568
90569       if( rc!=SQLCIPHER_ROW ){
90570         rc = sqlcipher3VdbeFinalize((Vdbe *)pStmt);
90571         pStmt = 0;
90572         if( rc!=SQLCIPHER_SCHEMA ){
90573           nRetry = 0;
90574           zSql = zLeftover;
90575           while( sqlcipher3Isspace(zSql[0]) ) zSql++;
90576         }
90577         break;
90578       }
90579     }
90580
90581     sqlcipher3DbFree(db, azCols);
90582     azCols = 0;
90583   }
90584
90585 exec_out:
90586   if( pStmt ) sqlcipher3VdbeFinalize((Vdbe *)pStmt);
90587   sqlcipher3DbFree(db, azCols);
90588
90589   rc = sqlcipher3ApiExit(db, rc);
90590   if( rc!=SQLCIPHER_OK && ALWAYS(rc==sqlcipher3_errcode(db)) && pzErrMsg ){
90591     int nErrMsg = 1 + sqlcipher3Strlen30(sqlcipher3_errmsg(db));
90592     *pzErrMsg = sqlcipher3Malloc(nErrMsg);
90593     if( *pzErrMsg ){
90594       memcpy(*pzErrMsg, sqlcipher3_errmsg(db), nErrMsg);
90595     }else{
90596       rc = SQLCIPHER_NOMEM;
90597       sqlcipher3Error(db, SQLCIPHER_NOMEM, 0);
90598     }
90599   }else if( pzErrMsg ){
90600     *pzErrMsg = 0;
90601   }
90602
90603   assert( (rc&db->errMask)==rc );
90604   sqlcipher3_mutex_leave(db->mutex);
90605   return rc;
90606 }
90607
90608 /************** End of legacy.c **********************************************/
90609 /************** Begin file loadext.c *****************************************/
90610 /*
90611 ** 2006 June 7
90612 **
90613 ** The author disclaims copyright to this source code.  In place of
90614 ** a legal notice, here is a blessing:
90615 **
90616 **    May you do good and not evil.
90617 **    May you find forgiveness for yourself and forgive others.
90618 **    May you share freely, never taking more than you give.
90619 **
90620 *************************************************************************
90621 ** This file contains code used to dynamically load extensions into
90622 ** the SQLite library.
90623 */
90624
90625 #ifndef SQLCIPHER_CORE
90626   #define SQLCIPHER_CORE 1  /* Disable the API redefinition in sqlcipher3ext.h */
90627 #endif
90628 /************** Include sqlcipher3ext.h in the middle of loadext.c **************/
90629 /************** Begin file sqlcipher3ext.h **************************************/
90630 /*
90631 ** 2006 June 7
90632 **
90633 ** The author disclaims copyright to this source code.  In place of
90634 ** a legal notice, here is a blessing:
90635 **
90636 **    May you do good and not evil.
90637 **    May you find forgiveness for yourself and forgive others.
90638 **    May you share freely, never taking more than you give.
90639 **
90640 *************************************************************************
90641 ** This header file defines the SQLite interface for use by
90642 ** shared libraries that want to be imported as extensions into
90643 ** an SQLite instance.  Shared libraries that intend to be loaded
90644 ** as extensions by SQLite should #include this file instead of 
90645 ** sqlcipher3.h.
90646 */
90647 #ifndef _SQLCIPHER3EXT_H_
90648 #define _SQLCIPHER3EXT_H_
90649
90650 typedef struct sqlcipher3_api_routines sqlcipher3_api_routines;
90651
90652 /*
90653 ** The following structure holds pointers to all of the SQLite API
90654 ** routines.
90655 **
90656 ** WARNING:  In order to maintain backwards compatibility, add new
90657 ** interfaces to the end of this structure only.  If you insert new
90658 ** interfaces in the middle of this structure, then older different
90659 ** versions of SQLite will not be able to load each others' shared
90660 ** libraries!
90661 */
90662 struct sqlcipher3_api_routines {
90663   void * (*aggregate_context)(sqlcipher3_context*,int nBytes);
90664   int  (*aggregate_count)(sqlcipher3_context*);
90665   int  (*bind_blob)(sqlcipher3_stmt*,int,const void*,int n,void(*)(void*));
90666   int  (*bind_double)(sqlcipher3_stmt*,int,double);
90667   int  (*bind_int)(sqlcipher3_stmt*,int,int);
90668   int  (*bind_int64)(sqlcipher3_stmt*,int,sqlcipher_int64);
90669   int  (*bind_null)(sqlcipher3_stmt*,int);
90670   int  (*bind_parameter_count)(sqlcipher3_stmt*);
90671   int  (*bind_parameter_index)(sqlcipher3_stmt*,const char*zName);
90672   const char * (*bind_parameter_name)(sqlcipher3_stmt*,int);
90673   int  (*bind_text)(sqlcipher3_stmt*,int,const char*,int n,void(*)(void*));
90674   int  (*bind_text16)(sqlcipher3_stmt*,int,const void*,int,void(*)(void*));
90675   int  (*bind_value)(sqlcipher3_stmt*,int,const sqlcipher3_value*);
90676   int  (*busy_handler)(sqlcipher3*,int(*)(void*,int),void*);
90677   int  (*busy_timeout)(sqlcipher3*,int ms);
90678   int  (*changes)(sqlcipher3*);
90679   int  (*close)(sqlcipher3*);
90680   int  (*collation_needed)(sqlcipher3*,void*,void(*)(void*,sqlcipher3*,
90681                            int eTextRep,const char*));
90682   int  (*collation_needed16)(sqlcipher3*,void*,void(*)(void*,sqlcipher3*,
90683                              int eTextRep,const void*));
90684   const void * (*column_blob)(sqlcipher3_stmt*,int iCol);
90685   int  (*column_bytes)(sqlcipher3_stmt*,int iCol);
90686   int  (*column_bytes16)(sqlcipher3_stmt*,int iCol);
90687   int  (*column_count)(sqlcipher3_stmt*pStmt);
90688   const char * (*column_database_name)(sqlcipher3_stmt*,int);
90689   const void * (*column_database_name16)(sqlcipher3_stmt*,int);
90690   const char * (*column_decltype)(sqlcipher3_stmt*,int i);
90691   const void * (*column_decltype16)(sqlcipher3_stmt*,int);
90692   double  (*column_double)(sqlcipher3_stmt*,int iCol);
90693   int  (*column_int)(sqlcipher3_stmt*,int iCol);
90694   sqlcipher_int64  (*column_int64)(sqlcipher3_stmt*,int iCol);
90695   const char * (*column_name)(sqlcipher3_stmt*,int);
90696   const void * (*column_name16)(sqlcipher3_stmt*,int);
90697   const char * (*column_origin_name)(sqlcipher3_stmt*,int);
90698   const void * (*column_origin_name16)(sqlcipher3_stmt*,int);
90699   const char * (*column_table_name)(sqlcipher3_stmt*,int);
90700   const void * (*column_table_name16)(sqlcipher3_stmt*,int);
90701   const unsigned char * (*column_text)(sqlcipher3_stmt*,int iCol);
90702   const void * (*column_text16)(sqlcipher3_stmt*,int iCol);
90703   int  (*column_type)(sqlcipher3_stmt*,int iCol);
90704   sqlcipher3_value* (*column_value)(sqlcipher3_stmt*,int iCol);
90705   void * (*commit_hook)(sqlcipher3*,int(*)(void*),void*);
90706   int  (*complete)(const char*sql);
90707   int  (*complete16)(const void*sql);
90708   int  (*create_collation)(sqlcipher3*,const char*,int,void*,
90709                            int(*)(void*,int,const void*,int,const void*));
90710   int  (*create_collation16)(sqlcipher3*,const void*,int,void*,
90711                              int(*)(void*,int,const void*,int,const void*));
90712   int  (*create_function)(sqlcipher3*,const char*,int,int,void*,
90713                           void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
90714                           void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
90715                           void (*xFinal)(sqlcipher3_context*));
90716   int  (*create_function16)(sqlcipher3*,const void*,int,int,void*,
90717                             void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
90718                             void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
90719                             void (*xFinal)(sqlcipher3_context*));
90720   int (*create_module)(sqlcipher3*,const char*,const sqlcipher3_module*,void*);
90721   int  (*data_count)(sqlcipher3_stmt*pStmt);
90722   sqlcipher3 * (*db_handle)(sqlcipher3_stmt*);
90723   int (*declare_vtab)(sqlcipher3*,const char*);
90724   int  (*enable_shared_cache)(int);
90725   int  (*errcode)(sqlcipher3*db);
90726   const char * (*errmsg)(sqlcipher3*);
90727   const void * (*errmsg16)(sqlcipher3*);
90728   int  (*exec)(sqlcipher3*,const char*,sqlcipher3_callback,void*,char**);
90729   int  (*expired)(sqlcipher3_stmt*);
90730   int  (*finalize)(sqlcipher3_stmt*pStmt);
90731   void  (*free)(void*);
90732   void  (*free_table)(char**result);
90733   int  (*get_autocommit)(sqlcipher3*);
90734   void * (*get_auxdata)(sqlcipher3_context*,int);
90735   int  (*get_table)(sqlcipher3*,const char*,char***,int*,int*,char**);
90736   int  (*global_recover)(void);
90737   void  (*interruptx)(sqlcipher3*);
90738   sqlcipher_int64  (*last_insert_rowid)(sqlcipher3*);
90739   const char * (*libversion)(void);
90740   int  (*libversion_number)(void);
90741   void *(*malloc)(int);
90742   char * (*mprintf)(const char*,...);
90743   int  (*open)(const char*,sqlcipher3**);
90744   int  (*open16)(const void*,sqlcipher3**);
90745   int  (*prepare)(sqlcipher3*,const char*,int,sqlcipher3_stmt**,const char**);
90746   int  (*prepare16)(sqlcipher3*,const void*,int,sqlcipher3_stmt**,const void**);
90747   void * (*profile)(sqlcipher3*,void(*)(void*,const char*,sqlcipher_uint64),void*);
90748   void  (*progress_handler)(sqlcipher3*,int,int(*)(void*),void*);
90749   void *(*realloc)(void*,int);
90750   int  (*reset)(sqlcipher3_stmt*pStmt);
90751   void  (*result_blob)(sqlcipher3_context*,const void*,int,void(*)(void*));
90752   void  (*result_double)(sqlcipher3_context*,double);
90753   void  (*result_error)(sqlcipher3_context*,const char*,int);
90754   void  (*result_error16)(sqlcipher3_context*,const void*,int);
90755   void  (*result_int)(sqlcipher3_context*,int);
90756   void  (*result_int64)(sqlcipher3_context*,sqlcipher_int64);
90757   void  (*result_null)(sqlcipher3_context*);
90758   void  (*result_text)(sqlcipher3_context*,const char*,int,void(*)(void*));
90759   void  (*result_text16)(sqlcipher3_context*,const void*,int,void(*)(void*));
90760   void  (*result_text16be)(sqlcipher3_context*,const void*,int,void(*)(void*));
90761   void  (*result_text16le)(sqlcipher3_context*,const void*,int,void(*)(void*));
90762   void  (*result_value)(sqlcipher3_context*,sqlcipher3_value*);
90763   void * (*rollback_hook)(sqlcipher3*,void(*)(void*),void*);
90764   int  (*set_authorizer)(sqlcipher3*,int(*)(void*,int,const char*,const char*,
90765                          const char*,const char*),void*);
90766   void  (*set_auxdata)(sqlcipher3_context*,int,void*,void (*)(void*));
90767   char * (*snprintf)(int,char*,const char*,...);
90768   int  (*step)(sqlcipher3_stmt*);
90769   int  (*table_column_metadata)(sqlcipher3*,const char*,const char*,const char*,
90770                                 char const**,char const**,int*,int*,int*);
90771   void  (*thread_cleanup)(void);
90772   int  (*total_changes)(sqlcipher3*);
90773   void * (*trace)(sqlcipher3*,void(*xTrace)(void*,const char*),void*);
90774   int  (*transfer_bindings)(sqlcipher3_stmt*,sqlcipher3_stmt*);
90775   void * (*update_hook)(sqlcipher3*,void(*)(void*,int ,char const*,char const*,
90776                                          sqlcipher_int64),void*);
90777   void * (*user_data)(sqlcipher3_context*);
90778   const void * (*value_blob)(sqlcipher3_value*);
90779   int  (*value_bytes)(sqlcipher3_value*);
90780   int  (*value_bytes16)(sqlcipher3_value*);
90781   double  (*value_double)(sqlcipher3_value*);
90782   int  (*value_int)(sqlcipher3_value*);
90783   sqlcipher_int64  (*value_int64)(sqlcipher3_value*);
90784   int  (*value_numeric_type)(sqlcipher3_value*);
90785   const unsigned char * (*value_text)(sqlcipher3_value*);
90786   const void * (*value_text16)(sqlcipher3_value*);
90787   const void * (*value_text16be)(sqlcipher3_value*);
90788   const void * (*value_text16le)(sqlcipher3_value*);
90789   int  (*value_type)(sqlcipher3_value*);
90790   char *(*vmprintf)(const char*,va_list);
90791   /* Added ??? */
90792   int (*overload_function)(sqlcipher3*, const char *zFuncName, int nArg);
90793   /* Added by 3.3.13 */
90794   int (*prepare_v2)(sqlcipher3*,const char*,int,sqlcipher3_stmt**,const char**);
90795   int (*prepare16_v2)(sqlcipher3*,const void*,int,sqlcipher3_stmt**,const void**);
90796   int (*clear_bindings)(sqlcipher3_stmt*);
90797   /* Added by 3.4.1 */
90798   int (*create_module_v2)(sqlcipher3*,const char*,const sqlcipher3_module*,void*,
90799                           void (*xDestroy)(void *));
90800   /* Added by 3.5.0 */
90801   int (*bind_zeroblob)(sqlcipher3_stmt*,int,int);
90802   int (*blob_bytes)(sqlcipher3_blob*);
90803   int (*blob_close)(sqlcipher3_blob*);
90804   int (*blob_open)(sqlcipher3*,const char*,const char*,const char*,sqlcipher3_int64,
90805                    int,sqlcipher3_blob**);
90806   int (*blob_read)(sqlcipher3_blob*,void*,int,int);
90807   int (*blob_write)(sqlcipher3_blob*,const void*,int,int);
90808   int (*create_collation_v2)(sqlcipher3*,const char*,int,void*,
90809                              int(*)(void*,int,const void*,int,const void*),
90810                              void(*)(void*));
90811   int (*file_control)(sqlcipher3*,const char*,int,void*);
90812   sqlcipher3_int64 (*memory_highwater)(int);
90813   sqlcipher3_int64 (*memory_used)(void);
90814   sqlcipher3_mutex *(*mutex_alloc)(int);
90815   void (*mutex_enter)(sqlcipher3_mutex*);
90816   void (*mutex_free)(sqlcipher3_mutex*);
90817   void (*mutex_leave)(sqlcipher3_mutex*);
90818   int (*mutex_try)(sqlcipher3_mutex*);
90819   int (*open_v2)(const char*,sqlcipher3**,int,const char*);
90820   int (*release_memory)(int);
90821   void (*result_error_nomem)(sqlcipher3_context*);
90822   void (*result_error_toobig)(sqlcipher3_context*);
90823   int (*sleep)(int);
90824   void (*soft_heap_limit)(int);
90825   sqlcipher3_vfs *(*vfs_find)(const char*);
90826   int (*vfs_register)(sqlcipher3_vfs*,int);
90827   int (*vfs_unregister)(sqlcipher3_vfs*);
90828   int (*xthreadsafe)(void);
90829   void (*result_zeroblob)(sqlcipher3_context*,int);
90830   void (*result_error_code)(sqlcipher3_context*,int);
90831   int (*test_control)(int, ...);
90832   void (*randomness)(int,void*);
90833   sqlcipher3 *(*context_db_handle)(sqlcipher3_context*);
90834   int (*extended_result_codes)(sqlcipher3*,int);
90835   int (*limit)(sqlcipher3*,int,int);
90836   sqlcipher3_stmt *(*next_stmt)(sqlcipher3*,sqlcipher3_stmt*);
90837   const char *(*sql)(sqlcipher3_stmt*);
90838   int (*status)(int,int*,int*,int);
90839   int (*backup_finish)(sqlcipher3_backup*);
90840   sqlcipher3_backup *(*backup_init)(sqlcipher3*,const char*,sqlcipher3*,const char*);
90841   int (*backup_pagecount)(sqlcipher3_backup*);
90842   int (*backup_remaining)(sqlcipher3_backup*);
90843   int (*backup_step)(sqlcipher3_backup*,int);
90844   const char *(*compileoption_get)(int);
90845   int (*compileoption_used)(const char*);
90846   int (*create_function_v2)(sqlcipher3*,const char*,int,int,void*,
90847                             void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
90848                             void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
90849                             void (*xFinal)(sqlcipher3_context*),
90850                             void(*xDestroy)(void*));
90851   int (*db_config)(sqlcipher3*,int,...);
90852   sqlcipher3_mutex *(*db_mutex)(sqlcipher3*);
90853   int (*db_status)(sqlcipher3*,int,int*,int*,int);
90854   int (*extended_errcode)(sqlcipher3*);
90855   void (*log)(int,const char*,...);
90856   sqlcipher3_int64 (*soft_heap_limit64)(sqlcipher3_int64);
90857   const char *(*sourceid)(void);
90858   int (*stmt_status)(sqlcipher3_stmt*,int,int);
90859   int (*strnicmp)(const char*,const char*,int);
90860   int (*unlock_notify)(sqlcipher3*,void(*)(void**,int),void*);
90861   int (*wal_autocheckpoint)(sqlcipher3*,int);
90862   int (*wal_checkpoint)(sqlcipher3*,const char*);
90863   void *(*wal_hook)(sqlcipher3*,int(*)(void*,sqlcipher3*,const char*,int),void*);
90864   int (*blob_reopen)(sqlcipher3_blob*,sqlcipher3_int64);
90865   int (*vtab_config)(sqlcipher3*,int op,...);
90866   int (*vtab_on_conflict)(sqlcipher3*);
90867 };
90868
90869 /*
90870 ** The following macros redefine the API routines so that they are
90871 ** redirected throught the global sqlcipher3_api structure.
90872 **
90873 ** This header file is also used by the loadext.c source file
90874 ** (part of the main SQLite library - not an extension) so that
90875 ** it can get access to the sqlcipher3_api_routines structure
90876 ** definition.  But the main library does not want to redefine
90877 ** the API.  So the redefinition macros are only valid if the
90878 ** SQLCIPHER_CORE macros is undefined.
90879 */
90880 #ifndef SQLCIPHER_CORE
90881 #define sqlcipher3_aggregate_context      sqlcipher3_api->aggregate_context
90882 #ifndef SQLCIPHER_OMIT_DEPRECATED
90883 #define sqlcipher3_aggregate_count        sqlcipher3_api->aggregate_count
90884 #endif
90885 #define sqlcipher3_bind_blob              sqlcipher3_api->bind_blob
90886 #define sqlcipher3_bind_double            sqlcipher3_api->bind_double
90887 #define sqlcipher3_bind_int               sqlcipher3_api->bind_int
90888 #define sqlcipher3_bind_int64             sqlcipher3_api->bind_int64
90889 #define sqlcipher3_bind_null              sqlcipher3_api->bind_null
90890 #define sqlcipher3_bind_parameter_count   sqlcipher3_api->bind_parameter_count
90891 #define sqlcipher3_bind_parameter_index   sqlcipher3_api->bind_parameter_index
90892 #define sqlcipher3_bind_parameter_name    sqlcipher3_api->bind_parameter_name
90893 #define sqlcipher3_bind_text              sqlcipher3_api->bind_text
90894 #define sqlcipher3_bind_text16            sqlcipher3_api->bind_text16
90895 #define sqlcipher3_bind_value             sqlcipher3_api->bind_value
90896 #define sqlcipher3_busy_handler           sqlcipher3_api->busy_handler
90897 #define sqlcipher3_busy_timeout           sqlcipher3_api->busy_timeout
90898 #define sqlcipher3_changes                sqlcipher3_api->changes
90899 #define sqlcipher3_close                  sqlcipher3_api->close
90900 #define sqlcipher3_collation_needed       sqlcipher3_api->collation_needed
90901 #define sqlcipher3_collation_needed16     sqlcipher3_api->collation_needed16
90902 #define sqlcipher3_column_blob            sqlcipher3_api->column_blob
90903 #define sqlcipher3_column_bytes           sqlcipher3_api->column_bytes
90904 #define sqlcipher3_column_bytes16         sqlcipher3_api->column_bytes16
90905 #define sqlcipher3_column_count           sqlcipher3_api->column_count
90906 #define sqlcipher3_column_database_name   sqlcipher3_api->column_database_name
90907 #define sqlcipher3_column_database_name16 sqlcipher3_api->column_database_name16
90908 #define sqlcipher3_column_decltype        sqlcipher3_api->column_decltype
90909 #define sqlcipher3_column_decltype16      sqlcipher3_api->column_decltype16
90910 #define sqlcipher3_column_double          sqlcipher3_api->column_double
90911 #define sqlcipher3_column_int             sqlcipher3_api->column_int
90912 #define sqlcipher3_column_int64           sqlcipher3_api->column_int64
90913 #define sqlcipher3_column_name            sqlcipher3_api->column_name
90914 #define sqlcipher3_column_name16          sqlcipher3_api->column_name16
90915 #define sqlcipher3_column_origin_name     sqlcipher3_api->column_origin_name
90916 #define sqlcipher3_column_origin_name16   sqlcipher3_api->column_origin_name16
90917 #define sqlcipher3_column_table_name      sqlcipher3_api->column_table_name
90918 #define sqlcipher3_column_table_name16    sqlcipher3_api->column_table_name16
90919 #define sqlcipher3_column_text            sqlcipher3_api->column_text
90920 #define sqlcipher3_column_text16          sqlcipher3_api->column_text16
90921 #define sqlcipher3_column_type            sqlcipher3_api->column_type
90922 #define sqlcipher3_column_value           sqlcipher3_api->column_value
90923 #define sqlcipher3_commit_hook            sqlcipher3_api->commit_hook
90924 #define sqlcipher3_complete               sqlcipher3_api->complete
90925 #define sqlcipher3_complete16             sqlcipher3_api->complete16
90926 #define sqlcipher3_create_collation       sqlcipher3_api->create_collation
90927 #define sqlcipher3_create_collation16     sqlcipher3_api->create_collation16
90928 #define sqlcipher3_create_function        sqlcipher3_api->create_function
90929 #define sqlcipher3_create_function16      sqlcipher3_api->create_function16
90930 #define sqlcipher3_create_module          sqlcipher3_api->create_module
90931 #define sqlcipher3_create_module_v2       sqlcipher3_api->create_module_v2
90932 #define sqlcipher3_data_count             sqlcipher3_api->data_count
90933 #define sqlcipher3_db_handle              sqlcipher3_api->db_handle
90934 #define sqlcipher3_declare_vtab           sqlcipher3_api->declare_vtab
90935 #define sqlcipher3_enable_shared_cache    sqlcipher3_api->enable_shared_cache
90936 #define sqlcipher3_errcode                sqlcipher3_api->errcode
90937 #define sqlcipher3_errmsg                 sqlcipher3_api->errmsg
90938 #define sqlcipher3_errmsg16               sqlcipher3_api->errmsg16
90939 #define sqlcipher3_exec                   sqlcipher3_api->exec
90940 #ifndef SQLCIPHER_OMIT_DEPRECATED
90941 #define sqlcipher3_expired                sqlcipher3_api->expired
90942 #endif
90943 #define sqlcipher3_finalize               sqlcipher3_api->finalize
90944 #define sqlcipher3_free                   sqlcipher3_api->free
90945 #define sqlcipher3_free_table             sqlcipher3_api->free_table
90946 #define sqlcipher3_get_autocommit         sqlcipher3_api->get_autocommit
90947 #define sqlcipher3_get_auxdata            sqlcipher3_api->get_auxdata
90948 #define sqlcipher3_get_table              sqlcipher3_api->get_table
90949 #ifndef SQLCIPHER_OMIT_DEPRECATED
90950 #define sqlcipher3_global_recover         sqlcipher3_api->global_recover
90951 #endif
90952 #define sqlcipher3_interrupt              sqlcipher3_api->interruptx
90953 #define sqlcipher3_last_insert_rowid      sqlcipher3_api->last_insert_rowid
90954 #define sqlcipher3_libversion             sqlcipher3_api->libversion
90955 #define sqlcipher3_libversion_number      sqlcipher3_api->libversion_number
90956 #define sqlcipher3_malloc                 sqlcipher3_api->malloc
90957 #define sqlcipher3_mprintf                sqlcipher3_api->mprintf
90958 #define sqlcipher3_open                   sqlcipher3_api->open
90959 #define sqlcipher3_open16                 sqlcipher3_api->open16
90960 #define sqlcipher3_prepare                sqlcipher3_api->prepare
90961 #define sqlcipher3_prepare16              sqlcipher3_api->prepare16
90962 #define sqlcipher3_prepare_v2             sqlcipher3_api->prepare_v2
90963 #define sqlcipher3_prepare16_v2           sqlcipher3_api->prepare16_v2
90964 #define sqlcipher3_profile                sqlcipher3_api->profile
90965 #define sqlcipher3_progress_handler       sqlcipher3_api->progress_handler
90966 #define sqlcipher3_realloc                sqlcipher3_api->realloc
90967 #define sqlcipher3_reset                  sqlcipher3_api->reset
90968 #define sqlcipher3_result_blob            sqlcipher3_api->result_blob
90969 #define sqlcipher3_result_double          sqlcipher3_api->result_double
90970 #define sqlcipher3_result_error           sqlcipher3_api->result_error
90971 #define sqlcipher3_result_error16         sqlcipher3_api->result_error16
90972 #define sqlcipher3_result_int             sqlcipher3_api->result_int
90973 #define sqlcipher3_result_int64           sqlcipher3_api->result_int64
90974 #define sqlcipher3_result_null            sqlcipher3_api->result_null
90975 #define sqlcipher3_result_text            sqlcipher3_api->result_text
90976 #define sqlcipher3_result_text16          sqlcipher3_api->result_text16
90977 #define sqlcipher3_result_text16be        sqlcipher3_api->result_text16be
90978 #define sqlcipher3_result_text16le        sqlcipher3_api->result_text16le
90979 #define sqlcipher3_result_value           sqlcipher3_api->result_value
90980 #define sqlcipher3_rollback_hook          sqlcipher3_api->rollback_hook
90981 #define sqlcipher3_set_authorizer         sqlcipher3_api->set_authorizer
90982 #define sqlcipher3_set_auxdata            sqlcipher3_api->set_auxdata
90983 #define sqlcipher3_snprintf               sqlcipher3_api->snprintf
90984 #define sqlcipher3_step                   sqlcipher3_api->step
90985 #define sqlcipher3_table_column_metadata  sqlcipher3_api->table_column_metadata
90986 #define sqlcipher3_thread_cleanup         sqlcipher3_api->thread_cleanup
90987 #define sqlcipher3_total_changes          sqlcipher3_api->total_changes
90988 #define sqlcipher3_trace                  sqlcipher3_api->trace
90989 #ifndef SQLCIPHER_OMIT_DEPRECATED
90990 #define sqlcipher3_transfer_bindings      sqlcipher3_api->transfer_bindings
90991 #endif
90992 #define sqlcipher3_update_hook            sqlcipher3_api->update_hook
90993 #define sqlcipher3_user_data              sqlcipher3_api->user_data
90994 #define sqlcipher3_value_blob             sqlcipher3_api->value_blob
90995 #define sqlcipher3_value_bytes            sqlcipher3_api->value_bytes
90996 #define sqlcipher3_value_bytes16          sqlcipher3_api->value_bytes16
90997 #define sqlcipher3_value_double           sqlcipher3_api->value_double
90998 #define sqlcipher3_value_int              sqlcipher3_api->value_int
90999 #define sqlcipher3_value_int64            sqlcipher3_api->value_int64
91000 #define sqlcipher3_value_numeric_type     sqlcipher3_api->value_numeric_type
91001 #define sqlcipher3_value_text             sqlcipher3_api->value_text
91002 #define sqlcipher3_value_text16           sqlcipher3_api->value_text16
91003 #define sqlcipher3_value_text16be         sqlcipher3_api->value_text16be
91004 #define sqlcipher3_value_text16le         sqlcipher3_api->value_text16le
91005 #define sqlcipher3_value_type             sqlcipher3_api->value_type
91006 #define sqlcipher3_vmprintf               sqlcipher3_api->vmprintf
91007 #define sqlcipher3_overload_function      sqlcipher3_api->overload_function
91008 #define sqlcipher3_prepare_v2             sqlcipher3_api->prepare_v2
91009 #define sqlcipher3_prepare16_v2           sqlcipher3_api->prepare16_v2
91010 #define sqlcipher3_clear_bindings         sqlcipher3_api->clear_bindings
91011 #define sqlcipher3_bind_zeroblob          sqlcipher3_api->bind_zeroblob
91012 #define sqlcipher3_blob_bytes             sqlcipher3_api->blob_bytes
91013 #define sqlcipher3_blob_close             sqlcipher3_api->blob_close
91014 #define sqlcipher3_blob_open              sqlcipher3_api->blob_open
91015 #define sqlcipher3_blob_read              sqlcipher3_api->blob_read
91016 #define sqlcipher3_blob_write             sqlcipher3_api->blob_write
91017 #define sqlcipher3_create_collation_v2    sqlcipher3_api->create_collation_v2
91018 #define sqlcipher3_file_control           sqlcipher3_api->file_control
91019 #define sqlcipher3_memory_highwater       sqlcipher3_api->memory_highwater
91020 #define sqlcipher3_memory_used            sqlcipher3_api->memory_used
91021 #define sqlcipher3_mutex_alloc            sqlcipher3_api->mutex_alloc
91022 #define sqlcipher3_mutex_enter            sqlcipher3_api->mutex_enter
91023 #define sqlcipher3_mutex_free             sqlcipher3_api->mutex_free
91024 #define sqlcipher3_mutex_leave            sqlcipher3_api->mutex_leave
91025 #define sqlcipher3_mutex_try              sqlcipher3_api->mutex_try
91026 #define sqlcipher3_open_v2                sqlcipher3_api->open_v2
91027 #define sqlcipher3_release_memory         sqlcipher3_api->release_memory
91028 #define sqlcipher3_result_error_nomem     sqlcipher3_api->result_error_nomem
91029 #define sqlcipher3_result_error_toobig    sqlcipher3_api->result_error_toobig
91030 #define sqlcipher3_sleep                  sqlcipher3_api->sleep
91031 #define sqlcipher3_soft_heap_limit        sqlcipher3_api->soft_heap_limit
91032 #define sqlcipher3_vfs_find               sqlcipher3_api->vfs_find
91033 #define sqlcipher3_vfs_register           sqlcipher3_api->vfs_register
91034 #define sqlcipher3_vfs_unregister         sqlcipher3_api->vfs_unregister
91035 #define sqlcipher3_threadsafe             sqlcipher3_api->xthreadsafe
91036 #define sqlcipher3_result_zeroblob        sqlcipher3_api->result_zeroblob
91037 #define sqlcipher3_result_error_code      sqlcipher3_api->result_error_code
91038 #define sqlcipher3_test_control           sqlcipher3_api->test_control
91039 #define sqlcipher3_randomness             sqlcipher3_api->randomness
91040 #define sqlcipher3_context_db_handle      sqlcipher3_api->context_db_handle
91041 #define sqlcipher3_extended_result_codes  sqlcipher3_api->extended_result_codes
91042 #define sqlcipher3_limit                  sqlcipher3_api->limit
91043 #define sqlcipher3_next_stmt              sqlcipher3_api->next_stmt
91044 #define sqlcipher3_sql                    sqlcipher3_api->sql
91045 #define sqlcipher3_status                 sqlcipher3_api->status
91046 #define sqlcipher3_backup_finish          sqlcipher3_api->backup_finish
91047 #define sqlcipher3_backup_init            sqlcipher3_api->backup_init
91048 #define sqlcipher3_backup_pagecount       sqlcipher3_api->backup_pagecount
91049 #define sqlcipher3_backup_remaining       sqlcipher3_api->backup_remaining
91050 #define sqlcipher3_backup_step            sqlcipher3_api->backup_step
91051 #define sqlcipher3_compileoption_get      sqlcipher3_api->compileoption_get
91052 #define sqlcipher3_compileoption_used     sqlcipher3_api->compileoption_used
91053 #define sqlcipher3_create_function_v2     sqlcipher3_api->create_function_v2
91054 #define sqlcipher3_db_config              sqlcipher3_api->db_config
91055 #define sqlcipher3_db_mutex               sqlcipher3_api->db_mutex
91056 #define sqlcipher3_db_status              sqlcipher3_api->db_status
91057 #define sqlcipher3_extended_errcode       sqlcipher3_api->extended_errcode
91058 #define sqlcipher3_log                    sqlcipher3_api->log
91059 #define sqlcipher3_soft_heap_limit64      sqlcipher3_api->soft_heap_limit64
91060 #define sqlcipher3_sourceid               sqlcipher3_api->sourceid
91061 #define sqlcipher3_stmt_status            sqlcipher3_api->stmt_status
91062 #define sqlcipher3_strnicmp               sqlcipher3_api->strnicmp
91063 #define sqlcipher3_unlock_notify          sqlcipher3_api->unlock_notify
91064 #define sqlcipher3_wal_autocheckpoint     sqlcipher3_api->wal_autocheckpoint
91065 #define sqlcipher3_wal_checkpoint         sqlcipher3_api->wal_checkpoint
91066 #define sqlcipher3_wal_hook               sqlcipher3_api->wal_hook
91067 #define sqlcipher3_blob_reopen            sqlcipher3_api->blob_reopen
91068 #define sqlcipher3_vtab_config            sqlcipher3_api->vtab_config
91069 #define sqlcipher3_vtab_on_conflict       sqlcipher3_api->vtab_on_conflict
91070 #endif /* SQLCIPHER_CORE */
91071
91072 #define SQLCIPHER_EXTENSION_INIT1     const sqlcipher3_api_routines *sqlcipher3_api = 0;
91073 #define SQLCIPHER_EXTENSION_INIT2(v)  sqlcipher3_api = v;
91074
91075 #endif /* _SQLCIPHER3EXT_H_ */
91076
91077 /************** End of sqlcipher3ext.h ******************************************/
91078 /************** Continuing where we left off in loadext.c ********************/
91079 /* #include <string.h> */
91080
91081 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
91082
91083 /*
91084 ** Some API routines are omitted when various features are
91085 ** excluded from a build of SQLite.  Substitute a NULL pointer
91086 ** for any missing APIs.
91087 */
91088 #ifndef SQLCIPHER_ENABLE_COLUMN_METADATA
91089 # define sqlcipher3_column_database_name   0
91090 # define sqlcipher3_column_database_name16 0
91091 # define sqlcipher3_column_table_name      0
91092 # define sqlcipher3_column_table_name16    0
91093 # define sqlcipher3_column_origin_name     0
91094 # define sqlcipher3_column_origin_name16   0
91095 # define sqlcipher3_table_column_metadata  0
91096 #endif
91097
91098 #ifdef SQLCIPHER_OMIT_AUTHORIZATION
91099 # define sqlcipher3_set_authorizer         0
91100 #endif
91101
91102 #ifdef SQLCIPHER_OMIT_UTF16
91103 # define sqlcipher3_bind_text16            0
91104 # define sqlcipher3_collation_needed16     0
91105 # define sqlcipher3_column_decltype16      0
91106 # define sqlcipher3_column_name16          0
91107 # define sqlcipher3_column_text16          0
91108 # define sqlcipher3_complete16             0
91109 # define sqlcipher3_create_collation16     0
91110 # define sqlcipher3_create_function16      0
91111 # define sqlcipher3_errmsg16               0
91112 # define sqlcipher3_open16                 0
91113 # define sqlcipher3_prepare16              0
91114 # define sqlcipher3_prepare16_v2           0
91115 # define sqlcipher3_result_error16         0
91116 # define sqlcipher3_result_text16          0
91117 # define sqlcipher3_result_text16be        0
91118 # define sqlcipher3_result_text16le        0
91119 # define sqlcipher3_value_text16           0
91120 # define sqlcipher3_value_text16be         0
91121 # define sqlcipher3_value_text16le         0
91122 # define sqlcipher3_column_database_name16 0
91123 # define sqlcipher3_column_table_name16    0
91124 # define sqlcipher3_column_origin_name16   0
91125 #endif
91126
91127 #ifdef SQLCIPHER_OMIT_COMPLETE
91128 # define sqlcipher3_complete 0
91129 # define sqlcipher3_complete16 0
91130 #endif
91131
91132 #ifdef SQLCIPHER_OMIT_DECLTYPE
91133 # define sqlcipher3_column_decltype16      0
91134 # define sqlcipher3_column_decltype        0
91135 #endif
91136
91137 #ifdef SQLCIPHER_OMIT_PROGRESS_CALLBACK
91138 # define sqlcipher3_progress_handler 0
91139 #endif
91140
91141 #ifdef SQLCIPHER_OMIT_VIRTUALTABLE
91142 # define sqlcipher3_create_module 0
91143 # define sqlcipher3_create_module_v2 0
91144 # define sqlcipher3_declare_vtab 0
91145 # define sqlcipher3_vtab_config 0
91146 # define sqlcipher3_vtab_on_conflict 0
91147 #endif
91148
91149 #ifdef SQLCIPHER_OMIT_SHARED_CACHE
91150 # define sqlcipher3_enable_shared_cache 0
91151 #endif
91152
91153 #ifdef SQLCIPHER_OMIT_TRACE
91154 # define sqlcipher3_profile       0
91155 # define sqlcipher3_trace         0
91156 #endif
91157
91158 #ifdef SQLCIPHER_OMIT_GET_TABLE
91159 # define sqlcipher3_free_table    0
91160 # define sqlcipher3_get_table     0
91161 #endif
91162
91163 #ifdef SQLCIPHER_OMIT_INCRBLOB
91164 #define sqlcipher3_bind_zeroblob  0
91165 #define sqlcipher3_blob_bytes     0
91166 #define sqlcipher3_blob_close     0
91167 #define sqlcipher3_blob_open      0
91168 #define sqlcipher3_blob_read      0
91169 #define sqlcipher3_blob_write     0
91170 #define sqlcipher3_blob_reopen    0
91171 #endif
91172
91173 /*
91174 ** The following structure contains pointers to all SQLite API routines.
91175 ** A pointer to this structure is passed into extensions when they are
91176 ** loaded so that the extension can make calls back into the SQLite
91177 ** library.
91178 **
91179 ** When adding new APIs, add them to the bottom of this structure
91180 ** in order to preserve backwards compatibility.
91181 **
91182 ** Extensions that use newer APIs should first call the
91183 ** sqlcipher3_libversion_number() to make sure that the API they
91184 ** intend to use is supported by the library.  Extensions should
91185 ** also check to make sure that the pointer to the function is
91186 ** not NULL before calling it.
91187 */
91188 static const sqlcipher3_api_routines sqlcipher3Apis = {
91189   sqlcipher3_aggregate_context,
91190 #ifndef SQLCIPHER_OMIT_DEPRECATED
91191   sqlcipher3_aggregate_count,
91192 #else
91193   0,
91194 #endif
91195   sqlcipher3_bind_blob,
91196   sqlcipher3_bind_double,
91197   sqlcipher3_bind_int,
91198   sqlcipher3_bind_int64,
91199   sqlcipher3_bind_null,
91200   sqlcipher3_bind_parameter_count,
91201   sqlcipher3_bind_parameter_index,
91202   sqlcipher3_bind_parameter_name,
91203   sqlcipher3_bind_text,
91204   sqlcipher3_bind_text16,
91205   sqlcipher3_bind_value,
91206   sqlcipher3_busy_handler,
91207   sqlcipher3_busy_timeout,
91208   sqlcipher3_changes,
91209   sqlcipher3_close,
91210   sqlcipher3_collation_needed,
91211   sqlcipher3_collation_needed16,
91212   sqlcipher3_column_blob,
91213   sqlcipher3_column_bytes,
91214   sqlcipher3_column_bytes16,
91215   sqlcipher3_column_count,
91216   sqlcipher3_column_database_name,
91217   sqlcipher3_column_database_name16,
91218   sqlcipher3_column_decltype,
91219   sqlcipher3_column_decltype16,
91220   sqlcipher3_column_double,
91221   sqlcipher3_column_int,
91222   sqlcipher3_column_int64,
91223   sqlcipher3_column_name,
91224   sqlcipher3_column_name16,
91225   sqlcipher3_column_origin_name,
91226   sqlcipher3_column_origin_name16,
91227   sqlcipher3_column_table_name,
91228   sqlcipher3_column_table_name16,
91229   sqlcipher3_column_text,
91230   sqlcipher3_column_text16,
91231   sqlcipher3_column_type,
91232   sqlcipher3_column_value,
91233   sqlcipher3_commit_hook,
91234   sqlcipher3_complete,
91235   sqlcipher3_complete16,
91236   sqlcipher3_create_collation,
91237   sqlcipher3_create_collation16,
91238   sqlcipher3_create_function,
91239   sqlcipher3_create_function16,
91240   sqlcipher3_create_module,
91241   sqlcipher3_data_count,
91242   sqlcipher3_db_handle,
91243   sqlcipher3_declare_vtab,
91244   sqlcipher3_enable_shared_cache,
91245   sqlcipher3_errcode,
91246   sqlcipher3_errmsg,
91247   sqlcipher3_errmsg16,
91248   sqlcipher3_exec,
91249 #ifndef SQLCIPHER_OMIT_DEPRECATED
91250   sqlcipher3_expired,
91251 #else
91252   0,
91253 #endif
91254   sqlcipher3_finalize,
91255   sqlcipher3_free,
91256   sqlcipher3_free_table,
91257   sqlcipher3_get_autocommit,
91258   sqlcipher3_get_auxdata,
91259   sqlcipher3_get_table,
91260   0,     /* Was sqlcipher3_global_recover(), but that function is deprecated */
91261   sqlcipher3_interrupt,
91262   sqlcipher3_last_insert_rowid,
91263   sqlcipher3_libversion,
91264   sqlcipher3_libversion_number,
91265   sqlcipher3_malloc,
91266   sqlcipher3_mprintf,
91267   sqlcipher3_open,
91268   sqlcipher3_open16,
91269   sqlcipher3_prepare,
91270   sqlcipher3_prepare16,
91271   sqlcipher3_profile,
91272   sqlcipher3_progress_handler,
91273   sqlcipher3_realloc,
91274   sqlcipher3_reset,
91275   sqlcipher3_result_blob,
91276   sqlcipher3_result_double,
91277   sqlcipher3_result_error,
91278   sqlcipher3_result_error16,
91279   sqlcipher3_result_int,
91280   sqlcipher3_result_int64,
91281   sqlcipher3_result_null,
91282   sqlcipher3_result_text,
91283   sqlcipher3_result_text16,
91284   sqlcipher3_result_text16be,
91285   sqlcipher3_result_text16le,
91286   sqlcipher3_result_value,
91287   sqlcipher3_rollback_hook,
91288   sqlcipher3_set_authorizer,
91289   sqlcipher3_set_auxdata,
91290   sqlcipher3_snprintf,
91291   sqlcipher3_step,
91292   sqlcipher3_table_column_metadata,
91293 #ifndef SQLCIPHER_OMIT_DEPRECATED
91294   sqlcipher3_thread_cleanup,
91295 #else
91296   0,
91297 #endif
91298   sqlcipher3_total_changes,
91299   sqlcipher3_trace,
91300 #ifndef SQLCIPHER_OMIT_DEPRECATED
91301   sqlcipher3_transfer_bindings,
91302 #else
91303   0,
91304 #endif
91305   sqlcipher3_update_hook,
91306   sqlcipher3_user_data,
91307   sqlcipher3_value_blob,
91308   sqlcipher3_value_bytes,
91309   sqlcipher3_value_bytes16,
91310   sqlcipher3_value_double,
91311   sqlcipher3_value_int,
91312   sqlcipher3_value_int64,
91313   sqlcipher3_value_numeric_type,
91314   sqlcipher3_value_text,
91315   sqlcipher3_value_text16,
91316   sqlcipher3_value_text16be,
91317   sqlcipher3_value_text16le,
91318   sqlcipher3_value_type,
91319   sqlcipher3_vmprintf,
91320   /*
91321   ** The original API set ends here.  All extensions can call any
91322   ** of the APIs above provided that the pointer is not NULL.  But
91323   ** before calling APIs that follow, extension should check the
91324   ** sqlcipher3_libversion_number() to make sure they are dealing with
91325   ** a library that is new enough to support that API.
91326   *************************************************************************
91327   */
91328   sqlcipher3_overload_function,
91329
91330   /*
91331   ** Added after 3.3.13
91332   */
91333   sqlcipher3_prepare_v2,
91334   sqlcipher3_prepare16_v2,
91335   sqlcipher3_clear_bindings,
91336
91337   /*
91338   ** Added for 3.4.1
91339   */
91340   sqlcipher3_create_module_v2,
91341
91342   /*
91343   ** Added for 3.5.0
91344   */
91345   sqlcipher3_bind_zeroblob,
91346   sqlcipher3_blob_bytes,
91347   sqlcipher3_blob_close,
91348   sqlcipher3_blob_open,
91349   sqlcipher3_blob_read,
91350   sqlcipher3_blob_write,
91351   sqlcipher3_create_collation_v2,
91352   sqlcipher3_file_control,
91353   sqlcipher3_memory_highwater,
91354   sqlcipher3_memory_used,
91355 #ifdef SQLCIPHER_MUTEX_OMIT
91356   0, 
91357   0, 
91358   0,
91359   0,
91360   0,
91361 #else
91362   sqlcipher3_mutex_alloc,
91363   sqlcipher3_mutex_enter,
91364   sqlcipher3_mutex_free,
91365   sqlcipher3_mutex_leave,
91366   sqlcipher3_mutex_try,
91367 #endif
91368   sqlcipher3_open_v2,
91369   sqlcipher3_release_memory,
91370   sqlcipher3_result_error_nomem,
91371   sqlcipher3_result_error_toobig,
91372   sqlcipher3_sleep,
91373   sqlcipher3_soft_heap_limit,
91374   sqlcipher3_vfs_find,
91375   sqlcipher3_vfs_register,
91376   sqlcipher3_vfs_unregister,
91377
91378   /*
91379   ** Added for 3.5.8
91380   */
91381   sqlcipher3_threadsafe,
91382   sqlcipher3_result_zeroblob,
91383   sqlcipher3_result_error_code,
91384   sqlcipher3_test_control,
91385   sqlcipher3_randomness,
91386   sqlcipher3_context_db_handle,
91387
91388   /*
91389   ** Added for 3.6.0
91390   */
91391   sqlcipher3_extended_result_codes,
91392   sqlcipher3_limit,
91393   sqlcipher3_next_stmt,
91394   sqlcipher3_sql,
91395   sqlcipher3_status,
91396
91397   /*
91398   ** Added for 3.7.4
91399   */
91400   sqlcipher3_backup_finish,
91401   sqlcipher3_backup_init,
91402   sqlcipher3_backup_pagecount,
91403   sqlcipher3_backup_remaining,
91404   sqlcipher3_backup_step,
91405 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
91406   sqlcipher3_compileoption_get,
91407   sqlcipher3_compileoption_used,
91408 #else
91409   0,
91410   0,
91411 #endif
91412   sqlcipher3_create_function_v2,
91413   sqlcipher3_db_config,
91414   sqlcipher3_db_mutex,
91415   sqlcipher3_db_status,
91416   sqlcipher3_extended_errcode,
91417   sqlcipher3_log,
91418   sqlcipher3_soft_heap_limit64,
91419   sqlcipher3_sourceid,
91420   sqlcipher3_stmt_status,
91421   sqlcipher3_strnicmp,
91422 #ifdef SQLCIPHER_ENABLE_UNLOCK_NOTIFY
91423   sqlcipher3_unlock_notify,
91424 #else
91425   0,
91426 #endif
91427 #ifndef SQLCIPHER_OMIT_WAL
91428   sqlcipher3_wal_autocheckpoint,
91429   sqlcipher3_wal_checkpoint,
91430   sqlcipher3_wal_hook,
91431 #else
91432   0,
91433   0,
91434   0,
91435 #endif
91436   sqlcipher3_blob_reopen,
91437   sqlcipher3_vtab_config,
91438   sqlcipher3_vtab_on_conflict,
91439 };
91440
91441 /*
91442 ** Attempt to load an SQLite extension library contained in the file
91443 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
91444 ** default entry point name (sqlcipher3_extension_init) is used.  Use
91445 ** of the default name is recommended.
91446 **
91447 ** Return SQLCIPHER_OK on success and SQLCIPHER_ERROR if something goes wrong.
91448 **
91449 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
91450 ** error message text.  The calling function should free this memory
91451 ** by calling sqlcipher3DbFree(db, ).
91452 */
91453 static int sqlcipher3LoadExtension(
91454   sqlcipher3 *db,          /* Load the extension into this database connection */
91455   const char *zFile,    /* Name of the shared library containing extension */
91456   const char *zProc,    /* Entry point.  Use "sqlcipher3_extension_init" if 0 */
91457   char **pzErrMsg       /* Put error message here if not 0 */
91458 ){
91459   sqlcipher3_vfs *pVfs = db->pVfs;
91460   void *handle;
91461   int (*xInit)(sqlcipher3*,char**,const sqlcipher3_api_routines*);
91462   char *zErrmsg = 0;
91463   void **aHandle;
91464   int nMsg = 300 + sqlcipher3Strlen30(zFile);
91465
91466   if( pzErrMsg ) *pzErrMsg = 0;
91467
91468   /* Ticket #1863.  To avoid a creating security problems for older
91469   ** applications that relink against newer versions of SQLite, the
91470   ** ability to run load_extension is turned off by default.  One
91471   ** must call sqlcipher3_enable_load_extension() to turn on extension
91472   ** loading.  Otherwise you get the following error.
91473   */
91474   if( (db->flags & SQLCIPHER_LoadExtension)==0 ){
91475     if( pzErrMsg ){
91476       *pzErrMsg = sqlcipher3_mprintf("not authorized");
91477     }
91478     return SQLCIPHER_ERROR;
91479   }
91480
91481   if( zProc==0 ){
91482     zProc = "sqlcipher3_extension_init";
91483   }
91484
91485   handle = sqlcipher3OsDlOpen(pVfs, zFile);
91486   if( handle==0 ){
91487     if( pzErrMsg ){
91488       *pzErrMsg = zErrmsg = sqlcipher3_malloc(nMsg);
91489       if( zErrmsg ){
91490         sqlcipher3_snprintf(nMsg, zErrmsg, 
91491             "unable to open shared library [%s]", zFile);
91492         sqlcipher3OsDlError(pVfs, nMsg-1, zErrmsg);
91493       }
91494     }
91495     return SQLCIPHER_ERROR;
91496   }
91497   xInit = (int(*)(sqlcipher3*,char**,const sqlcipher3_api_routines*))
91498                    sqlcipher3OsDlSym(pVfs, handle, zProc);
91499   if( xInit==0 ){
91500     if( pzErrMsg ){
91501       nMsg += sqlcipher3Strlen30(zProc);
91502       *pzErrMsg = zErrmsg = sqlcipher3_malloc(nMsg);
91503       if( zErrmsg ){
91504         sqlcipher3_snprintf(nMsg, zErrmsg,
91505             "no entry point [%s] in shared library [%s]", zProc,zFile);
91506         sqlcipher3OsDlError(pVfs, nMsg-1, zErrmsg);
91507       }
91508       sqlcipher3OsDlClose(pVfs, handle);
91509     }
91510     return SQLCIPHER_ERROR;
91511   }else if( xInit(db, &zErrmsg, &sqlcipher3Apis) ){
91512     if( pzErrMsg ){
91513       *pzErrMsg = sqlcipher3_mprintf("error during initialization: %s", zErrmsg);
91514     }
91515     sqlcipher3_free(zErrmsg);
91516     sqlcipher3OsDlClose(pVfs, handle);
91517     return SQLCIPHER_ERROR;
91518   }
91519
91520   /* Append the new shared library handle to the db->aExtension array. */
91521   aHandle = sqlcipher3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
91522   if( aHandle==0 ){
91523     return SQLCIPHER_NOMEM;
91524   }
91525   if( db->nExtension>0 ){
91526     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
91527   }
91528   sqlcipher3DbFree(db, db->aExtension);
91529   db->aExtension = aHandle;
91530
91531   db->aExtension[db->nExtension++] = handle;
91532   return SQLCIPHER_OK;
91533 }
91534 SQLCIPHER_API int sqlcipher3_load_extension(
91535   sqlcipher3 *db,          /* Load the extension into this database connection */
91536   const char *zFile,    /* Name of the shared library containing extension */
91537   const char *zProc,    /* Entry point.  Use "sqlcipher3_extension_init" if 0 */
91538   char **pzErrMsg       /* Put error message here if not 0 */
91539 ){
91540   int rc;
91541   sqlcipher3_mutex_enter(db->mutex);
91542   rc = sqlcipher3LoadExtension(db, zFile, zProc, pzErrMsg);
91543   rc = sqlcipher3ApiExit(db, rc);
91544   sqlcipher3_mutex_leave(db->mutex);
91545   return rc;
91546 }
91547
91548 /*
91549 ** Call this routine when the database connection is closing in order
91550 ** to clean up loaded extensions
91551 */
91552 SQLCIPHER_PRIVATE void sqlcipher3CloseExtensions(sqlcipher3 *db){
91553   int i;
91554   assert( sqlcipher3_mutex_held(db->mutex) );
91555   for(i=0; i<db->nExtension; i++){
91556     sqlcipher3OsDlClose(db->pVfs, db->aExtension[i]);
91557   }
91558   sqlcipher3DbFree(db, db->aExtension);
91559 }
91560
91561 /*
91562 ** Enable or disable extension loading.  Extension loading is disabled by
91563 ** default so as not to open security holes in older applications.
91564 */
91565 SQLCIPHER_API int sqlcipher3_enable_load_extension(sqlcipher3 *db, int onoff){
91566   sqlcipher3_mutex_enter(db->mutex);
91567   if( onoff ){
91568     db->flags |= SQLCIPHER_LoadExtension;
91569   }else{
91570     db->flags &= ~SQLCIPHER_LoadExtension;
91571   }
91572   sqlcipher3_mutex_leave(db->mutex);
91573   return SQLCIPHER_OK;
91574 }
91575
91576 #endif /* SQLCIPHER_OMIT_LOAD_EXTENSION */
91577
91578 /*
91579 ** The auto-extension code added regardless of whether or not extension
91580 ** loading is supported.  We need a dummy sqlcipher3Apis pointer for that
91581 ** code if regular extension loading is not available.  This is that
91582 ** dummy pointer.
91583 */
91584 #ifdef SQLCIPHER_OMIT_LOAD_EXTENSION
91585 static const sqlcipher3_api_routines sqlcipher3Apis = { 0 };
91586 #endif
91587
91588
91589 /*
91590 ** The following object holds the list of automatically loaded
91591 ** extensions.
91592 **
91593 ** This list is shared across threads.  The SQLCIPHER_MUTEX_STATIC_MASTER
91594 ** mutex must be held while accessing this list.
91595 */
91596 typedef struct sqlcipher3AutoExtList sqlcipher3AutoExtList;
91597 static SQLCIPHER_WSD struct sqlcipher3AutoExtList {
91598   int nExt;              /* Number of entries in aExt[] */          
91599   void (**aExt)(void);   /* Pointers to the extension init functions */
91600 } sqlcipher3Autoext = { 0, 0 };
91601
91602 /* The "wsdAutoext" macro will resolve to the autoextension
91603 ** state vector.  If writable static data is unsupported on the target,
91604 ** we have to locate the state vector at run-time.  In the more common
91605 ** case where writable static data is supported, wsdStat can refer directly
91606 ** to the "sqlcipher3Autoext" state vector declared above.
91607 */
91608 #ifdef SQLCIPHER_OMIT_WSD
91609 # define wsdAutoextInit \
91610   sqlcipher3AutoExtList *x = &GLOBAL(sqlcipher3AutoExtList,sqlcipher3Autoext)
91611 # define wsdAutoext x[0]
91612 #else
91613 # define wsdAutoextInit
91614 # define wsdAutoext sqlcipher3Autoext
91615 #endif
91616
91617
91618 /*
91619 ** Register a statically linked extension that is automatically
91620 ** loaded by every new database connection.
91621 */
91622 SQLCIPHER_API int sqlcipher3_auto_extension(void (*xInit)(void)){
91623   int rc = SQLCIPHER_OK;
91624 #ifndef SQLCIPHER_OMIT_AUTOINIT
91625   rc = sqlcipher3_initialize();
91626   if( rc ){
91627     return rc;
91628   }else
91629 #endif
91630   {
91631     int i;
91632 #if SQLCIPHER_THREADSAFE
91633     sqlcipher3_mutex *mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
91634 #endif
91635     wsdAutoextInit;
91636     sqlcipher3_mutex_enter(mutex);
91637     for(i=0; i<wsdAutoext.nExt; i++){
91638       if( wsdAutoext.aExt[i]==xInit ) break;
91639     }
91640     if( i==wsdAutoext.nExt ){
91641       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
91642       void (**aNew)(void);
91643       aNew = sqlcipher3_realloc(wsdAutoext.aExt, nByte);
91644       if( aNew==0 ){
91645         rc = SQLCIPHER_NOMEM;
91646       }else{
91647         wsdAutoext.aExt = aNew;
91648         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
91649         wsdAutoext.nExt++;
91650       }
91651     }
91652     sqlcipher3_mutex_leave(mutex);
91653     assert( (rc&0xff)==rc );
91654     return rc;
91655   }
91656 }
91657
91658 /*
91659 ** Reset the automatic extension loading mechanism.
91660 */
91661 SQLCIPHER_API void sqlcipher3_reset_auto_extension(void){
91662 #ifndef SQLCIPHER_OMIT_AUTOINIT
91663   if( sqlcipher3_initialize()==SQLCIPHER_OK )
91664 #endif
91665   {
91666 #if SQLCIPHER_THREADSAFE
91667     sqlcipher3_mutex *mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
91668 #endif
91669     wsdAutoextInit;
91670     sqlcipher3_mutex_enter(mutex);
91671     sqlcipher3_free(wsdAutoext.aExt);
91672     wsdAutoext.aExt = 0;
91673     wsdAutoext.nExt = 0;
91674     sqlcipher3_mutex_leave(mutex);
91675   }
91676 }
91677
91678 /*
91679 ** Load all automatic extensions.
91680 **
91681 ** If anything goes wrong, set an error in the database connection.
91682 */
91683 SQLCIPHER_PRIVATE void sqlcipher3AutoLoadExtensions(sqlcipher3 *db){
91684   int i;
91685   int go = 1;
91686   int (*xInit)(sqlcipher3*,char**,const sqlcipher3_api_routines*);
91687
91688   wsdAutoextInit;
91689   if( wsdAutoext.nExt==0 ){
91690     /* Common case: early out without every having to acquire a mutex */
91691     return;
91692   }
91693   for(i=0; go; i++){
91694     char *zErrmsg;
91695 #if SQLCIPHER_THREADSAFE
91696     sqlcipher3_mutex *mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
91697 #endif
91698     sqlcipher3_mutex_enter(mutex);
91699     if( i>=wsdAutoext.nExt ){
91700       xInit = 0;
91701       go = 0;
91702     }else{
91703       xInit = (int(*)(sqlcipher3*,char**,const sqlcipher3_api_routines*))
91704               wsdAutoext.aExt[i];
91705     }
91706     sqlcipher3_mutex_leave(mutex);
91707     zErrmsg = 0;
91708     if( xInit && xInit(db, &zErrmsg, &sqlcipher3Apis) ){
91709       sqlcipher3Error(db, SQLCIPHER_ERROR,
91710             "automatic extension loading failed: %s", zErrmsg);
91711       go = 0;
91712     }
91713     sqlcipher3_free(zErrmsg);
91714   }
91715 }
91716
91717 /************** End of loadext.c *********************************************/
91718 /************** Begin file pragma.c ******************************************/
91719 /*
91720 ** 2003 April 6
91721 **
91722 ** The author disclaims copyright to this source code.  In place of
91723 ** a legal notice, here is a blessing:
91724 **
91725 **    May you do good and not evil.
91726 **    May you find forgiveness for yourself and forgive others.
91727 **    May you share freely, never taking more than you give.
91728 **
91729 *************************************************************************
91730 ** This file contains code used to implement the PRAGMA command.
91731 */
91732
91733 /*
91734 ** Interpret the given string as a safety level.  Return 0 for OFF,
91735 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
91736 ** unrecognized string argument.
91737 **
91738 ** Note that the values returned are one less that the values that
91739 ** should be passed into sqlcipher3BtreeSetSafetyLevel().  The is done
91740 ** to support legacy SQL code.  The safety level used to be boolean
91741 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
91742 */
91743 static u8 getSafetyLevel(const char *z){
91744                              /* 123456789 123456789 */
91745   static const char zText[] = "onoffalseyestruefull";
91746   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
91747   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
91748   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
91749   int i, n;
91750   if( sqlcipher3Isdigit(*z) ){
91751     return (u8)sqlcipher3Atoi(z);
91752   }
91753   n = sqlcipher3Strlen30(z);
91754   for(i=0; i<ArraySize(iLength); i++){
91755     if( iLength[i]==n && sqlcipher3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
91756       return iValue[i];
91757     }
91758   }
91759   return 1;
91760 }
91761
91762 /*
91763 ** Interpret the given string as a boolean value.
91764 */
91765 SQLCIPHER_PRIVATE u8 sqlcipher3GetBoolean(const char *z){
91766   return getSafetyLevel(z)&1;
91767 }
91768
91769 /* The sqlcipher3GetBoolean() function is used by other modules but the
91770 ** remainder of this file is specific to PRAGMA processing.  So omit
91771 ** the rest of the file if PRAGMAs are omitted from the build.
91772 */
91773 #if !defined(SQLCIPHER_OMIT_PRAGMA)
91774
91775 /*
91776 ** Interpret the given string as a locking mode value.
91777 */
91778 static int getLockingMode(const char *z){
91779   if( z ){
91780     if( 0==sqlcipher3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
91781     if( 0==sqlcipher3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
91782   }
91783   return PAGER_LOCKINGMODE_QUERY;
91784 }
91785
91786 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
91787 /*
91788 ** Interpret the given string as an auto-vacuum mode value.
91789 **
91790 ** The following strings, "none", "full" and "incremental" are 
91791 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
91792 */
91793 static int getAutoVacuum(const char *z){
91794   int i;
91795   if( 0==sqlcipher3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
91796   if( 0==sqlcipher3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
91797   if( 0==sqlcipher3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
91798   i = sqlcipher3Atoi(z);
91799   return (u8)((i>=0&&i<=2)?i:0);
91800 }
91801 #endif /* ifndef SQLCIPHER_OMIT_AUTOVACUUM */
91802
91803 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
91804 /*
91805 ** Interpret the given string as a temp db location. Return 1 for file
91806 ** backed temporary databases, 2 for the Red-Black tree in memory database
91807 ** and 0 to use the compile-time default.
91808 */
91809 static int getTempStore(const char *z){
91810   if( z[0]>='0' && z[0]<='2' ){
91811     return z[0] - '0';
91812   }else if( sqlcipher3StrICmp(z, "file")==0 ){
91813     return 1;
91814   }else if( sqlcipher3StrICmp(z, "memory")==0 ){
91815     return 2;
91816   }else{
91817     return 0;
91818   }
91819 }
91820 #endif /* SQLCIPHER_PAGER_PRAGMAS */
91821
91822 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
91823 /*
91824 ** Invalidate temp storage, either when the temp storage is changed
91825 ** from default, or when 'file' and the temp_store_directory has changed
91826 */
91827 static int invalidateTempStorage(Parse *pParse){
91828   sqlcipher3 *db = pParse->db;
91829   if( db->aDb[1].pBt!=0 ){
91830     if( !db->autoCommit || sqlcipher3BtreeIsInReadTrans(db->aDb[1].pBt) ){
91831       sqlcipher3ErrorMsg(pParse, "temporary storage cannot be changed "
91832         "from within a transaction");
91833       return SQLCIPHER_ERROR;
91834     }
91835     sqlcipher3BtreeClose(db->aDb[1].pBt);
91836     db->aDb[1].pBt = 0;
91837     sqlcipher3ResetInternalSchema(db, -1);
91838   }
91839   return SQLCIPHER_OK;
91840 }
91841 #endif /* SQLCIPHER_PAGER_PRAGMAS */
91842
91843 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
91844 /*
91845 ** If the TEMP database is open, close it and mark the database schema
91846 ** as needing reloading.  This must be done when using the SQLCIPHER_TEMP_STORE
91847 ** or DEFAULT_TEMP_STORE pragmas.
91848 */
91849 static int changeTempStorage(Parse *pParse, const char *zStorageType){
91850   int ts = getTempStore(zStorageType);
91851   sqlcipher3 *db = pParse->db;
91852   if( db->temp_store==ts ) return SQLCIPHER_OK;
91853   if( invalidateTempStorage( pParse ) != SQLCIPHER_OK ){
91854     return SQLCIPHER_ERROR;
91855   }
91856   db->temp_store = (u8)ts;
91857   return SQLCIPHER_OK;
91858 }
91859 #endif /* SQLCIPHER_PAGER_PRAGMAS */
91860
91861 /*
91862 ** Generate code to return a single integer value.
91863 */
91864 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
91865   Vdbe *v = sqlcipher3GetVdbe(pParse);
91866   int mem = ++pParse->nMem;
91867   i64 *pI64 = sqlcipher3DbMallocRaw(pParse->db, sizeof(value));
91868   if( pI64 ){
91869     memcpy(pI64, &value, sizeof(value));
91870   }
91871   sqlcipher3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
91872   sqlcipher3VdbeSetNumCols(v, 1);
91873   sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLCIPHER_STATIC);
91874   sqlcipher3VdbeAddOp2(v, OP_ResultRow, mem, 1);
91875 }
91876
91877 #ifndef SQLCIPHER_OMIT_FLAG_PRAGMAS
91878 /*
91879 ** Check to see if zRight and zLeft refer to a pragma that queries
91880 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
91881 ** Also, implement the pragma.
91882 */
91883 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
91884   static const struct sPragmaType {
91885     const char *zName;  /* Name of the pragma */
91886     int mask;           /* Mask for the db->flags value */
91887   } aPragma[] = {
91888     { "full_column_names",        SQLCIPHER_FullColNames  },
91889     { "short_column_names",       SQLCIPHER_ShortColNames },
91890     { "count_changes",            SQLCIPHER_CountRows     },
91891     { "empty_result_callbacks",   SQLCIPHER_NullCallback  },
91892     { "legacy_file_format",       SQLCIPHER_LegacyFileFmt },
91893     { "fullfsync",                SQLCIPHER_FullFSync     },
91894     { "checkpoint_fullfsync",     SQLCIPHER_CkptFullFSync },
91895     { "reverse_unordered_selects", SQLCIPHER_ReverseOrder  },
91896 #ifndef SQLCIPHER_OMIT_AUTOMATIC_INDEX
91897     { "automatic_index",          SQLCIPHER_AutoIndex     },
91898 #endif
91899 #ifdef SQLCIPHER_DEBUG
91900     { "sql_trace",                SQLCIPHER_SqlTrace      },
91901     { "vdbe_listing",             SQLCIPHER_VdbeListing   },
91902     { "vdbe_trace",               SQLCIPHER_VdbeTrace     },
91903 #endif
91904 #ifndef SQLCIPHER_OMIT_CHECK
91905     { "ignore_check_constraints", SQLCIPHER_IgnoreChecks  },
91906 #endif
91907     /* The following is VERY experimental */
91908     { "writable_schema",          SQLCIPHER_WriteSchema|SQLCIPHER_RecoveryMode },
91909     { "omit_readlock",            SQLCIPHER_NoReadlock    },
91910
91911     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
91912     ** flag if there are any active statements. */
91913     { "read_uncommitted",         SQLCIPHER_ReadUncommitted },
91914     { "recursive_triggers",       SQLCIPHER_RecTriggers },
91915
91916     /* This flag may only be set if both foreign-key and trigger support
91917     ** are present in the build.  */
91918 #if !defined(SQLCIPHER_OMIT_FOREIGN_KEY) && !defined(SQLCIPHER_OMIT_TRIGGER)
91919     { "foreign_keys",             SQLCIPHER_ForeignKeys },
91920 #endif
91921   };
91922   int i;
91923   const struct sPragmaType *p;
91924   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
91925     if( sqlcipher3StrICmp(zLeft, p->zName)==0 ){
91926       sqlcipher3 *db = pParse->db;
91927       Vdbe *v;
91928       v = sqlcipher3GetVdbe(pParse);
91929       assert( v!=0 );  /* Already allocated by sqlcipher3Pragma() */
91930       if( ALWAYS(v) ){
91931         if( zRight==0 ){
91932           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
91933         }else{
91934           int mask = p->mask;          /* Mask of bits to set or clear. */
91935           if( db->autoCommit==0 ){
91936             /* Foreign key support may not be enabled or disabled while not
91937             ** in auto-commit mode.  */
91938             mask &= ~(SQLCIPHER_ForeignKeys);
91939           }
91940
91941           if( sqlcipher3GetBoolean(zRight) ){
91942             db->flags |= mask;
91943           }else{
91944             db->flags &= ~mask;
91945           }
91946
91947           /* Many of the flag-pragmas modify the code generated by the SQL 
91948           ** compiler (eg. count_changes). So add an opcode to expire all
91949           ** compiled SQL statements after modifying a pragma value.
91950           */
91951           sqlcipher3VdbeAddOp2(v, OP_Expire, 0, 0);
91952         }
91953       }
91954
91955       return 1;
91956     }
91957   }
91958   return 0;
91959 }
91960 #endif /* SQLCIPHER_OMIT_FLAG_PRAGMAS */
91961
91962 /*
91963 ** Return a human-readable name for a constraint resolution action.
91964 */
91965 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
91966 static const char *actionName(u8 action){
91967   const char *zName;
91968   switch( action ){
91969     case OE_SetNull:  zName = "SET NULL";        break;
91970     case OE_SetDflt:  zName = "SET DEFAULT";     break;
91971     case OE_Cascade:  zName = "CASCADE";         break;
91972     case OE_Restrict: zName = "RESTRICT";        break;
91973     default:          zName = "NO ACTION";  
91974                       assert( action==OE_None ); break;
91975   }
91976   return zName;
91977 }
91978 #endif
91979
91980
91981 /*
91982 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
91983 ** defined in pager.h. This function returns the associated lowercase
91984 ** journal-mode name.
91985 */
91986 SQLCIPHER_PRIVATE const char *sqlcipher3JournalModename(int eMode){
91987   static char * const azModeName[] = {
91988     "delete", "persist", "off", "truncate", "memory"
91989 #ifndef SQLCIPHER_OMIT_WAL
91990      , "wal"
91991 #endif
91992   };
91993   assert( PAGER_JOURNALMODE_DELETE==0 );
91994   assert( PAGER_JOURNALMODE_PERSIST==1 );
91995   assert( PAGER_JOURNALMODE_OFF==2 );
91996   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
91997   assert( PAGER_JOURNALMODE_MEMORY==4 );
91998   assert( PAGER_JOURNALMODE_WAL==5 );
91999   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
92000
92001   if( eMode==ArraySize(azModeName) ) return 0;
92002   return azModeName[eMode];
92003 }
92004
92005 /*
92006 ** Process a pragma statement.  
92007 **
92008 ** Pragmas are of this form:
92009 **
92010 **      PRAGMA [database.]id [= value]
92011 **
92012 ** The identifier might also be a string.  The value is a string, and
92013 ** identifier, or a number.  If minusFlag is true, then the value is
92014 ** a number that was preceded by a minus sign.
92015 **
92016 ** If the left side is "database.id" then pId1 is the database name
92017 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
92018 ** id and pId2 is any empty string.
92019 */
92020 SQLCIPHER_PRIVATE void sqlcipher3Pragma(
92021   Parse *pParse, 
92022   Token *pId1,        /* First part of [database.]id field */
92023   Token *pId2,        /* Second part of [database.]id field, or NULL */
92024   Token *pValue,      /* Token for <value>, or NULL */
92025   int minusFlag       /* True if a '-' sign preceded <value> */
92026 ){
92027   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
92028   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
92029   const char *zDb = 0;   /* The database name */
92030   Token *pId;            /* Pointer to <id> token */
92031   int iDb;               /* Database index for <database> */
92032   sqlcipher3 *db = pParse->db;
92033   Db *pDb;
92034   Vdbe *v = pParse->pVdbe = sqlcipher3VdbeCreate(db);
92035   if( v==0 ) return;
92036   sqlcipher3VdbeRunOnlyOnce(v);
92037   pParse->nMem = 2;
92038
92039   /* Interpret the [database.] part of the pragma statement. iDb is the
92040   ** index of the database this pragma is being applied to in db.aDb[]. */
92041   iDb = sqlcipher3TwoPartName(pParse, pId1, pId2, &pId);
92042   if( iDb<0 ) return;
92043   pDb = &db->aDb[iDb];
92044
92045   /* If the temp database has been explicitly named as part of the 
92046   ** pragma, make sure it is open. 
92047   */
92048   if( iDb==1 && sqlcipher3OpenTempDatabase(pParse) ){
92049     return;
92050   }
92051
92052   zLeft = sqlcipher3NameFromToken(db, pId);
92053   if( !zLeft ) return;
92054   if( minusFlag ){
92055     zRight = sqlcipher3MPrintf(db, "-%T", pValue);
92056   }else{
92057     zRight = sqlcipher3NameFromToken(db, pValue);
92058   }
92059
92060   assert( pId2 );
92061   zDb = pId2->n>0 ? pDb->zName : 0;
92062   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_PRAGMA, zLeft, zRight, zDb) ){
92063     goto pragma_out;
92064   }
92065  
92066 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
92067   /*
92068   **  PRAGMA [database.]default_cache_size
92069   **  PRAGMA [database.]default_cache_size=N
92070   **
92071   ** The first form reports the current persistent setting for the
92072   ** page cache size.  The value returned is the maximum number of
92073   ** pages in the page cache.  The second form sets both the current
92074   ** page cache size value and the persistent page cache size value
92075   ** stored in the database file.
92076   **
92077   ** Older versions of SQLite would set the default cache size to a
92078   ** negative number to indicate synchronous=OFF.  These days, synchronous
92079   ** is always on by default regardless of the sign of the default cache
92080   ** size.  But continue to take the absolute value of the default cache
92081   ** size of historical compatibility.
92082   */
92083   if( sqlcipher3StrICmp(zLeft,"default_cache_size")==0 ){
92084     static const VdbeOpList getCacheSize[] = {
92085       { OP_Transaction, 0, 0,        0},                         /* 0 */
92086       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
92087       { OP_IfPos,       1, 7,        0},
92088       { OP_Integer,     0, 2,        0},
92089       { OP_Subtract,    1, 2,        1},
92090       { OP_IfPos,       1, 7,        0},
92091       { OP_Integer,     0, 1,        0},                         /* 6 */
92092       { OP_ResultRow,   1, 1,        0},
92093     };
92094     int addr;
92095     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92096     sqlcipher3VdbeUsesBtree(v, iDb);
92097     if( !zRight ){
92098       sqlcipher3VdbeSetNumCols(v, 1);
92099       sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLCIPHER_STATIC);
92100       pParse->nMem += 2;
92101       addr = sqlcipher3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
92102       sqlcipher3VdbeChangeP1(v, addr, iDb);
92103       sqlcipher3VdbeChangeP1(v, addr+1, iDb);
92104       sqlcipher3VdbeChangeP1(v, addr+6, SQLCIPHER_DEFAULT_CACHE_SIZE);
92105     }else{
92106       int size = sqlcipher3AbsInt32(sqlcipher3Atoi(zRight));
92107       sqlcipher3BeginWriteOperation(pParse, 0, iDb);
92108       sqlcipher3VdbeAddOp2(v, OP_Integer, size, 1);
92109       sqlcipher3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
92110       assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
92111       pDb->pSchema->cache_size = size;
92112       sqlcipher3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92113     }
92114   }else
92115
92116   /*
92117   **  PRAGMA [database.]page_size
92118   **  PRAGMA [database.]page_size=N
92119   **
92120   ** The first form reports the current setting for the
92121   ** database page size in bytes.  The second form sets the
92122   ** database page size value.  The value can only be set if
92123   ** the database has not yet been created.
92124   */
92125   if( sqlcipher3StrICmp(zLeft,"page_size")==0 ){
92126     Btree *pBt = pDb->pBt;
92127     assert( pBt!=0 );
92128     if( !zRight ){
92129       int size = ALWAYS(pBt) ? sqlcipher3BtreeGetPageSize(pBt) : 0;
92130       returnSingleInt(pParse, "page_size", size);
92131     }else{
92132       /* Malloc may fail when setting the page-size, as there is an internal
92133       ** buffer that the pager module resizes using sqlcipher3_realloc().
92134       */
92135       db->nextPagesize = sqlcipher3Atoi(zRight);
92136       if( SQLCIPHER_NOMEM==sqlcipher3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
92137         db->mallocFailed = 1;
92138       }
92139     }
92140   }else
92141
92142   /*
92143   **  PRAGMA [database.]secure_delete
92144   **  PRAGMA [database.]secure_delete=ON/OFF
92145   **
92146   ** The first form reports the current setting for the
92147   ** secure_delete flag.  The second form changes the secure_delete
92148   ** flag setting and reports thenew value.
92149   */
92150   if( sqlcipher3StrICmp(zLeft,"secure_delete")==0 ){
92151     Btree *pBt = pDb->pBt;
92152     int b = -1;
92153     assert( pBt!=0 );
92154     if( zRight ){
92155       b = sqlcipher3GetBoolean(zRight);
92156     }
92157     if( pId2->n==0 && b>=0 ){
92158       int ii;
92159       for(ii=0; ii<db->nDb; ii++){
92160         sqlcipher3BtreeSecureDelete(db->aDb[ii].pBt, b);
92161       }
92162     }
92163     b = sqlcipher3BtreeSecureDelete(pBt, b);
92164     returnSingleInt(pParse, "secure_delete", b);
92165   }else
92166
92167   /*
92168   **  PRAGMA [database.]max_page_count
92169   **  PRAGMA [database.]max_page_count=N
92170   **
92171   ** The first form reports the current setting for the
92172   ** maximum number of pages in the database file.  The 
92173   ** second form attempts to change this setting.  Both
92174   ** forms return the current setting.
92175   **
92176   **  PRAGMA [database.]page_count
92177   **
92178   ** Return the number of pages in the specified database.
92179   */
92180   if( sqlcipher3StrICmp(zLeft,"page_count")==0
92181    || sqlcipher3StrICmp(zLeft,"max_page_count")==0
92182   ){
92183     int iReg;
92184     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92185     sqlcipher3CodeVerifySchema(pParse, iDb);
92186     iReg = ++pParse->nMem;
92187     if( sqlcipher3Tolower(zLeft[0])=='p' ){
92188       sqlcipher3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
92189     }else{
92190       sqlcipher3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlcipher3Atoi(zRight));
92191     }
92192     sqlcipher3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
92193     sqlcipher3VdbeSetNumCols(v, 1);
92194     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLCIPHER_TRANSIENT);
92195   }else
92196
92197   /*
92198   **  PRAGMA [database.]locking_mode
92199   **  PRAGMA [database.]locking_mode = (normal|exclusive)
92200   */
92201   if( sqlcipher3StrICmp(zLeft,"locking_mode")==0 ){
92202     const char *zRet = "normal";
92203     int eMode = getLockingMode(zRight);
92204
92205     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
92206       /* Simple "PRAGMA locking_mode;" statement. This is a query for
92207       ** the current default locking mode (which may be different to
92208       ** the locking-mode of the main database).
92209       */
92210       eMode = db->dfltLockMode;
92211     }else{
92212       Pager *pPager;
92213       if( pId2->n==0 ){
92214         /* This indicates that no database name was specified as part
92215         ** of the PRAGMA command. In this case the locking-mode must be
92216         ** set on all attached databases, as well as the main db file.
92217         **
92218         ** Also, the sqlcipher3.dfltLockMode variable is set so that
92219         ** any subsequently attached databases also use the specified
92220         ** locking mode.
92221         */
92222         int ii;
92223         assert(pDb==&db->aDb[0]);
92224         for(ii=2; ii<db->nDb; ii++){
92225           pPager = sqlcipher3BtreePager(db->aDb[ii].pBt);
92226           sqlcipher3PagerLockingMode(pPager, eMode);
92227         }
92228         db->dfltLockMode = (u8)eMode;
92229       }
92230       pPager = sqlcipher3BtreePager(pDb->pBt);
92231       eMode = sqlcipher3PagerLockingMode(pPager, eMode);
92232     }
92233
92234     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
92235     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
92236       zRet = "exclusive";
92237     }
92238     sqlcipher3VdbeSetNumCols(v, 1);
92239     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLCIPHER_STATIC);
92240     sqlcipher3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
92241     sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92242   }else
92243
92244   /*
92245   **  PRAGMA [database.]journal_mode
92246   **  PRAGMA [database.]journal_mode =
92247   **                      (delete|persist|off|truncate|memory|wal|off)
92248   */
92249   if( sqlcipher3StrICmp(zLeft,"journal_mode")==0 ){
92250     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
92251     int ii;           /* Loop counter */
92252
92253     /* Force the schema to be loaded on all databases.  This causes all
92254     ** database files to be opened and the journal_modes set.  This is
92255     ** necessary because subsequent processing must know if the databases
92256     ** are in WAL mode. */
92257     if( sqlcipher3ReadSchema(pParse) ){
92258       goto pragma_out;
92259     }
92260
92261     sqlcipher3VdbeSetNumCols(v, 1);
92262     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLCIPHER_STATIC);
92263
92264     if( zRight==0 ){
92265       /* If there is no "=MODE" part of the pragma, do a query for the
92266       ** current mode */
92267       eMode = PAGER_JOURNALMODE_QUERY;
92268     }else{
92269       const char *zMode;
92270       int n = sqlcipher3Strlen30(zRight);
92271       for(eMode=0; (zMode = sqlcipher3JournalModename(eMode))!=0; eMode++){
92272         if( sqlcipher3StrNICmp(zRight, zMode, n)==0 ) break;
92273       }
92274       if( !zMode ){
92275         /* If the "=MODE" part does not match any known journal mode,
92276         ** then do a query */
92277         eMode = PAGER_JOURNALMODE_QUERY;
92278       }
92279     }
92280     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
92281       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
92282       iDb = 0;
92283       pId2->n = 1;
92284     }
92285     for(ii=db->nDb-1; ii>=0; ii--){
92286       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
92287         sqlcipher3VdbeUsesBtree(v, ii);
92288         sqlcipher3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
92289       }
92290     }
92291     sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92292   }else
92293
92294   /*
92295   **  PRAGMA [database.]journal_size_limit
92296   **  PRAGMA [database.]journal_size_limit=N
92297   **
92298   ** Get or set the size limit on rollback journal files.
92299   */
92300   if( sqlcipher3StrICmp(zLeft,"journal_size_limit")==0 ){
92301     Pager *pPager = sqlcipher3BtreePager(pDb->pBt);
92302     i64 iLimit = -2;
92303     if( zRight ){
92304       sqlcipher3Atoi64(zRight, &iLimit, 1000000, SQLCIPHER_UTF8);
92305       if( iLimit<-1 ) iLimit = -1;
92306     }
92307     iLimit = sqlcipher3PagerJournalSizeLimit(pPager, iLimit);
92308     returnSingleInt(pParse, "journal_size_limit", iLimit);
92309   }else
92310
92311 #endif /* SQLCIPHER_OMIT_PAGER_PRAGMAS */
92312
92313   /*
92314   **  PRAGMA [database.]auto_vacuum
92315   **  PRAGMA [database.]auto_vacuum=N
92316   **
92317   ** Get or set the value of the database 'auto-vacuum' parameter.
92318   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
92319   */
92320 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
92321   if( sqlcipher3StrICmp(zLeft,"auto_vacuum")==0 ){
92322     Btree *pBt = pDb->pBt;
92323     assert( pBt!=0 );
92324     if( sqlcipher3ReadSchema(pParse) ){
92325       goto pragma_out;
92326     }
92327     if( !zRight ){
92328       int auto_vacuum;
92329       if( ALWAYS(pBt) ){
92330          auto_vacuum = sqlcipher3BtreeGetAutoVacuum(pBt);
92331       }else{
92332          auto_vacuum = SQLCIPHER_DEFAULT_AUTOVACUUM;
92333       }
92334       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
92335     }else{
92336       int eAuto = getAutoVacuum(zRight);
92337       assert( eAuto>=0 && eAuto<=2 );
92338       db->nextAutovac = (u8)eAuto;
92339       if( ALWAYS(eAuto>=0) ){
92340         /* Call SetAutoVacuum() to set initialize the internal auto and
92341         ** incr-vacuum flags. This is required in case this connection
92342         ** creates the database file. It is important that it is created
92343         ** as an auto-vacuum capable db.
92344         */
92345         int rc = sqlcipher3BtreeSetAutoVacuum(pBt, eAuto);
92346         if( rc==SQLCIPHER_OK && (eAuto==1 || eAuto==2) ){
92347           /* When setting the auto_vacuum mode to either "full" or 
92348           ** "incremental", write the value of meta[6] in the database
92349           ** file. Before writing to meta[6], check that meta[3] indicates
92350           ** that this really is an auto-vacuum capable database.
92351           */
92352           static const VdbeOpList setMeta6[] = {
92353             { OP_Transaction,    0,         1,                 0},    /* 0 */
92354             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
92355             { OP_If,             1,         0,                 0},    /* 2 */
92356             { OP_Halt,           SQLCIPHER_OK, OE_Abort,          0},    /* 3 */
92357             { OP_Integer,        0,         1,                 0},    /* 4 */
92358             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
92359           };
92360           int iAddr;
92361           iAddr = sqlcipher3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
92362           sqlcipher3VdbeChangeP1(v, iAddr, iDb);
92363           sqlcipher3VdbeChangeP1(v, iAddr+1, iDb);
92364           sqlcipher3VdbeChangeP2(v, iAddr+2, iAddr+4);
92365           sqlcipher3VdbeChangeP1(v, iAddr+4, eAuto-1);
92366           sqlcipher3VdbeChangeP1(v, iAddr+5, iDb);
92367           sqlcipher3VdbeUsesBtree(v, iDb);
92368         }
92369       }
92370     }
92371   }else
92372 #endif
92373
92374   /*
92375   **  PRAGMA [database.]incremental_vacuum(N)
92376   **
92377   ** Do N steps of incremental vacuuming on a database.
92378   */
92379 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
92380   if( sqlcipher3StrICmp(zLeft,"incremental_vacuum")==0 ){
92381     int iLimit, addr;
92382     if( sqlcipher3ReadSchema(pParse) ){
92383       goto pragma_out;
92384     }
92385     if( zRight==0 || !sqlcipher3GetInt32(zRight, &iLimit) || iLimit<=0 ){
92386       iLimit = 0x7fffffff;
92387     }
92388     sqlcipher3BeginWriteOperation(pParse, 0, iDb);
92389     sqlcipher3VdbeAddOp2(v, OP_Integer, iLimit, 1);
92390     addr = sqlcipher3VdbeAddOp1(v, OP_IncrVacuum, iDb);
92391     sqlcipher3VdbeAddOp1(v, OP_ResultRow, 1);
92392     sqlcipher3VdbeAddOp2(v, OP_AddImm, 1, -1);
92393     sqlcipher3VdbeAddOp2(v, OP_IfPos, 1, addr);
92394     sqlcipher3VdbeJumpHere(v, addr);
92395   }else
92396 #endif
92397
92398 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
92399   /*
92400   **  PRAGMA [database.]cache_size
92401   **  PRAGMA [database.]cache_size=N
92402   **
92403   ** The first form reports the current local setting for the
92404   ** page cache size.  The local setting can be different from
92405   ** the persistent cache size value that is stored in the database
92406   ** file itself.  The value returned is the maximum number of
92407   ** pages in the page cache.  The second form sets the local
92408   ** page cache size value.  It does not change the persistent
92409   ** cache size stored on the disk so the cache size will revert
92410   ** to its default value when the database is closed and reopened.
92411   ** N should be a positive integer.
92412   */
92413   if( sqlcipher3StrICmp(zLeft,"cache_size")==0 ){
92414     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92415     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
92416     if( !zRight ){
92417       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
92418     }else{
92419       int size = sqlcipher3AbsInt32(sqlcipher3Atoi(zRight));
92420       pDb->pSchema->cache_size = size;
92421       sqlcipher3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92422     }
92423   }else
92424
92425   /*
92426   **   PRAGMA temp_store
92427   **   PRAGMA temp_store = "default"|"memory"|"file"
92428   **
92429   ** Return or set the local value of the temp_store flag.  Changing
92430   ** the local value does not make changes to the disk file and the default
92431   ** value will be restored the next time the database is opened.
92432   **
92433   ** Note that it is possible for the library compile-time options to
92434   ** override this setting
92435   */
92436   if( sqlcipher3StrICmp(zLeft, "temp_store")==0 ){
92437     if( !zRight ){
92438       returnSingleInt(pParse, "temp_store", db->temp_store);
92439     }else{
92440       changeTempStorage(pParse, zRight);
92441     }
92442   }else
92443
92444   /*
92445   **   PRAGMA temp_store_directory
92446   **   PRAGMA temp_store_directory = ""|"directory_name"
92447   **
92448   ** Return or set the local value of the temp_store_directory flag.  Changing
92449   ** the value sets a specific directory to be used for temporary files.
92450   ** Setting to a null string reverts to the default temporary directory search.
92451   ** If temporary directory is changed, then invalidateTempStorage.
92452   **
92453   */
92454   if( sqlcipher3StrICmp(zLeft, "temp_store_directory")==0 ){
92455     if( !zRight ){
92456       if( sqlcipher3_temp_directory ){
92457         sqlcipher3VdbeSetNumCols(v, 1);
92458         sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, 
92459             "temp_store_directory", SQLCIPHER_STATIC);
92460         sqlcipher3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlcipher3_temp_directory, 0);
92461         sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92462       }
92463     }else{
92464 #ifndef SQLCIPHER_OMIT_WSD
92465       if( zRight[0] ){
92466         int rc;
92467         int res;
92468         rc = sqlcipher3OsAccess(db->pVfs, zRight, SQLCIPHER_ACCESS_READWRITE, &res);
92469         if( rc!=SQLCIPHER_OK || res==0 ){
92470           sqlcipher3ErrorMsg(pParse, "not a writable directory");
92471           goto pragma_out;
92472         }
92473       }
92474       if( SQLCIPHER_TEMP_STORE==0
92475        || (SQLCIPHER_TEMP_STORE==1 && db->temp_store<=1)
92476        || (SQLCIPHER_TEMP_STORE==2 && db->temp_store==1)
92477       ){
92478         invalidateTempStorage(pParse);
92479       }
92480       sqlcipher3_free(sqlcipher3_temp_directory);
92481       if( zRight[0] ){
92482         sqlcipher3_temp_directory = sqlcipher3_mprintf("%s", zRight);
92483       }else{
92484         sqlcipher3_temp_directory = 0;
92485       }
92486 #endif /* SQLCIPHER_OMIT_WSD */
92487     }
92488   }else
92489
92490 #if !defined(SQLCIPHER_ENABLE_LOCKING_STYLE)
92491 #  if defined(__APPLE__)
92492 #    define SQLCIPHER_ENABLE_LOCKING_STYLE 1
92493 #  else
92494 #    define SQLCIPHER_ENABLE_LOCKING_STYLE 0
92495 #  endif
92496 #endif
92497 #if SQLCIPHER_ENABLE_LOCKING_STYLE
92498   /*
92499    **   PRAGMA [database.]lock_proxy_file
92500    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
92501    **
92502    ** Return or set the value of the lock_proxy_file flag.  Changing
92503    ** the value sets a specific file to be used for database access locks.
92504    **
92505    */
92506   if( sqlcipher3StrICmp(zLeft, "lock_proxy_file")==0 ){
92507     if( !zRight ){
92508       Pager *pPager = sqlcipher3BtreePager(pDb->pBt);
92509       char *proxy_file_path = NULL;
92510       sqlcipher3_file *pFile = sqlcipher3PagerFile(pPager);
92511       sqlcipher3OsFileControl(pFile, SQLCIPHER_GET_LOCKPROXYFILE, 
92512                            &proxy_file_path);
92513       
92514       if( proxy_file_path ){
92515         sqlcipher3VdbeSetNumCols(v, 1);
92516         sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, 
92517                               "lock_proxy_file", SQLCIPHER_STATIC);
92518         sqlcipher3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
92519         sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92520       }
92521     }else{
92522       Pager *pPager = sqlcipher3BtreePager(pDb->pBt);
92523       sqlcipher3_file *pFile = sqlcipher3PagerFile(pPager);
92524       int res;
92525       if( zRight[0] ){
92526         res=sqlcipher3OsFileControl(pFile, SQLCIPHER_SET_LOCKPROXYFILE, 
92527                                      zRight);
92528       } else {
92529         res=sqlcipher3OsFileControl(pFile, SQLCIPHER_SET_LOCKPROXYFILE, 
92530                                      NULL);
92531       }
92532       if( res!=SQLCIPHER_OK ){
92533         sqlcipher3ErrorMsg(pParse, "failed to set lock proxy file");
92534         goto pragma_out;
92535       }
92536     }
92537   }else
92538 #endif /* SQLCIPHER_ENABLE_LOCKING_STYLE */      
92539     
92540   /*
92541   **   PRAGMA [database.]synchronous
92542   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
92543   **
92544   ** Return or set the local value of the synchronous flag.  Changing
92545   ** the local value does not make changes to the disk file and the
92546   ** default value will be restored the next time the database is
92547   ** opened.
92548   */
92549   if( sqlcipher3StrICmp(zLeft,"synchronous")==0 ){
92550     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92551     if( !zRight ){
92552       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
92553     }else{
92554       if( !db->autoCommit ){
92555         sqlcipher3ErrorMsg(pParse, 
92556             "Safety level may not be changed inside a transaction");
92557       }else{
92558         pDb->safety_level = getSafetyLevel(zRight)+1;
92559       }
92560     }
92561   }else
92562 #endif /* SQLCIPHER_OMIT_PAGER_PRAGMAS */
92563
92564 #ifndef SQLCIPHER_OMIT_FLAG_PRAGMAS
92565   if( flagPragma(pParse, zLeft, zRight) ){
92566     /* The flagPragma() subroutine also generates any necessary code
92567     ** there is nothing more to do here */
92568   }else
92569 #endif /* SQLCIPHER_OMIT_FLAG_PRAGMAS */
92570
92571 #ifndef SQLCIPHER_OMIT_SCHEMA_PRAGMAS
92572   /*
92573   **   PRAGMA table_info(<table>)
92574   **
92575   ** Return a single row for each column of the named table. The columns of
92576   ** the returned data set are:
92577   **
92578   ** cid:        Column id (numbered from left to right, starting at 0)
92579   ** name:       Column name
92580   ** type:       Column declaration type.
92581   ** notnull:    True if 'NOT NULL' is part of column declaration
92582   ** dflt_value: The default value for the column, if any.
92583   */
92584   if( sqlcipher3StrICmp(zLeft, "table_info")==0 && zRight ){
92585     Table *pTab;
92586     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92587     pTab = sqlcipher3FindTable(db, zRight, zDb);
92588     if( pTab ){
92589       int i;
92590       int nHidden = 0;
92591       Column *pCol;
92592       sqlcipher3VdbeSetNumCols(v, 6);
92593       pParse->nMem = 6;
92594       sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLCIPHER_STATIC);
92595       sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLCIPHER_STATIC);
92596       sqlcipher3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLCIPHER_STATIC);
92597       sqlcipher3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLCIPHER_STATIC);
92598       sqlcipher3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLCIPHER_STATIC);
92599       sqlcipher3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLCIPHER_STATIC);
92600       sqlcipher3ViewGetColumnNames(pParse, pTab);
92601       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
92602         if( IsHiddenColumn(pCol) ){
92603           nHidden++;
92604           continue;
92605         }
92606         sqlcipher3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
92607         sqlcipher3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
92608         sqlcipher3VdbeAddOp4(v, OP_String8, 0, 3, 0,
92609            pCol->zType ? pCol->zType : "", 0);
92610         sqlcipher3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
92611         if( pCol->zDflt ){
92612           sqlcipher3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
92613         }else{
92614           sqlcipher3VdbeAddOp2(v, OP_Null, 0, 5);
92615         }
92616         sqlcipher3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
92617         sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 6);
92618       }
92619     }
92620   }else
92621
92622   if( sqlcipher3StrICmp(zLeft, "index_info")==0 && zRight ){
92623     Index *pIdx;
92624     Table *pTab;
92625     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92626     pIdx = sqlcipher3FindIndex(db, zRight, zDb);
92627     if( pIdx ){
92628       int i;
92629       pTab = pIdx->pTable;
92630       sqlcipher3VdbeSetNumCols(v, 3);
92631       pParse->nMem = 3;
92632       sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLCIPHER_STATIC);
92633       sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLCIPHER_STATIC);
92634       sqlcipher3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLCIPHER_STATIC);
92635       for(i=0; i<pIdx->nColumn; i++){
92636         int cnum = pIdx->aiColumn[i];
92637         sqlcipher3VdbeAddOp2(v, OP_Integer, i, 1);
92638         sqlcipher3VdbeAddOp2(v, OP_Integer, cnum, 2);
92639         assert( pTab->nCol>cnum );
92640         sqlcipher3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
92641         sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 3);
92642       }
92643     }
92644   }else
92645
92646   if( sqlcipher3StrICmp(zLeft, "index_list")==0 && zRight ){
92647     Index *pIdx;
92648     Table *pTab;
92649     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92650     pTab = sqlcipher3FindTable(db, zRight, zDb);
92651     if( pTab ){
92652       v = sqlcipher3GetVdbe(pParse);
92653       pIdx = pTab->pIndex;
92654       if( pIdx ){
92655         int i = 0; 
92656         sqlcipher3VdbeSetNumCols(v, 3);
92657         pParse->nMem = 3;
92658         sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLCIPHER_STATIC);
92659         sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLCIPHER_STATIC);
92660         sqlcipher3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLCIPHER_STATIC);
92661         while(pIdx){
92662           sqlcipher3VdbeAddOp2(v, OP_Integer, i, 1);
92663           sqlcipher3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
92664           sqlcipher3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
92665           sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 3);
92666           ++i;
92667           pIdx = pIdx->pNext;
92668         }
92669       }
92670     }
92671   }else
92672
92673   if( sqlcipher3StrICmp(zLeft, "database_list")==0 ){
92674     int i;
92675     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92676     sqlcipher3VdbeSetNumCols(v, 3);
92677     pParse->nMem = 3;
92678     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLCIPHER_STATIC);
92679     sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLCIPHER_STATIC);
92680     sqlcipher3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLCIPHER_STATIC);
92681     for(i=0; i<db->nDb; i++){
92682       if( db->aDb[i].pBt==0 ) continue;
92683       assert( db->aDb[i].zName!=0 );
92684       sqlcipher3VdbeAddOp2(v, OP_Integer, i, 1);
92685       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
92686       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 3, 0,
92687            sqlcipher3BtreeGetFilename(db->aDb[i].pBt), 0);
92688       sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 3);
92689     }
92690   }else
92691
92692   if( sqlcipher3StrICmp(zLeft, "collation_list")==0 ){
92693     int i = 0;
92694     HashElem *p;
92695     sqlcipher3VdbeSetNumCols(v, 2);
92696     pParse->nMem = 2;
92697     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLCIPHER_STATIC);
92698     sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLCIPHER_STATIC);
92699     for(p=sqlcipherHashFirst(&db->aCollSeq); p; p=sqlcipherHashNext(p)){
92700       CollSeq *pColl = (CollSeq *)sqlcipherHashData(p);
92701       sqlcipher3VdbeAddOp2(v, OP_Integer, i++, 1);
92702       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
92703       sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 2);
92704     }
92705   }else
92706 #endif /* SQLCIPHER_OMIT_SCHEMA_PRAGMAS */
92707
92708 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
92709   if( sqlcipher3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
92710     FKey *pFK;
92711     Table *pTab;
92712     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92713     pTab = sqlcipher3FindTable(db, zRight, zDb);
92714     if( pTab ){
92715       v = sqlcipher3GetVdbe(pParse);
92716       pFK = pTab->pFKey;
92717       if( pFK ){
92718         int i = 0; 
92719         sqlcipher3VdbeSetNumCols(v, 8);
92720         pParse->nMem = 8;
92721         sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLCIPHER_STATIC);
92722         sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLCIPHER_STATIC);
92723         sqlcipher3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLCIPHER_STATIC);
92724         sqlcipher3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLCIPHER_STATIC);
92725         sqlcipher3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLCIPHER_STATIC);
92726         sqlcipher3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLCIPHER_STATIC);
92727         sqlcipher3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLCIPHER_STATIC);
92728         sqlcipher3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLCIPHER_STATIC);
92729         while(pFK){
92730           int j;
92731           for(j=0; j<pFK->nCol; j++){
92732             char *zCol = pFK->aCol[j].zCol;
92733             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
92734             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
92735             sqlcipher3VdbeAddOp2(v, OP_Integer, i, 1);
92736             sqlcipher3VdbeAddOp2(v, OP_Integer, j, 2);
92737             sqlcipher3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
92738             sqlcipher3VdbeAddOp4(v, OP_String8, 0, 4, 0,
92739                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
92740             sqlcipher3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
92741             sqlcipher3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
92742             sqlcipher3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
92743             sqlcipher3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
92744             sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 8);
92745           }
92746           ++i;
92747           pFK = pFK->pNextFrom;
92748         }
92749       }
92750     }
92751   }else
92752 #endif /* !defined(SQLCIPHER_OMIT_FOREIGN_KEY) */
92753
92754 #ifndef NDEBUG
92755   if( sqlcipher3StrICmp(zLeft, "parser_trace")==0 ){
92756     if( zRight ){
92757       if( sqlcipher3GetBoolean(zRight) ){
92758         sqlcipher3ParserTrace(stderr, "parser: ");
92759       }else{
92760         sqlcipher3ParserTrace(0, 0);
92761       }
92762     }
92763   }else
92764 #endif
92765
92766   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
92767   ** used will be case sensitive or not depending on the RHS.
92768   */
92769   if( sqlcipher3StrICmp(zLeft, "case_sensitive_like")==0 ){
92770     if( zRight ){
92771       sqlcipher3RegisterLikeFunctions(db, sqlcipher3GetBoolean(zRight));
92772     }
92773   }else
92774
92775 #ifndef SQLCIPHER_INTEGRITY_CHECK_ERROR_MAX
92776 # define SQLCIPHER_INTEGRITY_CHECK_ERROR_MAX 100
92777 #endif
92778
92779 #ifndef SQLCIPHER_OMIT_INTEGRITY_CHECK
92780   /* Pragma "quick_check" is an experimental reduced version of 
92781   ** integrity_check designed to detect most database corruption
92782   ** without most of the overhead of a full integrity-check.
92783   */
92784   if( sqlcipher3StrICmp(zLeft, "integrity_check")==0
92785    || sqlcipher3StrICmp(zLeft, "quick_check")==0 
92786   ){
92787     int i, j, addr, mxErr;
92788
92789     /* Code that appears at the end of the integrity check.  If no error
92790     ** messages have been generated, output OK.  Otherwise output the
92791     ** error message
92792     */
92793     static const VdbeOpList endCode[] = {
92794       { OP_AddImm,      1, 0,        0},    /* 0 */
92795       { OP_IfNeg,       1, 0,        0},    /* 1 */
92796       { OP_String8,     0, 3,        0},    /* 2 */
92797       { OP_ResultRow,   3, 1,        0},
92798     };
92799
92800     int isQuick = (sqlcipher3Tolower(zLeft[0])=='q');
92801
92802     /* Initialize the VDBE program */
92803     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92804     pParse->nMem = 6;
92805     sqlcipher3VdbeSetNumCols(v, 1);
92806     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLCIPHER_STATIC);
92807
92808     /* Set the maximum error count */
92809     mxErr = SQLCIPHER_INTEGRITY_CHECK_ERROR_MAX;
92810     if( zRight ){
92811       sqlcipher3GetInt32(zRight, &mxErr);
92812       if( mxErr<=0 ){
92813         mxErr = SQLCIPHER_INTEGRITY_CHECK_ERROR_MAX;
92814       }
92815     }
92816     sqlcipher3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
92817
92818     /* Do an integrity check on each database file */
92819     for(i=0; i<db->nDb; i++){
92820       HashElem *x;
92821       Hash *pTbls;
92822       int cnt = 0;
92823
92824       if( OMIT_TEMPDB && i==1 ) continue;
92825
92826       sqlcipher3CodeVerifySchema(pParse, i);
92827       addr = sqlcipher3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
92828       sqlcipher3VdbeAddOp2(v, OP_Halt, 0, 0);
92829       sqlcipher3VdbeJumpHere(v, addr);
92830
92831       /* Do an integrity check of the B-Tree
92832       **
92833       ** Begin by filling registers 2, 3, ... with the root pages numbers
92834       ** for all tables and indices in the database.
92835       */
92836       assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
92837       pTbls = &db->aDb[i].pSchema->tblHash;
92838       for(x=sqlcipherHashFirst(pTbls); x; x=sqlcipherHashNext(x)){
92839         Table *pTab = sqlcipherHashData(x);
92840         Index *pIdx;
92841         sqlcipher3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
92842         cnt++;
92843         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
92844           sqlcipher3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
92845           cnt++;
92846         }
92847       }
92848
92849       /* Make sure sufficient number of registers have been allocated */
92850       if( pParse->nMem < cnt+4 ){
92851         pParse->nMem = cnt+4;
92852       }
92853
92854       /* Do the b-tree integrity checks */
92855       sqlcipher3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
92856       sqlcipher3VdbeChangeP5(v, (u8)i);
92857       addr = sqlcipher3VdbeAddOp1(v, OP_IsNull, 2);
92858       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 3, 0,
92859          sqlcipher3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
92860          P4_DYNAMIC);
92861       sqlcipher3VdbeAddOp3(v, OP_Move, 2, 4, 1);
92862       sqlcipher3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
92863       sqlcipher3VdbeAddOp2(v, OP_ResultRow, 2, 1);
92864       sqlcipher3VdbeJumpHere(v, addr);
92865
92866       /* Make sure all the indices are constructed correctly.
92867       */
92868       for(x=sqlcipherHashFirst(pTbls); x && !isQuick; x=sqlcipherHashNext(x)){
92869         Table *pTab = sqlcipherHashData(x);
92870         Index *pIdx;
92871         int loopTop;
92872
92873         if( pTab->pIndex==0 ) continue;
92874         addr = sqlcipher3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
92875         sqlcipher3VdbeAddOp2(v, OP_Halt, 0, 0);
92876         sqlcipher3VdbeJumpHere(v, addr);
92877         sqlcipher3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
92878         sqlcipher3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
92879         loopTop = sqlcipher3VdbeAddOp2(v, OP_Rewind, 1, 0);
92880         sqlcipher3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
92881         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
92882           int jmp2;
92883           int r1;
92884           static const VdbeOpList idxErr[] = {
92885             { OP_AddImm,      1, -1,  0},
92886             { OP_String8,     0,  3,  0},    /* 1 */
92887             { OP_Rowid,       1,  4,  0},
92888             { OP_String8,     0,  5,  0},    /* 3 */
92889             { OP_String8,     0,  6,  0},    /* 4 */
92890             { OP_Concat,      4,  3,  3},
92891             { OP_Concat,      5,  3,  3},
92892             { OP_Concat,      6,  3,  3},
92893             { OP_ResultRow,   3,  1,  0},
92894             { OP_IfPos,       1,  0,  0},    /* 9 */
92895             { OP_Halt,        0,  0,  0},
92896           };
92897           r1 = sqlcipher3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
92898           jmp2 = sqlcipher3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
92899           addr = sqlcipher3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
92900           sqlcipher3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
92901           sqlcipher3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
92902           sqlcipher3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
92903           sqlcipher3VdbeJumpHere(v, addr+9);
92904           sqlcipher3VdbeJumpHere(v, jmp2);
92905         }
92906         sqlcipher3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
92907         sqlcipher3VdbeJumpHere(v, loopTop);
92908         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
92909           static const VdbeOpList cntIdx[] = {
92910              { OP_Integer,      0,  3,  0},
92911              { OP_Rewind,       0,  0,  0},  /* 1 */
92912              { OP_AddImm,       3,  1,  0},
92913              { OP_Next,         0,  0,  0},  /* 3 */
92914              { OP_Eq,           2,  0,  3},  /* 4 */
92915              { OP_AddImm,       1, -1,  0},
92916              { OP_String8,      0,  2,  0},  /* 6 */
92917              { OP_String8,      0,  3,  0},  /* 7 */
92918              { OP_Concat,       3,  2,  2},
92919              { OP_ResultRow,    2,  1,  0},
92920           };
92921           addr = sqlcipher3VdbeAddOp1(v, OP_IfPos, 1);
92922           sqlcipher3VdbeAddOp2(v, OP_Halt, 0, 0);
92923           sqlcipher3VdbeJumpHere(v, addr);
92924           addr = sqlcipher3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
92925           sqlcipher3VdbeChangeP1(v, addr+1, j+2);
92926           sqlcipher3VdbeChangeP2(v, addr+1, addr+4);
92927           sqlcipher3VdbeChangeP1(v, addr+3, j+2);
92928           sqlcipher3VdbeChangeP2(v, addr+3, addr+2);
92929           sqlcipher3VdbeJumpHere(v, addr+4);
92930           sqlcipher3VdbeChangeP4(v, addr+6, 
92931                      "wrong # of entries in index ", P4_STATIC);
92932           sqlcipher3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
92933         }
92934       } 
92935     }
92936     addr = sqlcipher3VdbeAddOpList(v, ArraySize(endCode), endCode);
92937     sqlcipher3VdbeChangeP2(v, addr, -mxErr);
92938     sqlcipher3VdbeJumpHere(v, addr+1);
92939     sqlcipher3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
92940   }else
92941 #endif /* SQLCIPHER_OMIT_INTEGRITY_CHECK */
92942
92943 #ifndef SQLCIPHER_OMIT_UTF16
92944   /*
92945   **   PRAGMA encoding
92946   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
92947   **
92948   ** In its first form, this pragma returns the encoding of the main
92949   ** database. If the database is not initialized, it is initialized now.
92950   **
92951   ** The second form of this pragma is a no-op if the main database file
92952   ** has not already been initialized. In this case it sets the default
92953   ** encoding that will be used for the main database file if a new file
92954   ** is created. If an existing main database file is opened, then the
92955   ** default text encoding for the existing database is used.
92956   ** 
92957   ** In all cases new databases created using the ATTACH command are
92958   ** created to use the same default text encoding as the main database. If
92959   ** the main database has not been initialized and/or created when ATTACH
92960   ** is executed, this is done before the ATTACH operation.
92961   **
92962   ** In the second form this pragma sets the text encoding to be used in
92963   ** new database files created using this database handle. It is only
92964   ** useful if invoked immediately after the main database i
92965   */
92966   if( sqlcipher3StrICmp(zLeft, "encoding")==0 ){
92967     static const struct EncName {
92968       char *zName;
92969       u8 enc;
92970     } encnames[] = {
92971       { "UTF8",     SQLCIPHER_UTF8        },
92972       { "UTF-8",    SQLCIPHER_UTF8        },  /* Must be element [1] */
92973       { "UTF-16le", SQLCIPHER_UTF16LE     },  /* Must be element [2] */
92974       { "UTF-16be", SQLCIPHER_UTF16BE     },  /* Must be element [3] */
92975       { "UTF16le",  SQLCIPHER_UTF16LE     },
92976       { "UTF16be",  SQLCIPHER_UTF16BE     },
92977       { "UTF-16",   0                  }, /* SQLCIPHER_UTF16NATIVE */
92978       { "UTF16",    0                  }, /* SQLCIPHER_UTF16NATIVE */
92979       { 0, 0 }
92980     };
92981     const struct EncName *pEnc;
92982     if( !zRight ){    /* "PRAGMA encoding" */
92983       if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92984       sqlcipher3VdbeSetNumCols(v, 1);
92985       sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLCIPHER_STATIC);
92986       sqlcipher3VdbeAddOp2(v, OP_String8, 0, 1);
92987       assert( encnames[SQLCIPHER_UTF8].enc==SQLCIPHER_UTF8 );
92988       assert( encnames[SQLCIPHER_UTF16LE].enc==SQLCIPHER_UTF16LE );
92989       assert( encnames[SQLCIPHER_UTF16BE].enc==SQLCIPHER_UTF16BE );
92990       sqlcipher3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
92991       sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92992     }else{                        /* "PRAGMA encoding = XXX" */
92993       /* Only change the value of sqlcipher.enc if the database handle is not
92994       ** initialized. If the main database exists, the new sqlcipher.enc value
92995       ** will be overwritten when the schema is next loaded. If it does not
92996       ** already exists, it will be created to use the new encoding value.
92997       */
92998       if( 
92999         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
93000         DbHasProperty(db, 0, DB_Empty) 
93001       ){
93002         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
93003           if( 0==sqlcipher3StrICmp(zRight, pEnc->zName) ){
93004             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLCIPHER_UTF16NATIVE;
93005             break;
93006           }
93007         }
93008         if( !pEnc->zName ){
93009           sqlcipher3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
93010         }
93011       }
93012     }
93013   }else
93014 #endif /* SQLCIPHER_OMIT_UTF16 */
93015
93016 #ifndef SQLCIPHER_OMIT_SCHEMA_VERSION_PRAGMAS
93017   /*
93018   **   PRAGMA [database.]schema_version
93019   **   PRAGMA [database.]schema_version = <integer>
93020   **
93021   **   PRAGMA [database.]user_version
93022   **   PRAGMA [database.]user_version = <integer>
93023   **
93024   ** The pragma's schema_version and user_version are used to set or get
93025   ** the value of the schema-version and user-version, respectively. Both
93026   ** the schema-version and the user-version are 32-bit signed integers
93027   ** stored in the database header.
93028   **
93029   ** The schema-cookie is usually only manipulated internally by SQLite. It
93030   ** is incremented by SQLite whenever the database schema is modified (by
93031   ** creating or dropping a table or index). The schema version is used by
93032   ** SQLite each time a query is executed to ensure that the internal cache
93033   ** of the schema used when compiling the SQL query matches the schema of
93034   ** the database against which the compiled query is actually executed.
93035   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
93036   ** the schema-version is potentially dangerous and may lead to program
93037   ** crashes or database corruption. Use with caution!
93038   **
93039   ** The user-version is not used internally by SQLite. It may be used by
93040   ** applications for any purpose.
93041   */
93042   if( sqlcipher3StrICmp(zLeft, "schema_version")==0 
93043    || sqlcipher3StrICmp(zLeft, "user_version")==0 
93044    || sqlcipher3StrICmp(zLeft, "freelist_count")==0 
93045   ){
93046     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
93047     sqlcipher3VdbeUsesBtree(v, iDb);
93048     switch( zLeft[0] ){
93049       case 'f': case 'F':
93050         iCookie = BTREE_FREE_PAGE_COUNT;
93051         break;
93052       case 's': case 'S':
93053         iCookie = BTREE_SCHEMA_VERSION;
93054         break;
93055       default:
93056         iCookie = BTREE_USER_VERSION;
93057         break;
93058     }
93059
93060     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
93061       /* Write the specified cookie value */
93062       static const VdbeOpList setCookie[] = {
93063         { OP_Transaction,    0,  1,  0},    /* 0 */
93064         { OP_Integer,        0,  1,  0},    /* 1 */
93065         { OP_SetCookie,      0,  0,  1},    /* 2 */
93066       };
93067       int addr = sqlcipher3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
93068       sqlcipher3VdbeChangeP1(v, addr, iDb);
93069       sqlcipher3VdbeChangeP1(v, addr+1, sqlcipher3Atoi(zRight));
93070       sqlcipher3VdbeChangeP1(v, addr+2, iDb);
93071       sqlcipher3VdbeChangeP2(v, addr+2, iCookie);
93072     }else{
93073       /* Read the specified cookie value */
93074       static const VdbeOpList readCookie[] = {
93075         { OP_Transaction,     0,  0,  0},    /* 0 */
93076         { OP_ReadCookie,      0,  1,  0},    /* 1 */
93077         { OP_ResultRow,       1,  1,  0}
93078       };
93079       int addr = sqlcipher3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
93080       sqlcipher3VdbeChangeP1(v, addr, iDb);
93081       sqlcipher3VdbeChangeP1(v, addr+1, iDb);
93082       sqlcipher3VdbeChangeP3(v, addr+1, iCookie);
93083       sqlcipher3VdbeSetNumCols(v, 1);
93084       sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLCIPHER_TRANSIENT);
93085     }
93086   }else
93087 #endif /* SQLCIPHER_OMIT_SCHEMA_VERSION_PRAGMAS */
93088
93089 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
93090   /*
93091   **   PRAGMA compile_options
93092   **
93093   ** Return the names of all compile-time options used in this build,
93094   ** one option per row.
93095   */
93096   if( sqlcipher3StrICmp(zLeft, "compile_options")==0 ){
93097     int i = 0;
93098     const char *zOpt;
93099     sqlcipher3VdbeSetNumCols(v, 1);
93100     pParse->nMem = 1;
93101     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLCIPHER_STATIC);
93102     while( (zOpt = sqlcipher3_compileoption_get(i++))!=0 ){
93103       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
93104       sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93105     }
93106   }else
93107 #endif /* SQLCIPHER_OMIT_COMPILEOPTION_DIAGS */
93108
93109 #ifndef SQLCIPHER_OMIT_WAL
93110   /*
93111   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
93112   **
93113   ** Checkpoint the database.
93114   */
93115   if( sqlcipher3StrICmp(zLeft, "wal_checkpoint")==0 ){
93116     int iBt = (pId2->z?iDb:SQLCIPHER_MAX_ATTACHED);
93117     int eMode = SQLCIPHER_CHECKPOINT_PASSIVE;
93118     if( zRight ){
93119       if( sqlcipher3StrICmp(zRight, "full")==0 ){
93120         eMode = SQLCIPHER_CHECKPOINT_FULL;
93121       }else if( sqlcipher3StrICmp(zRight, "restart")==0 ){
93122         eMode = SQLCIPHER_CHECKPOINT_RESTART;
93123       }
93124     }
93125     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
93126     sqlcipher3VdbeSetNumCols(v, 3);
93127     pParse->nMem = 3;
93128     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLCIPHER_STATIC);
93129     sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLCIPHER_STATIC);
93130     sqlcipher3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLCIPHER_STATIC);
93131
93132     sqlcipher3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
93133     sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93134   }else
93135
93136   /*
93137   **   PRAGMA wal_autocheckpoint
93138   **   PRAGMA wal_autocheckpoint = N
93139   **
93140   ** Configure a database connection to automatically checkpoint a database
93141   ** after accumulating N frames in the log. Or query for the current value
93142   ** of N.
93143   */
93144   if( sqlcipher3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
93145     if( zRight ){
93146       sqlcipher3_wal_autocheckpoint(db, sqlcipher3Atoi(zRight));
93147     }
93148     returnSingleInt(pParse, "wal_autocheckpoint", 
93149        db->xWalCallback==sqlcipher3WalDefaultHook ? 
93150            SQLCIPHER_PTR_TO_INT(db->pWalArg) : 0);
93151   }else
93152 #endif
93153
93154 #if defined(SQLCIPHER_DEBUG) || defined(SQLCIPHER_TEST)
93155   /*
93156   ** Report the current state of file logs for all databases
93157   */
93158   if( sqlcipher3StrICmp(zLeft, "lock_status")==0 ){
93159     static const char *const azLockName[] = {
93160       "unlocked", "shared", "reserved", "pending", "exclusive"
93161     };
93162     int i;
93163     sqlcipher3VdbeSetNumCols(v, 2);
93164     pParse->nMem = 2;
93165     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLCIPHER_STATIC);
93166     sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLCIPHER_STATIC);
93167     for(i=0; i<db->nDb; i++){
93168       Btree *pBt;
93169       Pager *pPager;
93170       const char *zState = "unknown";
93171       int j;
93172       if( db->aDb[i].zName==0 ) continue;
93173       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
93174       pBt = db->aDb[i].pBt;
93175       if( pBt==0 || (pPager = sqlcipher3BtreePager(pBt))==0 ){
93176         zState = "closed";
93177       }else if( sqlcipher3_file_control(db, i ? db->aDb[i].zName : 0, 
93178                                      SQLCIPHER_FCNTL_LOCKSTATE, &j)==SQLCIPHER_OK ){
93179          zState = azLockName[j];
93180       }
93181       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
93182       sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 2);
93183     }
93184
93185   }else
93186 #endif
93187
93188 #ifdef SQLCIPHER_HAS_CODEC
93189   if( sqlcipher3StrICmp(zLeft, "key")==0 && zRight ){
93190     sqlcipher3_key(db, zRight, sqlcipher3Strlen30(zRight));
93191   }else
93192   if( sqlcipher3StrICmp(zLeft, "rekey")==0 && zRight ){
93193     sqlcipher3_rekey(db, zRight, sqlcipher3Strlen30(zRight));
93194   }else
93195   if( zRight && (sqlcipher3StrICmp(zLeft, "hexkey")==0 ||
93196                  sqlcipher3StrICmp(zLeft, "hexrekey")==0) ){
93197     int i, h1, h2;
93198     char zKey[40];
93199     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
93200       h1 += 9*(1&(h1>>6));
93201       h2 += 9*(1&(h2>>6));
93202       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
93203     }
93204     if( (zLeft[3] & 0xf)==0xb ){
93205       sqlcipher3_key(db, zKey, i/2);
93206     }else{
93207       sqlcipher3_rekey(db, zKey, i/2);
93208     }
93209   }else
93210 /** BEGIN CRYPTO **/
93211   if( sqlcipher3StrICmp(zLeft, "cipher")==0 && zRight ){
93212     extern int codec_set_cipher_name(sqlcipher3*, int, const char *, int);
93213     codec_set_cipher_name(db, iDb, zRight, 2); // change cipher for both
93214   }else
93215   if( sqlcipher3StrICmp(zLeft, "rekey_cipher")==0 && zRight ){
93216     extern int codec_set_cipher_name(sqlcipher3*, int, const char *, int); 
93217     codec_set_cipher_name(db, iDb, zRight, 1); // change write cipher only
93218   }else
93219   if( sqlcipher3StrICmp(zLeft, "kdf_iter")==0 && zRight ){
93220     extern int codec_set_kdf_iter(sqlcipher3*, int, int, int);
93221     codec_set_kdf_iter(db, iDb, atoi(zRight), 2); // change of RW PBKDF2 iteration
93222   }else
93223   if( sqlcipher3StrICmp(zLeft, "fast_kdf_iter")==0 && zRight ){
93224     extern int codec_set_fast_kdf_iter(sqlcipher3*, int, int, int);
93225     codec_set_fast_kdf_iter(db, iDb, atoi(zRight), 2); // change of RW PBKDF2 iteration
93226   }else
93227   if( sqlcipher3StrICmp(zLeft, "rekey_kdf_iter")==0 && zRight ){
93228     extern int codec_set_kdf_iter(sqlcipher3*, int, int, int); 
93229     codec_set_kdf_iter(db, iDb, atoi(zRight), 1); // change # if W iterations
93230   }else
93231   if( sqlcipher3StrICmp(zLeft,"cipher_page_size")==0 ){
93232     extern int codec_set_page_size(sqlcipher3*, int, int); 
93233     codec_set_page_size(db, iDb, atoi(zRight)); // change page size
93234   }else
93235   if( sqlcipher3StrICmp(zLeft,"cipher_use_hmac")==0 ){
93236     extern int codec_set_use_hmac(sqlcipher3*, int, int);
93237     if(sqlcipher3GetBoolean(zRight)) {
93238       codec_set_use_hmac(db, iDb, 1);
93239     } else {
93240       codec_set_use_hmac(db, iDb, 0);
93241     }
93242   }else
93243 /** END CRYPTO **/
93244 #endif
93245 #if defined(SQLCIPHER_HAS_CODEC) || defined(SQLCIPHER_ENABLE_CEROD)
93246   if( sqlcipher3StrICmp(zLeft, "activate_extensions")==0 ){
93247 #ifdef SQLCIPHER_HAS_CODEC
93248     if( sqlcipher3StrNICmp(zRight, "see-", 4)==0 ){
93249       sqlcipher3_activate_see(&zRight[4]);
93250     }
93251 #endif
93252 #ifdef SQLCIPHER_ENABLE_CEROD
93253     if( sqlcipher3StrNICmp(zRight, "cerod-", 6)==0 ){
93254       sqlcipher3_activate_cerod(&zRight[6]);
93255     }
93256 #endif
93257   }else
93258 #endif
93259
93260  
93261   {/* Empty ELSE clause */}
93262
93263   /*
93264   ** Reset the safety level, in case the fullfsync flag or synchronous
93265   ** setting changed.
93266   */
93267 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
93268   if( db->autoCommit ){
93269     sqlcipher3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
93270                (db->flags&SQLCIPHER_FullFSync)!=0,
93271                (db->flags&SQLCIPHER_CkptFullFSync)!=0);
93272   }
93273 #endif
93274 pragma_out:
93275   sqlcipher3DbFree(db, zLeft);
93276   sqlcipher3DbFree(db, zRight);
93277 }
93278
93279 #endif /* SQLCIPHER_OMIT_PRAGMA */
93280
93281 /************** End of pragma.c **********************************************/
93282 /************** Begin file prepare.c *****************************************/
93283 /*
93284 ** 2005 May 25
93285 **
93286 ** The author disclaims copyright to this source code.  In place of
93287 ** a legal notice, here is a blessing:
93288 **
93289 **    May you do good and not evil.
93290 **    May you find forgiveness for yourself and forgive others.
93291 **    May you share freely, never taking more than you give.
93292 **
93293 *************************************************************************
93294 ** This file contains the implementation of the sqlcipher3_prepare()
93295 ** interface, and routines that contribute to loading the database schema
93296 ** from disk.
93297 */
93298
93299 /*
93300 ** Fill the InitData structure with an error message that indicates
93301 ** that the database is corrupt.
93302 */
93303 static void corruptSchema(
93304   InitData *pData,     /* Initialization context */
93305   const char *zObj,    /* Object being parsed at the point of error */
93306   const char *zExtra   /* Error information */
93307 ){
93308   sqlcipher3 *db = pData->db;
93309   if( !db->mallocFailed && (db->flags & SQLCIPHER_RecoveryMode)==0 ){
93310     if( zObj==0 ) zObj = "?";
93311     sqlcipher3SetString(pData->pzErrMsg, db,
93312       "malformed database schema (%s)", zObj);
93313     if( zExtra ){
93314       *pData->pzErrMsg = sqlcipher3MAppendf(db, *pData->pzErrMsg, 
93315                                  "%s - %s", *pData->pzErrMsg, zExtra);
93316     }
93317   }
93318   pData->rc = db->mallocFailed ? SQLCIPHER_NOMEM : SQLCIPHER_CORRUPT_BKPT;
93319 }
93320
93321 /*
93322 ** This is the callback routine for the code that initializes the
93323 ** database.  See sqlcipher3Init() below for additional information.
93324 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
93325 **
93326 ** Each callback contains the following information:
93327 **
93328 **     argv[0] = name of thing being created
93329 **     argv[1] = root page number for table or index. 0 for trigger or view.
93330 **     argv[2] = SQL text for the CREATE statement.
93331 **
93332 */
93333 SQLCIPHER_PRIVATE int sqlcipher3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
93334   InitData *pData = (InitData*)pInit;
93335   sqlcipher3 *db = pData->db;
93336   int iDb = pData->iDb;
93337
93338   assert( argc==3 );
93339   UNUSED_PARAMETER2(NotUsed, argc);
93340   assert( sqlcipher3_mutex_held(db->mutex) );
93341   DbClearProperty(db, iDb, DB_Empty);
93342   if( db->mallocFailed ){
93343     corruptSchema(pData, argv[0], 0);
93344     return 1;
93345   }
93346
93347   assert( iDb>=0 && iDb<db->nDb );
93348   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
93349   if( argv[1]==0 ){
93350     corruptSchema(pData, argv[0], 0);
93351   }else if( argv[2] && argv[2][0] ){
93352     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
93353     ** But because db->init.busy is set to 1, no VDBE code is generated
93354     ** or executed.  All the parser does is build the internal data
93355     ** structures that describe the table, index, or view.
93356     */
93357     int rc;
93358     sqlcipher3_stmt *pStmt;
93359     TESTONLY(int rcp);            /* Return code from sqlcipher3_prepare() */
93360
93361     assert( db->init.busy );
93362     db->init.iDb = iDb;
93363     db->init.newTnum = sqlcipher3Atoi(argv[1]);
93364     db->init.orphanTrigger = 0;
93365     TESTONLY(rcp = ) sqlcipher3_prepare(db, argv[2], -1, &pStmt, 0);
93366     rc = db->errCode;
93367     assert( (rc&0xFF)==(rcp&0xFF) );
93368     db->init.iDb = 0;
93369     if( SQLCIPHER_OK!=rc ){
93370       if( db->init.orphanTrigger ){
93371         assert( iDb==1 );
93372       }else{
93373         pData->rc = rc;
93374         if( rc==SQLCIPHER_NOMEM ){
93375           db->mallocFailed = 1;
93376         }else if( rc!=SQLCIPHER_INTERRUPT && (rc&0xFF)!=SQLCIPHER_LOCKED ){
93377           corruptSchema(pData, argv[0], sqlcipher3_errmsg(db));
93378         }
93379       }
93380     }
93381     sqlcipher3_finalize(pStmt);
93382   }else if( argv[0]==0 ){
93383     corruptSchema(pData, 0, 0);
93384   }else{
93385     /* If the SQL column is blank it means this is an index that
93386     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
93387     ** constraint for a CREATE TABLE.  The index should have already
93388     ** been created when we processed the CREATE TABLE.  All we have
93389     ** to do here is record the root page number for that index.
93390     */
93391     Index *pIndex;
93392     pIndex = sqlcipher3FindIndex(db, argv[0], db->aDb[iDb].zName);
93393     if( pIndex==0 ){
93394       /* This can occur if there exists an index on a TEMP table which
93395       ** has the same name as another index on a permanent index.  Since
93396       ** the permanent table is hidden by the TEMP table, we can also
93397       ** safely ignore the index on the permanent table.
93398       */
93399       /* Do Nothing */;
93400     }else if( sqlcipher3GetInt32(argv[1], &pIndex->tnum)==0 ){
93401       corruptSchema(pData, argv[0], "invalid rootpage");
93402     }
93403   }
93404   return 0;
93405 }
93406
93407 /*
93408 ** Attempt to read the database schema and initialize internal
93409 ** data structures for a single database file.  The index of the
93410 ** database file is given by iDb.  iDb==0 is used for the main
93411 ** database.  iDb==1 should never be used.  iDb>=2 is used for
93412 ** auxiliary databases.  Return one of the SQLCIPHER_ error codes to
93413 ** indicate success or failure.
93414 */
93415 static int sqlcipher3InitOne(sqlcipher3 *db, int iDb, char **pzErrMsg){
93416   int rc;
93417   int i;
93418   int size;
93419   Table *pTab;
93420   Db *pDb;
93421   char const *azArg[4];
93422   int meta[5];
93423   InitData initData;
93424   char const *zMasterSchema;
93425   char const *zMasterName;
93426   int openedTransaction = 0;
93427
93428   /*
93429   ** The master database table has a structure like this
93430   */
93431   static const char master_schema[] = 
93432      "CREATE TABLE sqlcipher_master(\n"
93433      "  type text,\n"
93434      "  name text,\n"
93435      "  tbl_name text,\n"
93436      "  rootpage integer,\n"
93437      "  sql text\n"
93438      ")"
93439   ;
93440 #ifndef SQLCIPHER_OMIT_TEMPDB
93441   static const char temp_master_schema[] = 
93442      "CREATE TEMP TABLE sqlcipher_temp_master(\n"
93443      "  type text,\n"
93444      "  name text,\n"
93445      "  tbl_name text,\n"
93446      "  rootpage integer,\n"
93447      "  sql text\n"
93448      ")"
93449   ;
93450 #else
93451   #define temp_master_schema 0
93452 #endif
93453
93454   assert( iDb>=0 && iDb<db->nDb );
93455   assert( db->aDb[iDb].pSchema );
93456   assert( sqlcipher3_mutex_held(db->mutex) );
93457   assert( iDb==1 || sqlcipher3BtreeHoldsMutex(db->aDb[iDb].pBt) );
93458
93459   /* zMasterSchema and zInitScript are set to point at the master schema
93460   ** and initialisation script appropriate for the database being
93461   ** initialised. zMasterName is the name of the master table.
93462   */
93463   if( !OMIT_TEMPDB && iDb==1 ){
93464     zMasterSchema = temp_master_schema;
93465   }else{
93466     zMasterSchema = master_schema;
93467   }
93468   zMasterName = SCHEMA_TABLE(iDb);
93469
93470   /* Construct the schema tables.  */
93471   azArg[0] = zMasterName;
93472   azArg[1] = "1";
93473   azArg[2] = zMasterSchema;
93474   azArg[3] = 0;
93475   initData.db = db;
93476   initData.iDb = iDb;
93477   initData.rc = SQLCIPHER_OK;
93478   initData.pzErrMsg = pzErrMsg;
93479   sqlcipher3InitCallback(&initData, 3, (char **)azArg, 0);
93480   if( initData.rc ){
93481     rc = initData.rc;
93482     goto error_out;
93483   }
93484   pTab = sqlcipher3FindTable(db, zMasterName, db->aDb[iDb].zName);
93485   if( ALWAYS(pTab) ){
93486     pTab->tabFlags |= TF_Readonly;
93487   }
93488
93489   /* Create a cursor to hold the database open
93490   */
93491   pDb = &db->aDb[iDb];
93492   if( pDb->pBt==0 ){
93493     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
93494       DbSetProperty(db, 1, DB_SchemaLoaded);
93495     }
93496     return SQLCIPHER_OK;
93497   }
93498
93499   /* If there is not already a read-only (or read-write) transaction opened
93500   ** on the b-tree database, open one now. If a transaction is opened, it 
93501   ** will be closed before this function returns.  */
93502   sqlcipher3BtreeEnter(pDb->pBt);
93503   if( !sqlcipher3BtreeIsInReadTrans(pDb->pBt) ){
93504     rc = sqlcipher3BtreeBeginTrans(pDb->pBt, 0);
93505     if( rc!=SQLCIPHER_OK ){
93506       sqlcipher3SetString(pzErrMsg, db, "%s", sqlcipher3ErrStr(rc));
93507       goto initone_error_out;
93508     }
93509     openedTransaction = 1;
93510   }
93511
93512   /* Get the database meta information.
93513   **
93514   ** Meta values are as follows:
93515   **    meta[0]   Schema cookie.  Changes with each schema change.
93516   **    meta[1]   File format of schema layer.
93517   **    meta[2]   Size of the page cache.
93518   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
93519   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
93520   **    meta[5]   User version
93521   **    meta[6]   Incremental vacuum mode
93522   **    meta[7]   unused
93523   **    meta[8]   unused
93524   **    meta[9]   unused
93525   **
93526   ** Note: The #defined SQLCIPHER_UTF* symbols in sqlcipherInt.h correspond to
93527   ** the possible values of meta[4].
93528   */
93529   for(i=0; i<ArraySize(meta); i++){
93530     sqlcipher3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
93531   }
93532   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
93533
93534   /* If opening a non-empty database, check the text encoding. For the
93535   ** main database, set sqlcipher3.enc to the encoding of the main database.
93536   ** For an attached db, it is an error if the encoding is not the same
93537   ** as sqlcipher3.enc.
93538   */
93539   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
93540     if( iDb==0 ){
93541       u8 encoding;
93542       /* If opening the main database, set ENC(db). */
93543       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
93544       if( encoding==0 ) encoding = SQLCIPHER_UTF8;
93545       ENC(db) = encoding;
93546       db->pDfltColl = sqlcipher3FindCollSeq(db, SQLCIPHER_UTF8, "BINARY", 0);
93547     }else{
93548       /* If opening an attached database, the encoding much match ENC(db) */
93549       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
93550         sqlcipher3SetString(pzErrMsg, db, "attached databases must use the same"
93551             " text encoding as main database");
93552         rc = SQLCIPHER_ERROR;
93553         goto initone_error_out;
93554       }
93555     }
93556   }else{
93557     DbSetProperty(db, iDb, DB_Empty);
93558   }
93559   pDb->pSchema->enc = ENC(db);
93560
93561   if( pDb->pSchema->cache_size==0 ){
93562     size = sqlcipher3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
93563     if( size==0 ){ size = SQLCIPHER_DEFAULT_CACHE_SIZE; }
93564     pDb->pSchema->cache_size = size;
93565     sqlcipher3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
93566   }
93567
93568   /*
93569   ** file_format==1    Version 3.0.0.
93570   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
93571   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
93572   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
93573   */
93574   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
93575   if( pDb->pSchema->file_format==0 ){
93576     pDb->pSchema->file_format = 1;
93577   }
93578   if( pDb->pSchema->file_format>SQLCIPHER_MAX_FILE_FORMAT ){
93579     sqlcipher3SetString(pzErrMsg, db, "unsupported file format");
93580     rc = SQLCIPHER_ERROR;
93581     goto initone_error_out;
93582   }
93583
93584   /* Ticket #2804:  When we open a database in the newer file format,
93585   ** clear the legacy_file_format pragma flag so that a VACUUM will
93586   ** not downgrade the database and thus invalidate any descending
93587   ** indices that the user might have created.
93588   */
93589   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
93590     db->flags &= ~SQLCIPHER_LegacyFileFmt;
93591   }
93592
93593   /* Read the schema information out of the schema tables
93594   */
93595   assert( db->init.busy );
93596   {
93597     char *zSql;
93598     zSql = sqlcipher3MPrintf(db, 
93599         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
93600         db->aDb[iDb].zName, zMasterName);
93601 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
93602     {
93603       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
93604       xAuth = db->xAuth;
93605       db->xAuth = 0;
93606 #endif
93607       rc = sqlcipher3_exec(db, zSql, sqlcipher3InitCallback, &initData, 0);
93608 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
93609       db->xAuth = xAuth;
93610     }
93611 #endif
93612     if( rc==SQLCIPHER_OK ) rc = initData.rc;
93613     sqlcipher3DbFree(db, zSql);
93614 #ifndef SQLCIPHER_OMIT_ANALYZE
93615     if( rc==SQLCIPHER_OK ){
93616       sqlcipher3AnalysisLoad(db, iDb);
93617     }
93618 #endif
93619   }
93620   if( db->mallocFailed ){
93621     rc = SQLCIPHER_NOMEM;
93622     sqlcipher3ResetInternalSchema(db, -1);
93623   }
93624   if( rc==SQLCIPHER_OK || (db->flags&SQLCIPHER_RecoveryMode)){
93625     /* Black magic: If the SQLCIPHER_RecoveryMode flag is set, then consider
93626     ** the schema loaded, even if errors occurred. In this situation the 
93627     ** current sqlcipher3_prepare() operation will fail, but the following one
93628     ** will attempt to compile the supplied statement against whatever subset
93629     ** of the schema was loaded before the error occurred. The primary
93630     ** purpose of this is to allow access to the sqlcipher_master table
93631     ** even when its contents have been corrupted.
93632     */
93633     DbSetProperty(db, iDb, DB_SchemaLoaded);
93634     rc = SQLCIPHER_OK;
93635   }
93636
93637   /* Jump here for an error that occurs after successfully allocating
93638   ** curMain and calling sqlcipher3BtreeEnter(). For an error that occurs
93639   ** before that point, jump to error_out.
93640   */
93641 initone_error_out:
93642   if( openedTransaction ){
93643     sqlcipher3BtreeCommit(pDb->pBt);
93644   }
93645   sqlcipher3BtreeLeave(pDb->pBt);
93646
93647 error_out:
93648   if( rc==SQLCIPHER_NOMEM || rc==SQLCIPHER_IOERR_NOMEM ){
93649     db->mallocFailed = 1;
93650   }
93651   return rc;
93652 }
93653
93654 /*
93655 ** Initialize all database files - the main database file, the file
93656 ** used to store temporary tables, and any additional database files
93657 ** created using ATTACH statements.  Return a success code.  If an
93658 ** error occurs, write an error message into *pzErrMsg.
93659 **
93660 ** After a database is initialized, the DB_SchemaLoaded bit is set
93661 ** bit is set in the flags field of the Db structure. If the database
93662 ** file was of zero-length, then the DB_Empty flag is also set.
93663 */
93664 SQLCIPHER_PRIVATE int sqlcipher3Init(sqlcipher3 *db, char **pzErrMsg){
93665   int i, rc;
93666   int commit_internal = !(db->flags&SQLCIPHER_InternChanges);
93667   
93668   assert( sqlcipher3_mutex_held(db->mutex) );
93669   rc = SQLCIPHER_OK;
93670   db->init.busy = 1;
93671   for(i=0; rc==SQLCIPHER_OK && i<db->nDb; i++){
93672     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
93673     rc = sqlcipher3InitOne(db, i, pzErrMsg);
93674     if( rc ){
93675       sqlcipher3ResetInternalSchema(db, i);
93676     }
93677   }
93678
93679   /* Once all the other databases have been initialised, load the schema
93680   ** for the TEMP database. This is loaded last, as the TEMP database
93681   ** schema may contain references to objects in other databases.
93682   */
93683 #ifndef SQLCIPHER_OMIT_TEMPDB
93684   if( rc==SQLCIPHER_OK && ALWAYS(db->nDb>1)
93685                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
93686     rc = sqlcipher3InitOne(db, 1, pzErrMsg);
93687     if( rc ){
93688       sqlcipher3ResetInternalSchema(db, 1);
93689     }
93690   }
93691 #endif
93692
93693   db->init.busy = 0;
93694   if( rc==SQLCIPHER_OK && commit_internal ){
93695     sqlcipher3CommitInternalChanges(db);
93696   }
93697
93698   return rc; 
93699 }
93700
93701 /*
93702 ** This routine is a no-op if the database schema is already initialised.
93703 ** Otherwise, the schema is loaded. An error code is returned.
93704 */
93705 SQLCIPHER_PRIVATE int sqlcipher3ReadSchema(Parse *pParse){
93706   int rc = SQLCIPHER_OK;
93707   sqlcipher3 *db = pParse->db;
93708   assert( sqlcipher3_mutex_held(db->mutex) );
93709   if( !db->init.busy ){
93710     rc = sqlcipher3Init(db, &pParse->zErrMsg);
93711   }
93712   if( rc!=SQLCIPHER_OK ){
93713     pParse->rc = rc;
93714     pParse->nErr++;
93715   }
93716   return rc;
93717 }
93718
93719
93720 /*
93721 ** Check schema cookies in all databases.  If any cookie is out
93722 ** of date set pParse->rc to SQLCIPHER_SCHEMA.  If all schema cookies
93723 ** make no changes to pParse->rc.
93724 */
93725 static void schemaIsValid(Parse *pParse){
93726   sqlcipher3 *db = pParse->db;
93727   int iDb;
93728   int rc;
93729   int cookie;
93730
93731   assert( pParse->checkSchema );
93732   assert( sqlcipher3_mutex_held(db->mutex) );
93733   for(iDb=0; iDb<db->nDb; iDb++){
93734     int openedTransaction = 0;         /* True if a transaction is opened */
93735     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
93736     if( pBt==0 ) continue;
93737
93738     /* If there is not already a read-only (or read-write) transaction opened
93739     ** on the b-tree database, open one now. If a transaction is opened, it 
93740     ** will be closed immediately after reading the meta-value. */
93741     if( !sqlcipher3BtreeIsInReadTrans(pBt) ){
93742       rc = sqlcipher3BtreeBeginTrans(pBt, 0);
93743       if( rc==SQLCIPHER_NOMEM || rc==SQLCIPHER_IOERR_NOMEM ){
93744         db->mallocFailed = 1;
93745       }
93746       if( rc!=SQLCIPHER_OK ) return;
93747       openedTransaction = 1;
93748     }
93749
93750     /* Read the schema cookie from the database. If it does not match the 
93751     ** value stored as part of the in-memory schema representation,
93752     ** set Parse.rc to SQLCIPHER_SCHEMA. */
93753     sqlcipher3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
93754     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
93755     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
93756       sqlcipher3ResetInternalSchema(db, iDb);
93757       pParse->rc = SQLCIPHER_SCHEMA;
93758     }
93759
93760     /* Close the transaction, if one was opened. */
93761     if( openedTransaction ){
93762       sqlcipher3BtreeCommit(pBt);
93763     }
93764   }
93765 }
93766
93767 /*
93768 ** Convert a schema pointer into the iDb index that indicates
93769 ** which database file in db->aDb[] the schema refers to.
93770 **
93771 ** If the same database is attached more than once, the first
93772 ** attached database is returned.
93773 */
93774 SQLCIPHER_PRIVATE int sqlcipher3SchemaToIndex(sqlcipher3 *db, Schema *pSchema){
93775   int i = -1000000;
93776
93777   /* If pSchema is NULL, then return -1000000. This happens when code in 
93778   ** expr.c is trying to resolve a reference to a transient table (i.e. one
93779   ** created by a sub-select). In this case the return value of this 
93780   ** function should never be used.
93781   **
93782   ** We return -1000000 instead of the more usual -1 simply because using
93783   ** -1000000 as the incorrect index into db->aDb[] is much 
93784   ** more likely to cause a segfault than -1 (of course there are assert()
93785   ** statements too, but it never hurts to play the odds).
93786   */
93787   assert( sqlcipher3_mutex_held(db->mutex) );
93788   if( pSchema ){
93789     for(i=0; ALWAYS(i<db->nDb); i++){
93790       if( db->aDb[i].pSchema==pSchema ){
93791         break;
93792       }
93793     }
93794     assert( i>=0 && i<db->nDb );
93795   }
93796   return i;
93797 }
93798
93799 /*
93800 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
93801 */
93802 static int sqlcipher3Prepare(
93803   sqlcipher3 *db,              /* Database handle. */
93804   const char *zSql,         /* UTF-8 encoded SQL statement. */
93805   int nBytes,               /* Length of zSql in bytes. */
93806   int saveSqlFlag,          /* True to copy SQL text into the sqlcipher3_stmt */
93807   Vdbe *pReprepare,         /* VM being reprepared */
93808   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
93809   const char **pzTail       /* OUT: End of parsed string */
93810 ){
93811   Parse *pParse;            /* Parsing context */
93812   char *zErrMsg = 0;        /* Error message */
93813   int rc = SQLCIPHER_OK;       /* Result code */
93814   int i;                    /* Loop counter */
93815
93816   /* Allocate the parsing context */
93817   pParse = sqlcipher3StackAllocZero(db, sizeof(*pParse));
93818   if( pParse==0 ){
93819     rc = SQLCIPHER_NOMEM;
93820     goto end_prepare;
93821   }
93822   pParse->pReprepare = pReprepare;
93823   assert( ppStmt && *ppStmt==0 );
93824   assert( !db->mallocFailed );
93825   assert( sqlcipher3_mutex_held(db->mutex) );
93826
93827   /* Check to verify that it is possible to get a read lock on all
93828   ** database schemas.  The inability to get a read lock indicates that
93829   ** some other database connection is holding a write-lock, which in
93830   ** turn means that the other connection has made uncommitted changes
93831   ** to the schema.
93832   **
93833   ** Were we to proceed and prepare the statement against the uncommitted
93834   ** schema changes and if those schema changes are subsequently rolled
93835   ** back and different changes are made in their place, then when this
93836   ** prepared statement goes to run the schema cookie would fail to detect
93837   ** the schema change.  Disaster would follow.
93838   **
93839   ** This thread is currently holding mutexes on all Btrees (because
93840   ** of the sqlcipher3BtreeEnterAll() in sqlcipher3LockAndPrepare()) so it
93841   ** is not possible for another thread to start a new schema change
93842   ** while this routine is running.  Hence, we do not need to hold 
93843   ** locks on the schema, we just need to make sure nobody else is 
93844   ** holding them.
93845   **
93846   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
93847   ** but it does *not* override schema lock detection, so this all still
93848   ** works even if READ_UNCOMMITTED is set.
93849   */
93850   for(i=0; i<db->nDb; i++) {
93851     Btree *pBt = db->aDb[i].pBt;
93852     if( pBt ){
93853       assert( sqlcipher3BtreeHoldsMutex(pBt) );
93854       rc = sqlcipher3BtreeSchemaLocked(pBt);
93855       if( rc ){
93856         const char *zDb = db->aDb[i].zName;
93857         sqlcipher3Error(db, rc, "database schema is locked: %s", zDb);
93858         testcase( db->flags & SQLCIPHER_ReadUncommitted );
93859         goto end_prepare;
93860       }
93861     }
93862   }
93863
93864   sqlcipher3VtabUnlockList(db);
93865
93866   pParse->db = db;
93867   pParse->nQueryLoop = (double)1;
93868   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
93869     char *zSqlCopy;
93870     int mxLen = db->aLimit[SQLCIPHER_LIMIT_SQL_LENGTH];
93871     testcase( nBytes==mxLen );
93872     testcase( nBytes==mxLen+1 );
93873     if( nBytes>mxLen ){
93874       sqlcipher3Error(db, SQLCIPHER_TOOBIG, "statement too long");
93875       rc = sqlcipher3ApiExit(db, SQLCIPHER_TOOBIG);
93876       goto end_prepare;
93877     }
93878     zSqlCopy = sqlcipher3DbStrNDup(db, zSql, nBytes);
93879     if( zSqlCopy ){
93880       sqlcipher3RunParser(pParse, zSqlCopy, &zErrMsg);
93881       sqlcipher3DbFree(db, zSqlCopy);
93882       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
93883     }else{
93884       pParse->zTail = &zSql[nBytes];
93885     }
93886   }else{
93887     sqlcipher3RunParser(pParse, zSql, &zErrMsg);
93888   }
93889   assert( 1==(int)pParse->nQueryLoop );
93890
93891   if( db->mallocFailed ){
93892     pParse->rc = SQLCIPHER_NOMEM;
93893   }
93894   if( pParse->rc==SQLCIPHER_DONE ) pParse->rc = SQLCIPHER_OK;
93895   if( pParse->checkSchema ){
93896     schemaIsValid(pParse);
93897   }
93898   if( db->mallocFailed ){
93899     pParse->rc = SQLCIPHER_NOMEM;
93900   }
93901   if( pzTail ){
93902     *pzTail = pParse->zTail;
93903   }
93904   rc = pParse->rc;
93905
93906 #ifndef SQLCIPHER_OMIT_EXPLAIN
93907   if( rc==SQLCIPHER_OK && pParse->pVdbe && pParse->explain ){
93908     static const char * const azColName[] = {
93909        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
93910        "selectid", "order", "from", "detail"
93911     };
93912     int iFirst, mx;
93913     if( pParse->explain==2 ){
93914       sqlcipher3VdbeSetNumCols(pParse->pVdbe, 4);
93915       iFirst = 8;
93916       mx = 12;
93917     }else{
93918       sqlcipher3VdbeSetNumCols(pParse->pVdbe, 8);
93919       iFirst = 0;
93920       mx = 8;
93921     }
93922     for(i=iFirst; i<mx; i++){
93923       sqlcipher3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
93924                             azColName[i], SQLCIPHER_STATIC);
93925     }
93926   }
93927 #endif
93928
93929   assert( db->init.busy==0 || saveSqlFlag==0 );
93930   if( db->init.busy==0 ){
93931     Vdbe *pVdbe = pParse->pVdbe;
93932     sqlcipher3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
93933   }
93934   if( pParse->pVdbe && (rc!=SQLCIPHER_OK || db->mallocFailed) ){
93935     sqlcipher3VdbeFinalize(pParse->pVdbe);
93936     assert(!(*ppStmt));
93937   }else{
93938     *ppStmt = (sqlcipher3_stmt*)pParse->pVdbe;
93939   }
93940
93941   if( zErrMsg ){
93942     sqlcipher3Error(db, rc, "%s", zErrMsg);
93943     sqlcipher3DbFree(db, zErrMsg);
93944   }else{
93945     sqlcipher3Error(db, rc, 0);
93946   }
93947
93948   /* Delete any TriggerPrg structures allocated while parsing this statement. */
93949   while( pParse->pTriggerPrg ){
93950     TriggerPrg *pT = pParse->pTriggerPrg;
93951     pParse->pTriggerPrg = pT->pNext;
93952     sqlcipher3DbFree(db, pT);
93953   }
93954
93955 end_prepare:
93956
93957   sqlcipher3StackFree(db, pParse);
93958   rc = sqlcipher3ApiExit(db, rc);
93959   assert( (rc&db->errMask)==rc );
93960   return rc;
93961 }
93962 static int sqlcipher3LockAndPrepare(
93963   sqlcipher3 *db,              /* Database handle. */
93964   const char *zSql,         /* UTF-8 encoded SQL statement. */
93965   int nBytes,               /* Length of zSql in bytes. */
93966   int saveSqlFlag,          /* True to copy SQL text into the sqlcipher3_stmt */
93967   Vdbe *pOld,               /* VM being reprepared */
93968   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
93969   const char **pzTail       /* OUT: End of parsed string */
93970 ){
93971   int rc;
93972   assert( ppStmt!=0 );
93973   *ppStmt = 0;
93974   if( !sqlcipher3SafetyCheckOk(db) ){
93975     return SQLCIPHER_MISUSE_BKPT;
93976   }
93977   sqlcipher3_mutex_enter(db->mutex);
93978   sqlcipher3BtreeEnterAll(db);
93979   rc = sqlcipher3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
93980   if( rc==SQLCIPHER_SCHEMA ){
93981     sqlcipher3_finalize(*ppStmt);
93982     rc = sqlcipher3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
93983   }
93984   sqlcipher3BtreeLeaveAll(db);
93985   sqlcipher3_mutex_leave(db->mutex);
93986   return rc;
93987 }
93988
93989 /*
93990 ** Rerun the compilation of a statement after a schema change.
93991 **
93992 ** If the statement is successfully recompiled, return SQLCIPHER_OK. Otherwise,
93993 ** if the statement cannot be recompiled because another connection has
93994 ** locked the sqlcipher3_master table, return SQLCIPHER_LOCKED. If any other error
93995 ** occurs, return SQLCIPHER_SCHEMA.
93996 */
93997 SQLCIPHER_PRIVATE int sqlcipher3Reprepare(Vdbe *p){
93998   int rc;
93999   sqlcipher3_stmt *pNew;
94000   const char *zSql;
94001   sqlcipher3 *db;
94002
94003   assert( sqlcipher3_mutex_held(sqlcipher3VdbeDb(p)->mutex) );
94004   zSql = sqlcipher3_sql((sqlcipher3_stmt *)p);
94005   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
94006   db = sqlcipher3VdbeDb(p);
94007   assert( sqlcipher3_mutex_held(db->mutex) );
94008   rc = sqlcipher3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
94009   if( rc ){
94010     if( rc==SQLCIPHER_NOMEM ){
94011       db->mallocFailed = 1;
94012     }
94013     assert( pNew==0 );
94014     return rc;
94015   }else{
94016     assert( pNew!=0 );
94017   }
94018   sqlcipher3VdbeSwap((Vdbe*)pNew, p);
94019   sqlcipher3TransferBindings(pNew, (sqlcipher3_stmt*)p);
94020   sqlcipher3VdbeResetStepResult((Vdbe*)pNew);
94021   sqlcipher3VdbeFinalize((Vdbe*)pNew);
94022   return SQLCIPHER_OK;
94023 }
94024
94025
94026 /*
94027 ** Two versions of the official API.  Legacy and new use.  In the legacy
94028 ** version, the original SQL text is not saved in the prepared statement
94029 ** and so if a schema change occurs, SQLCIPHER_SCHEMA is returned by
94030 ** sqlcipher3_step().  In the new version, the original SQL text is retained
94031 ** and the statement is automatically recompiled if an schema change
94032 ** occurs.
94033 */
94034 SQLCIPHER_API int sqlcipher3_prepare(
94035   sqlcipher3 *db,              /* Database handle. */
94036   const char *zSql,         /* UTF-8 encoded SQL statement. */
94037   int nBytes,               /* Length of zSql in bytes. */
94038   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94039   const char **pzTail       /* OUT: End of parsed string */
94040 ){
94041   int rc;
94042   rc = sqlcipher3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
94043   assert( rc==SQLCIPHER_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94044   return rc;
94045 }
94046 SQLCIPHER_API int sqlcipher3_prepare_v2(
94047   sqlcipher3 *db,              /* Database handle. */
94048   const char *zSql,         /* UTF-8 encoded SQL statement. */
94049   int nBytes,               /* Length of zSql in bytes. */
94050   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94051   const char **pzTail       /* OUT: End of parsed string */
94052 ){
94053   int rc;
94054   rc = sqlcipher3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
94055   assert( rc==SQLCIPHER_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94056   return rc;
94057 }
94058
94059
94060 #ifndef SQLCIPHER_OMIT_UTF16
94061 /*
94062 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
94063 */
94064 static int sqlcipher3Prepare16(
94065   sqlcipher3 *db,              /* Database handle. */ 
94066   const void *zSql,         /* UTF-16 encoded SQL statement. */
94067   int nBytes,               /* Length of zSql in bytes. */
94068   int saveSqlFlag,          /* True to save SQL text into the sqlcipher3_stmt */
94069   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94070   const void **pzTail       /* OUT: End of parsed string */
94071 ){
94072   /* This function currently works by first transforming the UTF-16
94073   ** encoded string to UTF-8, then invoking sqlcipher3_prepare(). The
94074   ** tricky bit is figuring out the pointer to return in *pzTail.
94075   */
94076   char *zSql8;
94077   const char *zTail8 = 0;
94078   int rc = SQLCIPHER_OK;
94079
94080   assert( ppStmt );
94081   *ppStmt = 0;
94082   if( !sqlcipher3SafetyCheckOk(db) ){
94083     return SQLCIPHER_MISUSE_BKPT;
94084   }
94085   sqlcipher3_mutex_enter(db->mutex);
94086   zSql8 = sqlcipher3Utf16to8(db, zSql, nBytes, SQLCIPHER_UTF16NATIVE);
94087   if( zSql8 ){
94088     rc = sqlcipher3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
94089   }
94090
94091   if( zTail8 && pzTail ){
94092     /* If sqlcipher3_prepare returns a tail pointer, we calculate the
94093     ** equivalent pointer into the UTF-16 string by counting the unicode
94094     ** characters between zSql8 and zTail8, and then returning a pointer
94095     ** the same number of characters into the UTF-16 string.
94096     */
94097     int chars_parsed = sqlcipher3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
94098     *pzTail = (u8 *)zSql + sqlcipher3Utf16ByteLen(zSql, chars_parsed);
94099   }
94100   sqlcipher3DbFree(db, zSql8); 
94101   rc = sqlcipher3ApiExit(db, rc);
94102   sqlcipher3_mutex_leave(db->mutex);
94103   return rc;
94104 }
94105
94106 /*
94107 ** Two versions of the official API.  Legacy and new use.  In the legacy
94108 ** version, the original SQL text is not saved in the prepared statement
94109 ** and so if a schema change occurs, SQLCIPHER_SCHEMA is returned by
94110 ** sqlcipher3_step().  In the new version, the original SQL text is retained
94111 ** and the statement is automatically recompiled if an schema change
94112 ** occurs.
94113 */
94114 SQLCIPHER_API int sqlcipher3_prepare16(
94115   sqlcipher3 *db,              /* Database handle. */ 
94116   const void *zSql,         /* UTF-16 encoded SQL statement. */
94117   int nBytes,               /* Length of zSql in bytes. */
94118   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94119   const void **pzTail       /* OUT: End of parsed string */
94120 ){
94121   int rc;
94122   rc = sqlcipher3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
94123   assert( rc==SQLCIPHER_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94124   return rc;
94125 }
94126 SQLCIPHER_API int sqlcipher3_prepare16_v2(
94127   sqlcipher3 *db,              /* Database handle. */ 
94128   const void *zSql,         /* UTF-16 encoded SQL statement. */
94129   int nBytes,               /* Length of zSql in bytes. */
94130   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94131   const void **pzTail       /* OUT: End of parsed string */
94132 ){
94133   int rc;
94134   rc = sqlcipher3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
94135   assert( rc==SQLCIPHER_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94136   return rc;
94137 }
94138
94139 #endif /* SQLCIPHER_OMIT_UTF16 */
94140
94141 /************** End of prepare.c *********************************************/
94142 /************** Begin file select.c ******************************************/
94143 /*
94144 ** 2001 September 15
94145 **
94146 ** The author disclaims copyright to this source code.  In place of
94147 ** a legal notice, here is a blessing:
94148 **
94149 **    May you do good and not evil.
94150 **    May you find forgiveness for yourself and forgive others.
94151 **    May you share freely, never taking more than you give.
94152 **
94153 *************************************************************************
94154 ** This file contains C code routines that are called by the parser
94155 ** to handle SELECT statements in SQLite.
94156 */
94157
94158
94159 /*
94160 ** Delete all the content of a Select structure but do not deallocate
94161 ** the select structure itself.
94162 */
94163 static void clearSelect(sqlcipher3 *db, Select *p){
94164   sqlcipher3ExprListDelete(db, p->pEList);
94165   sqlcipher3SrcListDelete(db, p->pSrc);
94166   sqlcipher3ExprDelete(db, p->pWhere);
94167   sqlcipher3ExprListDelete(db, p->pGroupBy);
94168   sqlcipher3ExprDelete(db, p->pHaving);
94169   sqlcipher3ExprListDelete(db, p->pOrderBy);
94170   sqlcipher3SelectDelete(db, p->pPrior);
94171   sqlcipher3ExprDelete(db, p->pLimit);
94172   sqlcipher3ExprDelete(db, p->pOffset);
94173 }
94174
94175 /*
94176 ** Initialize a SelectDest structure.
94177 */
94178 SQLCIPHER_PRIVATE void sqlcipher3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
94179   pDest->eDest = (u8)eDest;
94180   pDest->iParm = iParm;
94181   pDest->affinity = 0;
94182   pDest->iMem = 0;
94183   pDest->nMem = 0;
94184 }
94185
94186
94187 /*
94188 ** Allocate a new Select structure and return a pointer to that
94189 ** structure.
94190 */
94191 SQLCIPHER_PRIVATE Select *sqlcipher3SelectNew(
94192   Parse *pParse,        /* Parsing context */
94193   ExprList *pEList,     /* which columns to include in the result */
94194   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
94195   Expr *pWhere,         /* the WHERE clause */
94196   ExprList *pGroupBy,   /* the GROUP BY clause */
94197   Expr *pHaving,        /* the HAVING clause */
94198   ExprList *pOrderBy,   /* the ORDER BY clause */
94199   int isDistinct,       /* true if the DISTINCT keyword is present */
94200   Expr *pLimit,         /* LIMIT value.  NULL means not used */
94201   Expr *pOffset         /* OFFSET value.  NULL means no offset */
94202 ){
94203   Select *pNew;
94204   Select standin;
94205   sqlcipher3 *db = pParse->db;
94206   pNew = sqlcipher3DbMallocZero(db, sizeof(*pNew) );
94207   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
94208   if( pNew==0 ){
94209     assert( db->mallocFailed );
94210     pNew = &standin;
94211     memset(pNew, 0, sizeof(*pNew));
94212   }
94213   if( pEList==0 ){
94214     pEList = sqlcipher3ExprListAppend(pParse, 0, sqlcipher3Expr(db,TK_ALL,0));
94215   }
94216   pNew->pEList = pEList;
94217   pNew->pSrc = pSrc;
94218   pNew->pWhere = pWhere;
94219   pNew->pGroupBy = pGroupBy;
94220   pNew->pHaving = pHaving;
94221   pNew->pOrderBy = pOrderBy;
94222   pNew->selFlags = isDistinct ? SF_Distinct : 0;
94223   pNew->op = TK_SELECT;
94224   pNew->pLimit = pLimit;
94225   pNew->pOffset = pOffset;
94226   assert( pOffset==0 || pLimit!=0 );
94227   pNew->addrOpenEphm[0] = -1;
94228   pNew->addrOpenEphm[1] = -1;
94229   pNew->addrOpenEphm[2] = -1;
94230   if( db->mallocFailed ) {
94231     clearSelect(db, pNew);
94232     if( pNew!=&standin ) sqlcipher3DbFree(db, pNew);
94233     pNew = 0;
94234   }else{
94235     assert( pNew->pSrc!=0 || pParse->nErr>0 );
94236   }
94237   assert( pNew!=&standin );
94238   return pNew;
94239 }
94240
94241 /*
94242 ** Delete the given Select structure and all of its substructures.
94243 */
94244 SQLCIPHER_PRIVATE void sqlcipher3SelectDelete(sqlcipher3 *db, Select *p){
94245   if( p ){
94246     clearSelect(db, p);
94247     sqlcipher3DbFree(db, p);
94248   }
94249 }
94250
94251 /*
94252 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
94253 ** type of join.  Return an integer constant that expresses that type
94254 ** in terms of the following bit values:
94255 **
94256 **     JT_INNER
94257 **     JT_CROSS
94258 **     JT_OUTER
94259 **     JT_NATURAL
94260 **     JT_LEFT
94261 **     JT_RIGHT
94262 **
94263 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
94264 **
94265 ** If an illegal or unsupported join type is seen, then still return
94266 ** a join type, but put an error in the pParse structure.
94267 */
94268 SQLCIPHER_PRIVATE int sqlcipher3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
94269   int jointype = 0;
94270   Token *apAll[3];
94271   Token *p;
94272                              /*   0123456789 123456789 123456789 123 */
94273   static const char zKeyText[] = "naturaleftouterightfullinnercross";
94274   static const struct {
94275     u8 i;        /* Beginning of keyword text in zKeyText[] */
94276     u8 nChar;    /* Length of the keyword in characters */
94277     u8 code;     /* Join type mask */
94278   } aKeyword[] = {
94279     /* natural */ { 0,  7, JT_NATURAL                },
94280     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
94281     /* outer   */ { 10, 5, JT_OUTER                  },
94282     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
94283     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
94284     /* inner   */ { 23, 5, JT_INNER                  },
94285     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
94286   };
94287   int i, j;
94288   apAll[0] = pA;
94289   apAll[1] = pB;
94290   apAll[2] = pC;
94291   for(i=0; i<3 && apAll[i]; i++){
94292     p = apAll[i];
94293     for(j=0; j<ArraySize(aKeyword); j++){
94294       if( p->n==aKeyword[j].nChar 
94295           && sqlcipher3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
94296         jointype |= aKeyword[j].code;
94297         break;
94298       }
94299     }
94300     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
94301     if( j>=ArraySize(aKeyword) ){
94302       jointype |= JT_ERROR;
94303       break;
94304     }
94305   }
94306   if(
94307      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
94308      (jointype & JT_ERROR)!=0
94309   ){
94310     const char *zSp = " ";
94311     assert( pB!=0 );
94312     if( pC==0 ){ zSp++; }
94313     sqlcipher3ErrorMsg(pParse, "unknown or unsupported join type: "
94314        "%T %T%s%T", pA, pB, zSp, pC);
94315     jointype = JT_INNER;
94316   }else if( (jointype & JT_OUTER)!=0 
94317          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
94318     sqlcipher3ErrorMsg(pParse, 
94319       "RIGHT and FULL OUTER JOINs are not currently supported");
94320     jointype = JT_INNER;
94321   }
94322   return jointype;
94323 }
94324
94325 /*
94326 ** Return the index of a column in a table.  Return -1 if the column
94327 ** is not contained in the table.
94328 */
94329 static int columnIndex(Table *pTab, const char *zCol){
94330   int i;
94331   for(i=0; i<pTab->nCol; i++){
94332     if( sqlcipher3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
94333   }
94334   return -1;
94335 }
94336
94337 /*
94338 ** Search the first N tables in pSrc, from left to right, looking for a
94339 ** table that has a column named zCol.  
94340 **
94341 ** When found, set *piTab and *piCol to the table index and column index
94342 ** of the matching column and return TRUE.
94343 **
94344 ** If not found, return FALSE.
94345 */
94346 static int tableAndColumnIndex(
94347   SrcList *pSrc,       /* Array of tables to search */
94348   int N,               /* Number of tables in pSrc->a[] to search */
94349   const char *zCol,    /* Name of the column we are looking for */
94350   int *piTab,          /* Write index of pSrc->a[] here */
94351   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
94352 ){
94353   int i;               /* For looping over tables in pSrc */
94354   int iCol;            /* Index of column matching zCol */
94355
94356   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
94357   for(i=0; i<N; i++){
94358     iCol = columnIndex(pSrc->a[i].pTab, zCol);
94359     if( iCol>=0 ){
94360       if( piTab ){
94361         *piTab = i;
94362         *piCol = iCol;
94363       }
94364       return 1;
94365     }
94366   }
94367   return 0;
94368 }
94369
94370 /*
94371 ** This function is used to add terms implied by JOIN syntax to the
94372 ** WHERE clause expression of a SELECT statement. The new term, which
94373 ** is ANDed with the existing WHERE clause, is of the form:
94374 **
94375 **    (tab1.col1 = tab2.col2)
94376 **
94377 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
94378 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
94379 ** column iColRight of tab2.
94380 */
94381 static void addWhereTerm(
94382   Parse *pParse,                  /* Parsing context */
94383   SrcList *pSrc,                  /* List of tables in FROM clause */
94384   int iLeft,                      /* Index of first table to join in pSrc */
94385   int iColLeft,                   /* Index of column in first table */
94386   int iRight,                     /* Index of second table in pSrc */
94387   int iColRight,                  /* Index of column in second table */
94388   int isOuterJoin,                /* True if this is an OUTER join */
94389   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
94390 ){
94391   sqlcipher3 *db = pParse->db;
94392   Expr *pE1;
94393   Expr *pE2;
94394   Expr *pEq;
94395
94396   assert( iLeft<iRight );
94397   assert( pSrc->nSrc>iRight );
94398   assert( pSrc->a[iLeft].pTab );
94399   assert( pSrc->a[iRight].pTab );
94400
94401   pE1 = sqlcipher3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
94402   pE2 = sqlcipher3CreateColumnExpr(db, pSrc, iRight, iColRight);
94403
94404   pEq = sqlcipher3PExpr(pParse, TK_EQ, pE1, pE2, 0);
94405   if( pEq && isOuterJoin ){
94406     ExprSetProperty(pEq, EP_FromJoin);
94407     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
94408     ExprSetIrreducible(pEq);
94409     pEq->iRightJoinTable = (i16)pE2->iTable;
94410   }
94411   *ppWhere = sqlcipher3ExprAnd(db, *ppWhere, pEq);
94412 }
94413
94414 /*
94415 ** Set the EP_FromJoin property on all terms of the given expression.
94416 ** And set the Expr.iRightJoinTable to iTable for every term in the
94417 ** expression.
94418 **
94419 ** The EP_FromJoin property is used on terms of an expression to tell
94420 ** the LEFT OUTER JOIN processing logic that this term is part of the
94421 ** join restriction specified in the ON or USING clause and not a part
94422 ** of the more general WHERE clause.  These terms are moved over to the
94423 ** WHERE clause during join processing but we need to remember that they
94424 ** originated in the ON or USING clause.
94425 **
94426 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
94427 ** expression depends on table iRightJoinTable even if that table is not
94428 ** explicitly mentioned in the expression.  That information is needed
94429 ** for cases like this:
94430 **
94431 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
94432 **
94433 ** The where clause needs to defer the handling of the t1.x=5
94434 ** term until after the t2 loop of the join.  In that way, a
94435 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
94436 ** defer the handling of t1.x=5, it will be processed immediately
94437 ** after the t1 loop and rows with t1.x!=5 will never appear in
94438 ** the output, which is incorrect.
94439 */
94440 static void setJoinExpr(Expr *p, int iTable){
94441   while( p ){
94442     ExprSetProperty(p, EP_FromJoin);
94443     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
94444     ExprSetIrreducible(p);
94445     p->iRightJoinTable = (i16)iTable;
94446     setJoinExpr(p->pLeft, iTable);
94447     p = p->pRight;
94448   } 
94449 }
94450
94451 /*
94452 ** This routine processes the join information for a SELECT statement.
94453 ** ON and USING clauses are converted into extra terms of the WHERE clause.
94454 ** NATURAL joins also create extra WHERE clause terms.
94455 **
94456 ** The terms of a FROM clause are contained in the Select.pSrc structure.
94457 ** The left most table is the first entry in Select.pSrc.  The right-most
94458 ** table is the last entry.  The join operator is held in the entry to
94459 ** the left.  Thus entry 0 contains the join operator for the join between
94460 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
94461 ** also attached to the left entry.
94462 **
94463 ** This routine returns the number of errors encountered.
94464 */
94465 static int sqlcipherProcessJoin(Parse *pParse, Select *p){
94466   SrcList *pSrc;                  /* All tables in the FROM clause */
94467   int i, j;                       /* Loop counters */
94468   struct SrcList_item *pLeft;     /* Left table being joined */
94469   struct SrcList_item *pRight;    /* Right table being joined */
94470
94471   pSrc = p->pSrc;
94472   pLeft = &pSrc->a[0];
94473   pRight = &pLeft[1];
94474   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
94475     Table *pLeftTab = pLeft->pTab;
94476     Table *pRightTab = pRight->pTab;
94477     int isOuter;
94478
94479     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
94480     isOuter = (pRight->jointype & JT_OUTER)!=0;
94481
94482     /* When the NATURAL keyword is present, add WHERE clause terms for
94483     ** every column that the two tables have in common.
94484     */
94485     if( pRight->jointype & JT_NATURAL ){
94486       if( pRight->pOn || pRight->pUsing ){
94487         sqlcipher3ErrorMsg(pParse, "a NATURAL join may not have "
94488            "an ON or USING clause", 0);
94489         return 1;
94490       }
94491       for(j=0; j<pRightTab->nCol; j++){
94492         char *zName;   /* Name of column in the right table */
94493         int iLeft;     /* Matching left table */
94494         int iLeftCol;  /* Matching column in the left table */
94495
94496         zName = pRightTab->aCol[j].zName;
94497         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
94498           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
94499                        isOuter, &p->pWhere);
94500         }
94501       }
94502     }
94503
94504     /* Disallow both ON and USING clauses in the same join
94505     */
94506     if( pRight->pOn && pRight->pUsing ){
94507       sqlcipher3ErrorMsg(pParse, "cannot have both ON and USING "
94508         "clauses in the same join");
94509       return 1;
94510     }
94511
94512     /* Add the ON clause to the end of the WHERE clause, connected by
94513     ** an AND operator.
94514     */
94515     if( pRight->pOn ){
94516       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
94517       p->pWhere = sqlcipher3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
94518       pRight->pOn = 0;
94519     }
94520
94521     /* Create extra terms on the WHERE clause for each column named
94522     ** in the USING clause.  Example: If the two tables to be joined are 
94523     ** A and B and the USING clause names X, Y, and Z, then add this
94524     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
94525     ** Report an error if any column mentioned in the USING clause is
94526     ** not contained in both tables to be joined.
94527     */
94528     if( pRight->pUsing ){
94529       IdList *pList = pRight->pUsing;
94530       for(j=0; j<pList->nId; j++){
94531         char *zName;     /* Name of the term in the USING clause */
94532         int iLeft;       /* Table on the left with matching column name */
94533         int iLeftCol;    /* Column number of matching column on the left */
94534         int iRightCol;   /* Column number of matching column on the right */
94535
94536         zName = pList->a[j].zName;
94537         iRightCol = columnIndex(pRightTab, zName);
94538         if( iRightCol<0
94539          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
94540         ){
94541           sqlcipher3ErrorMsg(pParse, "cannot join using column %s - column "
94542             "not present in both tables", zName);
94543           return 1;
94544         }
94545         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
94546                      isOuter, &p->pWhere);
94547       }
94548     }
94549   }
94550   return 0;
94551 }
94552
94553 /*
94554 ** Insert code into "v" that will push the record on the top of the
94555 ** stack into the sorter.
94556 */
94557 static void pushOntoSorter(
94558   Parse *pParse,         /* Parser context */
94559   ExprList *pOrderBy,    /* The ORDER BY clause */
94560   Select *pSelect,       /* The whole SELECT statement */
94561   int regData            /* Register holding data to be sorted */
94562 ){
94563   Vdbe *v = pParse->pVdbe;
94564   int nExpr = pOrderBy->nExpr;
94565   int regBase = sqlcipher3GetTempRange(pParse, nExpr+2);
94566   int regRecord = sqlcipher3GetTempReg(pParse);
94567   int op;
94568   sqlcipher3ExprCacheClear(pParse);
94569   sqlcipher3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
94570   sqlcipher3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
94571   sqlcipher3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
94572   sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
94573   if( pSelect->selFlags & SF_UseSorter ){
94574     op = OP_SorterInsert;
94575   }else{
94576     op = OP_IdxInsert;
94577   }
94578   sqlcipher3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
94579   sqlcipher3ReleaseTempReg(pParse, regRecord);
94580   sqlcipher3ReleaseTempRange(pParse, regBase, nExpr+2);
94581   if( pSelect->iLimit ){
94582     int addr1, addr2;
94583     int iLimit;
94584     if( pSelect->iOffset ){
94585       iLimit = pSelect->iOffset+1;
94586     }else{
94587       iLimit = pSelect->iLimit;
94588     }
94589     addr1 = sqlcipher3VdbeAddOp1(v, OP_IfZero, iLimit);
94590     sqlcipher3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
94591     addr2 = sqlcipher3VdbeAddOp0(v, OP_Goto);
94592     sqlcipher3VdbeJumpHere(v, addr1);
94593     sqlcipher3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
94594     sqlcipher3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
94595     sqlcipher3VdbeJumpHere(v, addr2);
94596   }
94597 }
94598
94599 /*
94600 ** Add code to implement the OFFSET
94601 */
94602 static void codeOffset(
94603   Vdbe *v,          /* Generate code into this VM */
94604   Select *p,        /* The SELECT statement being coded */
94605   int iContinue     /* Jump here to skip the current record */
94606 ){
94607   if( p->iOffset && iContinue!=0 ){
94608     int addr;
94609     sqlcipher3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
94610     addr = sqlcipher3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
94611     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, iContinue);
94612     VdbeComment((v, "skip OFFSET records"));
94613     sqlcipher3VdbeJumpHere(v, addr);
94614   }
94615 }
94616
94617 /*
94618 ** Add code that will check to make sure the N registers starting at iMem
94619 ** form a distinct entry.  iTab is a sorting index that holds previously
94620 ** seen combinations of the N values.  A new entry is made in iTab
94621 ** if the current N values are new.
94622 **
94623 ** A jump to addrRepeat is made and the N+1 values are popped from the
94624 ** stack if the top N elements are not distinct.
94625 */
94626 static void codeDistinct(
94627   Parse *pParse,     /* Parsing and code generating context */
94628   int iTab,          /* A sorting index used to test for distinctness */
94629   int addrRepeat,    /* Jump to here if not distinct */
94630   int N,             /* Number of elements */
94631   int iMem           /* First element */
94632 ){
94633   Vdbe *v;
94634   int r1;
94635
94636   v = pParse->pVdbe;
94637   r1 = sqlcipher3GetTempReg(pParse);
94638   sqlcipher3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
94639   sqlcipher3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
94640   sqlcipher3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
94641   sqlcipher3ReleaseTempReg(pParse, r1);
94642 }
94643
94644 #ifndef SQLCIPHER_OMIT_SUBQUERY
94645 /*
94646 ** Generate an error message when a SELECT is used within a subexpression
94647 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
94648 ** column.  We do this in a subroutine because the error used to occur
94649 ** in multiple places.  (The error only occurs in one place now, but we
94650 ** retain the subroutine to minimize code disruption.)
94651 */
94652 static int checkForMultiColumnSelectError(
94653   Parse *pParse,       /* Parse context. */
94654   SelectDest *pDest,   /* Destination of SELECT results */
94655   int nExpr            /* Number of result columns returned by SELECT */
94656 ){
94657   int eDest = pDest->eDest;
94658   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
94659     sqlcipher3ErrorMsg(pParse, "only a single result allowed for "
94660        "a SELECT that is part of an expression");
94661     return 1;
94662   }else{
94663     return 0;
94664   }
94665 }
94666 #endif
94667
94668 /*
94669 ** This routine generates the code for the inside of the inner loop
94670 ** of a SELECT.
94671 **
94672 ** If srcTab and nColumn are both zero, then the pEList expressions
94673 ** are evaluated in order to get the data for this row.  If nColumn>0
94674 ** then data is pulled from srcTab and pEList is used only to get the
94675 ** datatypes for each column.
94676 */
94677 static void selectInnerLoop(
94678   Parse *pParse,          /* The parser context */
94679   Select *p,              /* The complete select statement being coded */
94680   ExprList *pEList,       /* List of values being extracted */
94681   int srcTab,             /* Pull data from this table */
94682   int nColumn,            /* Number of columns in the source table */
94683   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
94684   int distinct,           /* If >=0, make sure results are distinct */
94685   SelectDest *pDest,      /* How to dispose of the results */
94686   int iContinue,          /* Jump here to continue with next row */
94687   int iBreak              /* Jump here to break out of the inner loop */
94688 ){
94689   Vdbe *v = pParse->pVdbe;
94690   int i;
94691   int hasDistinct;        /* True if the DISTINCT keyword is present */
94692   int regResult;              /* Start of memory holding result set */
94693   int eDest = pDest->eDest;   /* How to dispose of results */
94694   int iParm = pDest->iParm;   /* First argument to disposal method */
94695   int nResultCol;             /* Number of result columns */
94696
94697   assert( v );
94698   if( NEVER(v==0) ) return;
94699   assert( pEList!=0 );
94700   hasDistinct = distinct>=0;
94701   if( pOrderBy==0 && !hasDistinct ){
94702     codeOffset(v, p, iContinue);
94703   }
94704
94705   /* Pull the requested columns.
94706   */
94707   if( nColumn>0 ){
94708     nResultCol = nColumn;
94709   }else{
94710     nResultCol = pEList->nExpr;
94711   }
94712   if( pDest->iMem==0 ){
94713     pDest->iMem = pParse->nMem+1;
94714     pDest->nMem = nResultCol;
94715     pParse->nMem += nResultCol;
94716   }else{ 
94717     assert( pDest->nMem==nResultCol );
94718   }
94719   regResult = pDest->iMem;
94720   if( nColumn>0 ){
94721     for(i=0; i<nColumn; i++){
94722       sqlcipher3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
94723     }
94724   }else if( eDest!=SRT_Exists ){
94725     /* If the destination is an EXISTS(...) expression, the actual
94726     ** values returned by the SELECT are not required.
94727     */
94728     sqlcipher3ExprCacheClear(pParse);
94729     sqlcipher3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
94730   }
94731   nColumn = nResultCol;
94732
94733   /* If the DISTINCT keyword was present on the SELECT statement
94734   ** and this row has been seen before, then do not make this row
94735   ** part of the result.
94736   */
94737   if( hasDistinct ){
94738     assert( pEList!=0 );
94739     assert( pEList->nExpr==nColumn );
94740     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
94741     if( pOrderBy==0 ){
94742       codeOffset(v, p, iContinue);
94743     }
94744   }
94745
94746   switch( eDest ){
94747     /* In this mode, write each query result to the key of the temporary
94748     ** table iParm.
94749     */
94750 #ifndef SQLCIPHER_OMIT_COMPOUND_SELECT
94751     case SRT_Union: {
94752       int r1;
94753       r1 = sqlcipher3GetTempReg(pParse);
94754       sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
94755       sqlcipher3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
94756       sqlcipher3ReleaseTempReg(pParse, r1);
94757       break;
94758     }
94759
94760     /* Construct a record from the query result, but instead of
94761     ** saving that record, use it as a key to delete elements from
94762     ** the temporary table iParm.
94763     */
94764     case SRT_Except: {
94765       sqlcipher3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
94766       break;
94767     }
94768 #endif
94769
94770     /* Store the result as data using a unique key.
94771     */
94772     case SRT_Table:
94773     case SRT_EphemTab: {
94774       int r1 = sqlcipher3GetTempReg(pParse);
94775       testcase( eDest==SRT_Table );
94776       testcase( eDest==SRT_EphemTab );
94777       sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
94778       if( pOrderBy ){
94779         pushOntoSorter(pParse, pOrderBy, p, r1);
94780       }else{
94781         int r2 = sqlcipher3GetTempReg(pParse);
94782         sqlcipher3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
94783         sqlcipher3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
94784         sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
94785         sqlcipher3ReleaseTempReg(pParse, r2);
94786       }
94787       sqlcipher3ReleaseTempReg(pParse, r1);
94788       break;
94789     }
94790
94791 #ifndef SQLCIPHER_OMIT_SUBQUERY
94792     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
94793     ** then there should be a single item on the stack.  Write this
94794     ** item into the set table with bogus data.
94795     */
94796     case SRT_Set: {
94797       assert( nColumn==1 );
94798       p->affinity = sqlcipher3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
94799       if( pOrderBy ){
94800         /* At first glance you would think we could optimize out the
94801         ** ORDER BY in this case since the order of entries in the set
94802         ** does not matter.  But there might be a LIMIT clause, in which
94803         ** case the order does matter */
94804         pushOntoSorter(pParse, pOrderBy, p, regResult);
94805       }else{
94806         int r1 = sqlcipher3GetTempReg(pParse);
94807         sqlcipher3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
94808         sqlcipher3ExprCacheAffinityChange(pParse, regResult, 1);
94809         sqlcipher3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
94810         sqlcipher3ReleaseTempReg(pParse, r1);
94811       }
94812       break;
94813     }
94814
94815     /* If any row exist in the result set, record that fact and abort.
94816     */
94817     case SRT_Exists: {
94818       sqlcipher3VdbeAddOp2(v, OP_Integer, 1, iParm);
94819       /* The LIMIT clause will terminate the loop for us */
94820       break;
94821     }
94822
94823     /* If this is a scalar select that is part of an expression, then
94824     ** store the results in the appropriate memory cell and break out
94825     ** of the scan loop.
94826     */
94827     case SRT_Mem: {
94828       assert( nColumn==1 );
94829       if( pOrderBy ){
94830         pushOntoSorter(pParse, pOrderBy, p, regResult);
94831       }else{
94832         sqlcipher3ExprCodeMove(pParse, regResult, iParm, 1);
94833         /* The LIMIT clause will jump out of the loop for us */
94834       }
94835       break;
94836     }
94837 #endif /* #ifndef SQLCIPHER_OMIT_SUBQUERY */
94838
94839     /* Send the data to the callback function or to a subroutine.  In the
94840     ** case of a subroutine, the subroutine itself is responsible for
94841     ** popping the data from the stack.
94842     */
94843     case SRT_Coroutine:
94844     case SRT_Output: {
94845       testcase( eDest==SRT_Coroutine );
94846       testcase( eDest==SRT_Output );
94847       if( pOrderBy ){
94848         int r1 = sqlcipher3GetTempReg(pParse);
94849         sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
94850         pushOntoSorter(pParse, pOrderBy, p, r1);
94851         sqlcipher3ReleaseTempReg(pParse, r1);
94852       }else if( eDest==SRT_Coroutine ){
94853         sqlcipher3VdbeAddOp1(v, OP_Yield, pDest->iParm);
94854       }else{
94855         sqlcipher3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
94856         sqlcipher3ExprCacheAffinityChange(pParse, regResult, nColumn);
94857       }
94858       break;
94859     }
94860
94861 #if !defined(SQLCIPHER_OMIT_TRIGGER)
94862     /* Discard the results.  This is used for SELECT statements inside
94863     ** the body of a TRIGGER.  The purpose of such selects is to call
94864     ** user-defined functions that have side effects.  We do not care
94865     ** about the actual results of the select.
94866     */
94867     default: {
94868       assert( eDest==SRT_Discard );
94869       break;
94870     }
94871 #endif
94872   }
94873
94874   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
94875   ** there is a sorter, in which case the sorter has already limited
94876   ** the output for us.
94877   */
94878   if( pOrderBy==0 && p->iLimit ){
94879     sqlcipher3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
94880   }
94881 }
94882
94883 /*
94884 ** Given an expression list, generate a KeyInfo structure that records
94885 ** the collating sequence for each expression in that expression list.
94886 **
94887 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
94888 ** KeyInfo structure is appropriate for initializing a virtual index to
94889 ** implement that clause.  If the ExprList is the result set of a SELECT
94890 ** then the KeyInfo structure is appropriate for initializing a virtual
94891 ** index to implement a DISTINCT test.
94892 **
94893 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
94894 ** function is responsible for seeing that this structure is eventually
94895 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
94896 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
94897 */
94898 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
94899   sqlcipher3 *db = pParse->db;
94900   int nExpr;
94901   KeyInfo *pInfo;
94902   struct ExprList_item *pItem;
94903   int i;
94904
94905   nExpr = pList->nExpr;
94906   pInfo = sqlcipher3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
94907   if( pInfo ){
94908     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
94909     pInfo->nField = (u16)nExpr;
94910     pInfo->enc = ENC(db);
94911     pInfo->db = db;
94912     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
94913       CollSeq *pColl;
94914       pColl = sqlcipher3ExprCollSeq(pParse, pItem->pExpr);
94915       if( !pColl ){
94916         pColl = db->pDfltColl;
94917       }
94918       pInfo->aColl[i] = pColl;
94919       pInfo->aSortOrder[i] = pItem->sortOrder;
94920     }
94921   }
94922   return pInfo;
94923 }
94924
94925 #ifndef SQLCIPHER_OMIT_COMPOUND_SELECT
94926 /*
94927 ** Name of the connection operator, used for error messages.
94928 */
94929 static const char *selectOpName(int id){
94930   char *z;
94931   switch( id ){
94932     case TK_ALL:       z = "UNION ALL";   break;
94933     case TK_INTERSECT: z = "INTERSECT";   break;
94934     case TK_EXCEPT:    z = "EXCEPT";      break;
94935     default:           z = "UNION";       break;
94936   }
94937   return z;
94938 }
94939 #endif /* SQLCIPHER_OMIT_COMPOUND_SELECT */
94940
94941 #ifndef SQLCIPHER_OMIT_EXPLAIN
94942 /*
94943 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
94944 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
94945 ** where the caption is of the form:
94946 **
94947 **   "USE TEMP B-TREE FOR xxx"
94948 **
94949 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
94950 ** is determined by the zUsage argument.
94951 */
94952 static void explainTempTable(Parse *pParse, const char *zUsage){
94953   if( pParse->explain==2 ){
94954     Vdbe *v = pParse->pVdbe;
94955     char *zMsg = sqlcipher3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
94956     sqlcipher3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
94957   }
94958 }
94959
94960 /*
94961 ** Assign expression b to lvalue a. A second, no-op, version of this macro
94962 ** is provided when SQLCIPHER_OMIT_EXPLAIN is defined. This allows the code
94963 ** in sqlcipher3Select() to assign values to structure member variables that
94964 ** only exist if SQLCIPHER_OMIT_EXPLAIN is not defined without polluting the
94965 ** code with #ifndef directives.
94966 */
94967 # define explainSetInteger(a, b) a = b
94968
94969 #else
94970 /* No-op versions of the explainXXX() functions and macros. */
94971 # define explainTempTable(y,z)
94972 # define explainSetInteger(y,z)
94973 #endif
94974
94975 #if !defined(SQLCIPHER_OMIT_EXPLAIN) && !defined(SQLCIPHER_OMIT_COMPOUND_SELECT)
94976 /*
94977 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
94978 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
94979 ** where the caption is of one of the two forms:
94980 **
94981 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
94982 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
94983 **
94984 ** where iSub1 and iSub2 are the integers passed as the corresponding
94985 ** function parameters, and op is the text representation of the parameter
94986 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
94987 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
94988 ** false, or the second form if it is true.
94989 */
94990 static void explainComposite(
94991   Parse *pParse,                  /* Parse context */
94992   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
94993   int iSub1,                      /* Subquery id 1 */
94994   int iSub2,                      /* Subquery id 2 */
94995   int bUseTmp                     /* True if a temp table was used */
94996 ){
94997   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
94998   if( pParse->explain==2 ){
94999     Vdbe *v = pParse->pVdbe;
95000     char *zMsg = sqlcipher3MPrintf(
95001         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
95002         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
95003     );
95004     sqlcipher3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
95005   }
95006 }
95007 #else
95008 /* No-op versions of the explainXXX() functions and macros. */
95009 # define explainComposite(v,w,x,y,z)
95010 #endif
95011
95012 /*
95013 ** If the inner loop was generated using a non-null pOrderBy argument,
95014 ** then the results were placed in a sorter.  After the loop is terminated
95015 ** we need to run the sorter and output the results.  The following
95016 ** routine generates the code needed to do that.
95017 */
95018 static void generateSortTail(
95019   Parse *pParse,    /* Parsing context */
95020   Select *p,        /* The SELECT statement */
95021   Vdbe *v,          /* Generate code into this VDBE */
95022   int nColumn,      /* Number of columns of data */
95023   SelectDest *pDest /* Write the sorted results here */
95024 ){
95025   int addrBreak = sqlcipher3VdbeMakeLabel(v);     /* Jump here to exit loop */
95026   int addrContinue = sqlcipher3VdbeMakeLabel(v);  /* Jump here for next cycle */
95027   int addr;
95028   int iTab;
95029   int pseudoTab = 0;
95030   ExprList *pOrderBy = p->pOrderBy;
95031
95032   int eDest = pDest->eDest;
95033   int iParm = pDest->iParm;
95034
95035   int regRow;
95036   int regRowid;
95037
95038   iTab = pOrderBy->iECursor;
95039   regRow = sqlcipher3GetTempReg(pParse);
95040   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95041     pseudoTab = pParse->nTab++;
95042     sqlcipher3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
95043     regRowid = 0;
95044   }else{
95045     regRowid = sqlcipher3GetTempReg(pParse);
95046   }
95047   if( p->selFlags & SF_UseSorter ){
95048     int regSortOut = ++pParse->nMem;
95049     int ptab2 = pParse->nTab++;
95050     sqlcipher3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
95051     addr = 1 + sqlcipher3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
95052     codeOffset(v, p, addrContinue);
95053     sqlcipher3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
95054     sqlcipher3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
95055     sqlcipher3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95056   }else{
95057     addr = 1 + sqlcipher3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
95058     codeOffset(v, p, addrContinue);
95059     sqlcipher3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
95060   }
95061   switch( eDest ){
95062     case SRT_Table:
95063     case SRT_EphemTab: {
95064       testcase( eDest==SRT_Table );
95065       testcase( eDest==SRT_EphemTab );
95066       sqlcipher3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
95067       sqlcipher3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
95068       sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
95069       break;
95070     }
95071 #ifndef SQLCIPHER_OMIT_SUBQUERY
95072     case SRT_Set: {
95073       assert( nColumn==1 );
95074       sqlcipher3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
95075       sqlcipher3ExprCacheAffinityChange(pParse, regRow, 1);
95076       sqlcipher3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
95077       break;
95078     }
95079     case SRT_Mem: {
95080       assert( nColumn==1 );
95081       sqlcipher3ExprCodeMove(pParse, regRow, iParm, 1);
95082       /* The LIMIT clause will terminate the loop for us */
95083       break;
95084     }
95085 #endif
95086     default: {
95087       int i;
95088       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
95089       testcase( eDest==SRT_Output );
95090       testcase( eDest==SRT_Coroutine );
95091       for(i=0; i<nColumn; i++){
95092         assert( regRow!=pDest->iMem+i );
95093         sqlcipher3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
95094         if( i==0 ){
95095           sqlcipher3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95096         }
95097       }
95098       if( eDest==SRT_Output ){
95099         sqlcipher3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
95100         sqlcipher3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
95101       }else{
95102         sqlcipher3VdbeAddOp1(v, OP_Yield, pDest->iParm);
95103       }
95104       break;
95105     }
95106   }
95107   sqlcipher3ReleaseTempReg(pParse, regRow);
95108   sqlcipher3ReleaseTempReg(pParse, regRowid);
95109
95110   /* The bottom of the loop
95111   */
95112   sqlcipher3VdbeResolveLabel(v, addrContinue);
95113   if( p->selFlags & SF_UseSorter ){
95114     sqlcipher3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
95115   }else{
95116     sqlcipher3VdbeAddOp2(v, OP_Next, iTab, addr);
95117   }
95118   sqlcipher3VdbeResolveLabel(v, addrBreak);
95119   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95120     sqlcipher3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
95121   }
95122 }
95123
95124 /*
95125 ** Return a pointer to a string containing the 'declaration type' of the
95126 ** expression pExpr. The string may be treated as static by the caller.
95127 **
95128 ** The declaration type is the exact datatype definition extracted from the
95129 ** original CREATE TABLE statement if the expression is a column. The
95130 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
95131 ** is considered a column can be complex in the presence of subqueries. The
95132 ** result-set expression in all of the following SELECT statements is 
95133 ** considered a column by this function.
95134 **
95135 **   SELECT col FROM tbl;
95136 **   SELECT (SELECT col FROM tbl;
95137 **   SELECT (SELECT col FROM tbl);
95138 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
95139 ** 
95140 ** The declaration type for any expression other than a column is NULL.
95141 */
95142 static const char *columnType(
95143   NameContext *pNC, 
95144   Expr *pExpr,
95145   const char **pzOriginDb,
95146   const char **pzOriginTab,
95147   const char **pzOriginCol
95148 ){
95149   char const *zType = 0;
95150   char const *zOriginDb = 0;
95151   char const *zOriginTab = 0;
95152   char const *zOriginCol = 0;
95153   int j;
95154   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
95155
95156   switch( pExpr->op ){
95157     case TK_AGG_COLUMN:
95158     case TK_COLUMN: {
95159       /* The expression is a column. Locate the table the column is being
95160       ** extracted from in NameContext.pSrcList. This table may be real
95161       ** database table or a subquery.
95162       */
95163       Table *pTab = 0;            /* Table structure column is extracted from */
95164       Select *pS = 0;             /* Select the column is extracted from */
95165       int iCol = pExpr->iColumn;  /* Index of column in pTab */
95166       testcase( pExpr->op==TK_AGG_COLUMN );
95167       testcase( pExpr->op==TK_COLUMN );
95168       while( pNC && !pTab ){
95169         SrcList *pTabList = pNC->pSrcList;
95170         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
95171         if( j<pTabList->nSrc ){
95172           pTab = pTabList->a[j].pTab;
95173           pS = pTabList->a[j].pSelect;
95174         }else{
95175           pNC = pNC->pNext;
95176         }
95177       }
95178
95179       if( pTab==0 ){
95180         /* At one time, code such as "SELECT new.x" within a trigger would
95181         ** cause this condition to run.  Since then, we have restructured how
95182         ** trigger code is generated and so this condition is no longer 
95183         ** possible. However, it can still be true for statements like
95184         ** the following:
95185         **
95186         **   CREATE TABLE t1(col INTEGER);
95187         **   SELECT (SELECT t1.col) FROM FROM t1;
95188         **
95189         ** when columnType() is called on the expression "t1.col" in the 
95190         ** sub-select. In this case, set the column type to NULL, even
95191         ** though it should really be "INTEGER".
95192         **
95193         ** This is not a problem, as the column type of "t1.col" is never
95194         ** used. When columnType() is called on the expression 
95195         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
95196         ** branch below.  */
95197         break;
95198       }
95199
95200       assert( pTab && pExpr->pTab==pTab );
95201       if( pS ){
95202         /* The "table" is actually a sub-select or a view in the FROM clause
95203         ** of the SELECT statement. Return the declaration type and origin
95204         ** data for the result-set column of the sub-select.
95205         */
95206         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
95207           /* If iCol is less than zero, then the expression requests the
95208           ** rowid of the sub-select or view. This expression is legal (see 
95209           ** test case misc2.2.2) - it always evaluates to NULL.
95210           */
95211           NameContext sNC;
95212           Expr *p = pS->pEList->a[iCol].pExpr;
95213           sNC.pSrcList = pS->pSrc;
95214           sNC.pNext = pNC;
95215           sNC.pParse = pNC->pParse;
95216           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
95217         }
95218       }else if( ALWAYS(pTab->pSchema) ){
95219         /* A real table */
95220         assert( !pS );
95221         if( iCol<0 ) iCol = pTab->iPKey;
95222         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95223         if( iCol<0 ){
95224           zType = "INTEGER";
95225           zOriginCol = "rowid";
95226         }else{
95227           zType = pTab->aCol[iCol].zType;
95228           zOriginCol = pTab->aCol[iCol].zName;
95229         }
95230         zOriginTab = pTab->zName;
95231         if( pNC->pParse ){
95232           int iDb = sqlcipher3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
95233           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
95234         }
95235       }
95236       break;
95237     }
95238 #ifndef SQLCIPHER_OMIT_SUBQUERY
95239     case TK_SELECT: {
95240       /* The expression is a sub-select. Return the declaration type and
95241       ** origin info for the single column in the result set of the SELECT
95242       ** statement.
95243       */
95244       NameContext sNC;
95245       Select *pS = pExpr->x.pSelect;
95246       Expr *p = pS->pEList->a[0].pExpr;
95247       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
95248       sNC.pSrcList = pS->pSrc;
95249       sNC.pNext = pNC;
95250       sNC.pParse = pNC->pParse;
95251       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
95252       break;
95253     }
95254 #endif
95255   }
95256   
95257   if( pzOriginDb ){
95258     assert( pzOriginTab && pzOriginCol );
95259     *pzOriginDb = zOriginDb;
95260     *pzOriginTab = zOriginTab;
95261     *pzOriginCol = zOriginCol;
95262   }
95263   return zType;
95264 }
95265
95266 /*
95267 ** Generate code that will tell the VDBE the declaration types of columns
95268 ** in the result set.
95269 */
95270 static void generateColumnTypes(
95271   Parse *pParse,      /* Parser context */
95272   SrcList *pTabList,  /* List of tables */
95273   ExprList *pEList    /* Expressions defining the result set */
95274 ){
95275 #ifndef SQLCIPHER_OMIT_DECLTYPE
95276   Vdbe *v = pParse->pVdbe;
95277   int i;
95278   NameContext sNC;
95279   sNC.pSrcList = pTabList;
95280   sNC.pParse = pParse;
95281   for(i=0; i<pEList->nExpr; i++){
95282     Expr *p = pEList->a[i].pExpr;
95283     const char *zType;
95284 #ifdef SQLCIPHER_ENABLE_COLUMN_METADATA
95285     const char *zOrigDb = 0;
95286     const char *zOrigTab = 0;
95287     const char *zOrigCol = 0;
95288     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
95289
95290     /* The vdbe must make its own copy of the column-type and other 
95291     ** column specific strings, in case the schema is reset before this
95292     ** virtual machine is deleted.
95293     */
95294     sqlcipher3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLCIPHER_TRANSIENT);
95295     sqlcipher3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLCIPHER_TRANSIENT);
95296     sqlcipher3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLCIPHER_TRANSIENT);
95297 #else
95298     zType = columnType(&sNC, p, 0, 0, 0);
95299 #endif
95300     sqlcipher3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLCIPHER_TRANSIENT);
95301   }
95302 #endif /* SQLCIPHER_OMIT_DECLTYPE */
95303 }
95304
95305 /*
95306 ** Generate code that will tell the VDBE the names of columns
95307 ** in the result set.  This information is used to provide the
95308 ** azCol[] values in the callback.
95309 */
95310 static void generateColumnNames(
95311   Parse *pParse,      /* Parser context */
95312   SrcList *pTabList,  /* List of tables */
95313   ExprList *pEList    /* Expressions defining the result set */
95314 ){
95315   Vdbe *v = pParse->pVdbe;
95316   int i, j;
95317   sqlcipher3 *db = pParse->db;
95318   int fullNames, shortNames;
95319
95320 #ifndef SQLCIPHER_OMIT_EXPLAIN
95321   /* If this is an EXPLAIN, skip this step */
95322   if( pParse->explain ){
95323     return;
95324   }
95325 #endif
95326
95327   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
95328   pParse->colNamesSet = 1;
95329   fullNames = (db->flags & SQLCIPHER_FullColNames)!=0;
95330   shortNames = (db->flags & SQLCIPHER_ShortColNames)!=0;
95331   sqlcipher3VdbeSetNumCols(v, pEList->nExpr);
95332   for(i=0; i<pEList->nExpr; i++){
95333     Expr *p;
95334     p = pEList->a[i].pExpr;
95335     if( NEVER(p==0) ) continue;
95336     if( pEList->a[i].zName ){
95337       char *zName = pEList->a[i].zName;
95338       sqlcipher3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLCIPHER_TRANSIENT);
95339     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
95340       Table *pTab;
95341       char *zCol;
95342       int iCol = p->iColumn;
95343       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
95344         if( pTabList->a[j].iCursor==p->iTable ) break;
95345       }
95346       assert( j<pTabList->nSrc );
95347       pTab = pTabList->a[j].pTab;
95348       if( iCol<0 ) iCol = pTab->iPKey;
95349       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95350       if( iCol<0 ){
95351         zCol = "rowid";
95352       }else{
95353         zCol = pTab->aCol[iCol].zName;
95354       }
95355       if( !shortNames && !fullNames ){
95356         sqlcipher3VdbeSetColName(v, i, COLNAME_NAME, 
95357             sqlcipher3DbStrDup(db, pEList->a[i].zSpan), SQLCIPHER_DYNAMIC);
95358       }else if( fullNames ){
95359         char *zName = 0;
95360         zName = sqlcipher3MPrintf(db, "%s.%s", pTab->zName, zCol);
95361         sqlcipher3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLCIPHER_DYNAMIC);
95362       }else{
95363         sqlcipher3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLCIPHER_TRANSIENT);
95364       }
95365     }else{
95366       sqlcipher3VdbeSetColName(v, i, COLNAME_NAME, 
95367           sqlcipher3DbStrDup(db, pEList->a[i].zSpan), SQLCIPHER_DYNAMIC);
95368     }
95369   }
95370   generateColumnTypes(pParse, pTabList, pEList);
95371 }
95372
95373 /*
95374 ** Given a an expression list (which is really the list of expressions
95375 ** that form the result set of a SELECT statement) compute appropriate
95376 ** column names for a table that would hold the expression list.
95377 **
95378 ** All column names will be unique.
95379 **
95380 ** Only the column names are computed.  Column.zType, Column.zColl,
95381 ** and other fields of Column are zeroed.
95382 **
95383 ** Return SQLCIPHER_OK on success.  If a memory allocation error occurs,
95384 ** store NULL in *paCol and 0 in *pnCol and return SQLCIPHER_NOMEM.
95385 */
95386 static int selectColumnsFromExprList(
95387   Parse *pParse,          /* Parsing context */
95388   ExprList *pEList,       /* Expr list from which to derive column names */
95389   int *pnCol,             /* Write the number of columns here */
95390   Column **paCol          /* Write the new column list here */
95391 ){
95392   sqlcipher3 *db = pParse->db;   /* Database connection */
95393   int i, j;                   /* Loop counters */
95394   int cnt;                    /* Index added to make the name unique */
95395   Column *aCol, *pCol;        /* For looping over result columns */
95396   int nCol;                   /* Number of columns in the result set */
95397   Expr *p;                    /* Expression for a single result column */
95398   char *zName;                /* Column name */
95399   int nName;                  /* Size of name in zName[] */
95400
95401   *pnCol = nCol = pEList->nExpr;
95402   aCol = *paCol = sqlcipher3DbMallocZero(db, sizeof(aCol[0])*nCol);
95403   if( aCol==0 ) return SQLCIPHER_NOMEM;
95404   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
95405     /* Get an appropriate name for the column
95406     */
95407     p = pEList->a[i].pExpr;
95408     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
95409                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
95410     if( (zName = pEList->a[i].zName)!=0 ){
95411       /* If the column contains an "AS <name>" phrase, use <name> as the name */
95412       zName = sqlcipher3DbStrDup(db, zName);
95413     }else{
95414       Expr *pColExpr = p;  /* The expression that is the result column name */
95415       Table *pTab;         /* Table associated with this expression */
95416       while( pColExpr->op==TK_DOT ){
95417         pColExpr = pColExpr->pRight;
95418         assert( pColExpr!=0 );
95419       }
95420       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
95421         /* For columns use the column name name */
95422         int iCol = pColExpr->iColumn;
95423         pTab = pColExpr->pTab;
95424         if( iCol<0 ) iCol = pTab->iPKey;
95425         zName = sqlcipher3MPrintf(db, "%s",
95426                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
95427       }else if( pColExpr->op==TK_ID ){
95428         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
95429         zName = sqlcipher3MPrintf(db, "%s", pColExpr->u.zToken);
95430       }else{
95431         /* Use the original text of the column expression as its name */
95432         zName = sqlcipher3MPrintf(db, "%s", pEList->a[i].zSpan);
95433       }
95434     }
95435     if( db->mallocFailed ){
95436       sqlcipher3DbFree(db, zName);
95437       break;
95438     }
95439
95440     /* Make sure the column name is unique.  If the name is not unique,
95441     ** append a integer to the name so that it becomes unique.
95442     */
95443     nName = sqlcipher3Strlen30(zName);
95444     for(j=cnt=0; j<i; j++){
95445       if( sqlcipher3StrICmp(aCol[j].zName, zName)==0 ){
95446         char *zNewName;
95447         zName[nName] = 0;
95448         zNewName = sqlcipher3MPrintf(db, "%s:%d", zName, ++cnt);
95449         sqlcipher3DbFree(db, zName);
95450         zName = zNewName;
95451         j = -1;
95452         if( zName==0 ) break;
95453       }
95454     }
95455     pCol->zName = zName;
95456   }
95457   if( db->mallocFailed ){
95458     for(j=0; j<i; j++){
95459       sqlcipher3DbFree(db, aCol[j].zName);
95460     }
95461     sqlcipher3DbFree(db, aCol);
95462     *paCol = 0;
95463     *pnCol = 0;
95464     return SQLCIPHER_NOMEM;
95465   }
95466   return SQLCIPHER_OK;
95467 }
95468
95469 /*
95470 ** Add type and collation information to a column list based on
95471 ** a SELECT statement.
95472 ** 
95473 ** The column list presumably came from selectColumnNamesFromExprList().
95474 ** The column list has only names, not types or collations.  This
95475 ** routine goes through and adds the types and collations.
95476 **
95477 ** This routine requires that all identifiers in the SELECT
95478 ** statement be resolved.
95479 */
95480 static void selectAddColumnTypeAndCollation(
95481   Parse *pParse,        /* Parsing contexts */
95482   int nCol,             /* Number of columns */
95483   Column *aCol,         /* List of columns */
95484   Select *pSelect       /* SELECT used to determine types and collations */
95485 ){
95486   sqlcipher3 *db = pParse->db;
95487   NameContext sNC;
95488   Column *pCol;
95489   CollSeq *pColl;
95490   int i;
95491   Expr *p;
95492   struct ExprList_item *a;
95493
95494   assert( pSelect!=0 );
95495   assert( (pSelect->selFlags & SF_Resolved)!=0 );
95496   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
95497   if( db->mallocFailed ) return;
95498   memset(&sNC, 0, sizeof(sNC));
95499   sNC.pSrcList = pSelect->pSrc;
95500   a = pSelect->pEList->a;
95501   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
95502     p = a[i].pExpr;
95503     pCol->zType = sqlcipher3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
95504     pCol->affinity = sqlcipher3ExprAffinity(p);
95505     if( pCol->affinity==0 ) pCol->affinity = SQLCIPHER_AFF_NONE;
95506     pColl = sqlcipher3ExprCollSeq(pParse, p);
95507     if( pColl ){
95508       pCol->zColl = sqlcipher3DbStrDup(db, pColl->zName);
95509     }
95510   }
95511 }
95512
95513 /*
95514 ** Given a SELECT statement, generate a Table structure that describes
95515 ** the result set of that SELECT.
95516 */
95517 SQLCIPHER_PRIVATE Table *sqlcipher3ResultSetOfSelect(Parse *pParse, Select *pSelect){
95518   Table *pTab;
95519   sqlcipher3 *db = pParse->db;
95520   int savedFlags;
95521
95522   savedFlags = db->flags;
95523   db->flags &= ~SQLCIPHER_FullColNames;
95524   db->flags |= SQLCIPHER_ShortColNames;
95525   sqlcipher3SelectPrep(pParse, pSelect, 0);
95526   if( pParse->nErr ) return 0;
95527   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
95528   db->flags = savedFlags;
95529   pTab = sqlcipher3DbMallocZero(db, sizeof(Table) );
95530   if( pTab==0 ){
95531     return 0;
95532   }
95533   /* The sqlcipher3ResultSetOfSelect() is only used n contexts where lookaside
95534   ** is disabled */
95535   assert( db->lookaside.bEnabled==0 );
95536   pTab->nRef = 1;
95537   pTab->zName = 0;
95538   pTab->nRowEst = 1000000;
95539   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
95540   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
95541   pTab->iPKey = -1;
95542   if( db->mallocFailed ){
95543     sqlcipher3DeleteTable(db, pTab);
95544     return 0;
95545   }
95546   return pTab;
95547 }
95548
95549 /*
95550 ** Get a VDBE for the given parser context.  Create a new one if necessary.
95551 ** If an error occurs, return NULL and leave a message in pParse.
95552 */
95553 SQLCIPHER_PRIVATE Vdbe *sqlcipher3GetVdbe(Parse *pParse){
95554   Vdbe *v = pParse->pVdbe;
95555   if( v==0 ){
95556     v = pParse->pVdbe = sqlcipher3VdbeCreate(pParse->db);
95557 #ifndef SQLCIPHER_OMIT_TRACE
95558     if( v ){
95559       sqlcipher3VdbeAddOp0(v, OP_Trace);
95560     }
95561 #endif
95562   }
95563   return v;
95564 }
95565
95566
95567 /*
95568 ** Compute the iLimit and iOffset fields of the SELECT based on the
95569 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
95570 ** that appear in the original SQL statement after the LIMIT and OFFSET
95571 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
95572 ** are the integer memory register numbers for counters used to compute 
95573 ** the limit and offset.  If there is no limit and/or offset, then 
95574 ** iLimit and iOffset are negative.
95575 **
95576 ** This routine changes the values of iLimit and iOffset only if
95577 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
95578 ** iOffset should have been preset to appropriate default values
95579 ** (usually but not always -1) prior to calling this routine.
95580 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
95581 ** redefined.  The UNION ALL operator uses this property to force
95582 ** the reuse of the same limit and offset registers across multiple
95583 ** SELECT statements.
95584 */
95585 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
95586   Vdbe *v = 0;
95587   int iLimit = 0;
95588   int iOffset;
95589   int addr1, n;
95590   if( p->iLimit ) return;
95591
95592   /* 
95593   ** "LIMIT -1" always shows all rows.  There is some
95594   ** contraversy about what the correct behavior should be.
95595   ** The current implementation interprets "LIMIT 0" to mean
95596   ** no rows.
95597   */
95598   sqlcipher3ExprCacheClear(pParse);
95599   assert( p->pOffset==0 || p->pLimit!=0 );
95600   if( p->pLimit ){
95601     p->iLimit = iLimit = ++pParse->nMem;
95602     v = sqlcipher3GetVdbe(pParse);
95603     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
95604     if( sqlcipher3ExprIsInteger(p->pLimit, &n) ){
95605       sqlcipher3VdbeAddOp2(v, OP_Integer, n, iLimit);
95606       VdbeComment((v, "LIMIT counter"));
95607       if( n==0 ){
95608         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, iBreak);
95609       }else{
95610         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
95611       }
95612     }else{
95613       sqlcipher3ExprCode(pParse, p->pLimit, iLimit);
95614       sqlcipher3VdbeAddOp1(v, OP_MustBeInt, iLimit);
95615       VdbeComment((v, "LIMIT counter"));
95616       sqlcipher3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
95617     }
95618     if( p->pOffset ){
95619       p->iOffset = iOffset = ++pParse->nMem;
95620       pParse->nMem++;   /* Allocate an extra register for limit+offset */
95621       sqlcipher3ExprCode(pParse, p->pOffset, iOffset);
95622       sqlcipher3VdbeAddOp1(v, OP_MustBeInt, iOffset);
95623       VdbeComment((v, "OFFSET counter"));
95624       addr1 = sqlcipher3VdbeAddOp1(v, OP_IfPos, iOffset);
95625       sqlcipher3VdbeAddOp2(v, OP_Integer, 0, iOffset);
95626       sqlcipher3VdbeJumpHere(v, addr1);
95627       sqlcipher3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
95628       VdbeComment((v, "LIMIT+OFFSET"));
95629       addr1 = sqlcipher3VdbeAddOp1(v, OP_IfPos, iLimit);
95630       sqlcipher3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
95631       sqlcipher3VdbeJumpHere(v, addr1);
95632     }
95633   }
95634 }
95635
95636 #ifndef SQLCIPHER_OMIT_COMPOUND_SELECT
95637 /*
95638 ** Return the appropriate collating sequence for the iCol-th column of
95639 ** the result set for the compound-select statement "p".  Return NULL if
95640 ** the column has no default collating sequence.
95641 **
95642 ** The collating sequence for the compound select is taken from the
95643 ** left-most term of the select that has a collating sequence.
95644 */
95645 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
95646   CollSeq *pRet;
95647   if( p->pPrior ){
95648     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
95649   }else{
95650     pRet = 0;
95651   }
95652   assert( iCol>=0 );
95653   if( pRet==0 && iCol<p->pEList->nExpr ){
95654     pRet = sqlcipher3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
95655   }
95656   return pRet;
95657 }
95658 #endif /* SQLCIPHER_OMIT_COMPOUND_SELECT */
95659
95660 /* Forward reference */
95661 static int multiSelectOrderBy(
95662   Parse *pParse,        /* Parsing context */
95663   Select *p,            /* The right-most of SELECTs to be coded */
95664   SelectDest *pDest     /* What to do with query results */
95665 );
95666
95667
95668 #ifndef SQLCIPHER_OMIT_COMPOUND_SELECT
95669 /*
95670 ** This routine is called to process a compound query form from
95671 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
95672 ** INTERSECT
95673 **
95674 ** "p" points to the right-most of the two queries.  the query on the
95675 ** left is p->pPrior.  The left query could also be a compound query
95676 ** in which case this routine will be called recursively. 
95677 **
95678 ** The results of the total query are to be written into a destination
95679 ** of type eDest with parameter iParm.
95680 **
95681 ** Example 1:  Consider a three-way compound SQL statement.
95682 **
95683 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
95684 **
95685 ** This statement is parsed up as follows:
95686 **
95687 **     SELECT c FROM t3
95688 **      |
95689 **      `----->  SELECT b FROM t2
95690 **                |
95691 **                `------>  SELECT a FROM t1
95692 **
95693 ** The arrows in the diagram above represent the Select.pPrior pointer.
95694 ** So if this routine is called with p equal to the t3 query, then
95695 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
95696 **
95697 ** Notice that because of the way SQLite parses compound SELECTs, the
95698 ** individual selects always group from left to right.
95699 */
95700 static int multiSelect(
95701   Parse *pParse,        /* Parsing context */
95702   Select *p,            /* The right-most of SELECTs to be coded */
95703   SelectDest *pDest     /* What to do with query results */
95704 ){
95705   int rc = SQLCIPHER_OK;   /* Success code from a subroutine */
95706   Select *pPrior;       /* Another SELECT immediately to our left */
95707   Vdbe *v;              /* Generate code to this VDBE */
95708   SelectDest dest;      /* Alternative data destination */
95709   Select *pDelete = 0;  /* Chain of simple selects to delete */
95710   sqlcipher3 *db;          /* Database connection */
95711 #ifndef SQLCIPHER_OMIT_EXPLAIN
95712   int iSub1;            /* EQP id of left-hand query */
95713   int iSub2;            /* EQP id of right-hand query */
95714 #endif
95715
95716   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
95717   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
95718   */
95719   assert( p && p->pPrior );  /* Calling function guarantees this much */
95720   db = pParse->db;
95721   pPrior = p->pPrior;
95722   assert( pPrior->pRightmost!=pPrior );
95723   assert( pPrior->pRightmost==p->pRightmost );
95724   dest = *pDest;
95725   if( pPrior->pOrderBy ){
95726     sqlcipher3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
95727       selectOpName(p->op));
95728     rc = 1;
95729     goto multi_select_end;
95730   }
95731   if( pPrior->pLimit ){
95732     sqlcipher3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
95733       selectOpName(p->op));
95734     rc = 1;
95735     goto multi_select_end;
95736   }
95737
95738   v = sqlcipher3GetVdbe(pParse);
95739   assert( v!=0 );  /* The VDBE already created by calling function */
95740
95741   /* Create the destination temporary table if necessary
95742   */
95743   if( dest.eDest==SRT_EphemTab ){
95744     assert( p->pEList );
95745     sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
95746     sqlcipher3VdbeChangeP5(v, BTREE_UNORDERED);
95747     dest.eDest = SRT_Table;
95748   }
95749
95750   /* Make sure all SELECTs in the statement have the same number of elements
95751   ** in their result sets.
95752   */
95753   assert( p->pEList && pPrior->pEList );
95754   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
95755     sqlcipher3ErrorMsg(pParse, "SELECTs to the left and right of %s"
95756       " do not have the same number of result columns", selectOpName(p->op));
95757     rc = 1;
95758     goto multi_select_end;
95759   }
95760
95761   /* Compound SELECTs that have an ORDER BY clause are handled separately.
95762   */
95763   if( p->pOrderBy ){
95764     return multiSelectOrderBy(pParse, p, pDest);
95765   }
95766
95767   /* Generate code for the left and right SELECT statements.
95768   */
95769   switch( p->op ){
95770     case TK_ALL: {
95771       int addr = 0;
95772       int nLimit;
95773       assert( !pPrior->pLimit );
95774       pPrior->pLimit = p->pLimit;
95775       pPrior->pOffset = p->pOffset;
95776       explainSetInteger(iSub1, pParse->iNextSelectId);
95777       rc = sqlcipher3Select(pParse, pPrior, &dest);
95778       p->pLimit = 0;
95779       p->pOffset = 0;
95780       if( rc ){
95781         goto multi_select_end;
95782       }
95783       p->pPrior = 0;
95784       p->iLimit = pPrior->iLimit;
95785       p->iOffset = pPrior->iOffset;
95786       if( p->iLimit ){
95787         addr = sqlcipher3VdbeAddOp1(v, OP_IfZero, p->iLimit);
95788         VdbeComment((v, "Jump ahead if LIMIT reached"));
95789       }
95790       explainSetInteger(iSub2, pParse->iNextSelectId);
95791       rc = sqlcipher3Select(pParse, p, &dest);
95792       testcase( rc!=SQLCIPHER_OK );
95793       pDelete = p->pPrior;
95794       p->pPrior = pPrior;
95795       p->nSelectRow += pPrior->nSelectRow;
95796       if( pPrior->pLimit
95797        && sqlcipher3ExprIsInteger(pPrior->pLimit, &nLimit)
95798        && p->nSelectRow > (double)nLimit 
95799       ){
95800         p->nSelectRow = (double)nLimit;
95801       }
95802       if( addr ){
95803         sqlcipher3VdbeJumpHere(v, addr);
95804       }
95805       break;
95806     }
95807     case TK_EXCEPT:
95808     case TK_UNION: {
95809       int unionTab;    /* Cursor number of the temporary table holding result */
95810       u8 op = 0;       /* One of the SRT_ operations to apply to self */
95811       int priorOp;     /* The SRT_ operation to apply to prior selects */
95812       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
95813       int addr;
95814       SelectDest uniondest;
95815
95816       testcase( p->op==TK_EXCEPT );
95817       testcase( p->op==TK_UNION );
95818       priorOp = SRT_Union;
95819       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
95820         /* We can reuse a temporary table generated by a SELECT to our
95821         ** right.
95822         */
95823         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
95824                                      ** of a 3-way or more compound */
95825         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
95826         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
95827         unionTab = dest.iParm;
95828       }else{
95829         /* We will need to create our own temporary table to hold the
95830         ** intermediate results.
95831         */
95832         unionTab = pParse->nTab++;
95833         assert( p->pOrderBy==0 );
95834         addr = sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
95835         assert( p->addrOpenEphm[0] == -1 );
95836         p->addrOpenEphm[0] = addr;
95837         p->pRightmost->selFlags |= SF_UsesEphemeral;
95838         assert( p->pEList );
95839       }
95840
95841       /* Code the SELECT statements to our left
95842       */
95843       assert( !pPrior->pOrderBy );
95844       sqlcipher3SelectDestInit(&uniondest, priorOp, unionTab);
95845       explainSetInteger(iSub1, pParse->iNextSelectId);
95846       rc = sqlcipher3Select(pParse, pPrior, &uniondest);
95847       if( rc ){
95848         goto multi_select_end;
95849       }
95850
95851       /* Code the current SELECT statement
95852       */
95853       if( p->op==TK_EXCEPT ){
95854         op = SRT_Except;
95855       }else{
95856         assert( p->op==TK_UNION );
95857         op = SRT_Union;
95858       }
95859       p->pPrior = 0;
95860       pLimit = p->pLimit;
95861       p->pLimit = 0;
95862       pOffset = p->pOffset;
95863       p->pOffset = 0;
95864       uniondest.eDest = op;
95865       explainSetInteger(iSub2, pParse->iNextSelectId);
95866       rc = sqlcipher3Select(pParse, p, &uniondest);
95867       testcase( rc!=SQLCIPHER_OK );
95868       /* Query flattening in sqlcipher3Select() might refill p->pOrderBy.
95869       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
95870       sqlcipher3ExprListDelete(db, p->pOrderBy);
95871       pDelete = p->pPrior;
95872       p->pPrior = pPrior;
95873       p->pOrderBy = 0;
95874       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
95875       sqlcipher3ExprDelete(db, p->pLimit);
95876       p->pLimit = pLimit;
95877       p->pOffset = pOffset;
95878       p->iLimit = 0;
95879       p->iOffset = 0;
95880
95881       /* Convert the data in the temporary table into whatever form
95882       ** it is that we currently need.
95883       */
95884       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
95885       if( dest.eDest!=priorOp ){
95886         int iCont, iBreak, iStart;
95887         assert( p->pEList );
95888         if( dest.eDest==SRT_Output ){
95889           Select *pFirst = p;
95890           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
95891           generateColumnNames(pParse, 0, pFirst->pEList);
95892         }
95893         iBreak = sqlcipher3VdbeMakeLabel(v);
95894         iCont = sqlcipher3VdbeMakeLabel(v);
95895         computeLimitRegisters(pParse, p, iBreak);
95896         sqlcipher3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
95897         iStart = sqlcipher3VdbeCurrentAddr(v);
95898         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
95899                         0, -1, &dest, iCont, iBreak);
95900         sqlcipher3VdbeResolveLabel(v, iCont);
95901         sqlcipher3VdbeAddOp2(v, OP_Next, unionTab, iStart);
95902         sqlcipher3VdbeResolveLabel(v, iBreak);
95903         sqlcipher3VdbeAddOp2(v, OP_Close, unionTab, 0);
95904       }
95905       break;
95906     }
95907     default: assert( p->op==TK_INTERSECT ); {
95908       int tab1, tab2;
95909       int iCont, iBreak, iStart;
95910       Expr *pLimit, *pOffset;
95911       int addr;
95912       SelectDest intersectdest;
95913       int r1;
95914
95915       /* INTERSECT is different from the others since it requires
95916       ** two temporary tables.  Hence it has its own case.  Begin
95917       ** by allocating the tables we will need.
95918       */
95919       tab1 = pParse->nTab++;
95920       tab2 = pParse->nTab++;
95921       assert( p->pOrderBy==0 );
95922
95923       addr = sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
95924       assert( p->addrOpenEphm[0] == -1 );
95925       p->addrOpenEphm[0] = addr;
95926       p->pRightmost->selFlags |= SF_UsesEphemeral;
95927       assert( p->pEList );
95928
95929       /* Code the SELECTs to our left into temporary table "tab1".
95930       */
95931       sqlcipher3SelectDestInit(&intersectdest, SRT_Union, tab1);
95932       explainSetInteger(iSub1, pParse->iNextSelectId);
95933       rc = sqlcipher3Select(pParse, pPrior, &intersectdest);
95934       if( rc ){
95935         goto multi_select_end;
95936       }
95937
95938       /* Code the current SELECT into temporary table "tab2"
95939       */
95940       addr = sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
95941       assert( p->addrOpenEphm[1] == -1 );
95942       p->addrOpenEphm[1] = addr;
95943       p->pPrior = 0;
95944       pLimit = p->pLimit;
95945       p->pLimit = 0;
95946       pOffset = p->pOffset;
95947       p->pOffset = 0;
95948       intersectdest.iParm = tab2;
95949       explainSetInteger(iSub2, pParse->iNextSelectId);
95950       rc = sqlcipher3Select(pParse, p, &intersectdest);
95951       testcase( rc!=SQLCIPHER_OK );
95952       pDelete = p->pPrior;
95953       p->pPrior = pPrior;
95954       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
95955       sqlcipher3ExprDelete(db, p->pLimit);
95956       p->pLimit = pLimit;
95957       p->pOffset = pOffset;
95958
95959       /* Generate code to take the intersection of the two temporary
95960       ** tables.
95961       */
95962       assert( p->pEList );
95963       if( dest.eDest==SRT_Output ){
95964         Select *pFirst = p;
95965         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
95966         generateColumnNames(pParse, 0, pFirst->pEList);
95967       }
95968       iBreak = sqlcipher3VdbeMakeLabel(v);
95969       iCont = sqlcipher3VdbeMakeLabel(v);
95970       computeLimitRegisters(pParse, p, iBreak);
95971       sqlcipher3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
95972       r1 = sqlcipher3GetTempReg(pParse);
95973       iStart = sqlcipher3VdbeAddOp2(v, OP_RowKey, tab1, r1);
95974       sqlcipher3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
95975       sqlcipher3ReleaseTempReg(pParse, r1);
95976       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
95977                       0, -1, &dest, iCont, iBreak);
95978       sqlcipher3VdbeResolveLabel(v, iCont);
95979       sqlcipher3VdbeAddOp2(v, OP_Next, tab1, iStart);
95980       sqlcipher3VdbeResolveLabel(v, iBreak);
95981       sqlcipher3VdbeAddOp2(v, OP_Close, tab2, 0);
95982       sqlcipher3VdbeAddOp2(v, OP_Close, tab1, 0);
95983       break;
95984     }
95985   }
95986
95987   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
95988
95989   /* Compute collating sequences used by 
95990   ** temporary tables needed to implement the compound select.
95991   ** Attach the KeyInfo structure to all temporary tables.
95992   **
95993   ** This section is run by the right-most SELECT statement only.
95994   ** SELECT statements to the left always skip this part.  The right-most
95995   ** SELECT might also skip this part if it has no ORDER BY clause and
95996   ** no temp tables are required.
95997   */
95998   if( p->selFlags & SF_UsesEphemeral ){
95999     int i;                        /* Loop counter */
96000     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
96001     Select *pLoop;                /* For looping through SELECT statements */
96002     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
96003     int nCol;                     /* Number of columns in result set */
96004
96005     assert( p->pRightmost==p );
96006     nCol = p->pEList->nExpr;
96007     pKeyInfo = sqlcipher3DbMallocZero(db,
96008                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
96009     if( !pKeyInfo ){
96010       rc = SQLCIPHER_NOMEM;
96011       goto multi_select_end;
96012     }
96013
96014     pKeyInfo->enc = ENC(db);
96015     pKeyInfo->nField = (u16)nCol;
96016
96017     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
96018       *apColl = multiSelectCollSeq(pParse, p, i);
96019       if( 0==*apColl ){
96020         *apColl = db->pDfltColl;
96021       }
96022     }
96023
96024     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
96025       for(i=0; i<2; i++){
96026         int addr = pLoop->addrOpenEphm[i];
96027         if( addr<0 ){
96028           /* If [0] is unused then [1] is also unused.  So we can
96029           ** always safely abort as soon as the first unused slot is found */
96030           assert( pLoop->addrOpenEphm[1]<0 );
96031           break;
96032         }
96033         sqlcipher3VdbeChangeP2(v, addr, nCol);
96034         sqlcipher3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
96035         pLoop->addrOpenEphm[i] = -1;
96036       }
96037     }
96038     sqlcipher3DbFree(db, pKeyInfo);
96039   }
96040
96041 multi_select_end:
96042   pDest->iMem = dest.iMem;
96043   pDest->nMem = dest.nMem;
96044   sqlcipher3SelectDelete(db, pDelete);
96045   return rc;
96046 }
96047 #endif /* SQLCIPHER_OMIT_COMPOUND_SELECT */
96048
96049 /*
96050 ** Code an output subroutine for a coroutine implementation of a
96051 ** SELECT statment.
96052 **
96053 ** The data to be output is contained in pIn->iMem.  There are
96054 ** pIn->nMem columns to be output.  pDest is where the output should
96055 ** be sent.
96056 **
96057 ** regReturn is the number of the register holding the subroutine
96058 ** return address.
96059 **
96060 ** If regPrev>0 then it is the first register in a vector that
96061 ** records the previous output.  mem[regPrev] is a flag that is false
96062 ** if there has been no previous output.  If regPrev>0 then code is
96063 ** generated to suppress duplicates.  pKeyInfo is used for comparing
96064 ** keys.
96065 **
96066 ** If the LIMIT found in p->iLimit is reached, jump immediately to
96067 ** iBreak.
96068 */
96069 static int generateOutputSubroutine(
96070   Parse *pParse,          /* Parsing context */
96071   Select *p,              /* The SELECT statement */
96072   SelectDest *pIn,        /* Coroutine supplying data */
96073   SelectDest *pDest,      /* Where to send the data */
96074   int regReturn,          /* The return address register */
96075   int regPrev,            /* Previous result register.  No uniqueness if 0 */
96076   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
96077   int p4type,             /* The p4 type for pKeyInfo */
96078   int iBreak              /* Jump here if we hit the LIMIT */
96079 ){
96080   Vdbe *v = pParse->pVdbe;
96081   int iContinue;
96082   int addr;
96083
96084   addr = sqlcipher3VdbeCurrentAddr(v);
96085   iContinue = sqlcipher3VdbeMakeLabel(v);
96086
96087   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
96088   */
96089   if( regPrev ){
96090     int j1, j2;
96091     j1 = sqlcipher3VdbeAddOp1(v, OP_IfNot, regPrev);
96092     j2 = sqlcipher3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
96093                               (char*)pKeyInfo, p4type);
96094     sqlcipher3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
96095     sqlcipher3VdbeJumpHere(v, j1);
96096     sqlcipher3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
96097     sqlcipher3VdbeAddOp2(v, OP_Integer, 1, regPrev);
96098   }
96099   if( pParse->db->mallocFailed ) return 0;
96100
96101   /* Suppress the the first OFFSET entries if there is an OFFSET clause
96102   */
96103   codeOffset(v, p, iContinue);
96104
96105   switch( pDest->eDest ){
96106     /* Store the result as data using a unique key.
96107     */
96108     case SRT_Table:
96109     case SRT_EphemTab: {
96110       int r1 = sqlcipher3GetTempReg(pParse);
96111       int r2 = sqlcipher3GetTempReg(pParse);
96112       testcase( pDest->eDest==SRT_Table );
96113       testcase( pDest->eDest==SRT_EphemTab );
96114       sqlcipher3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
96115       sqlcipher3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
96116       sqlcipher3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
96117       sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
96118       sqlcipher3ReleaseTempReg(pParse, r2);
96119       sqlcipher3ReleaseTempReg(pParse, r1);
96120       break;
96121     }
96122
96123 #ifndef SQLCIPHER_OMIT_SUBQUERY
96124     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
96125     ** then there should be a single item on the stack.  Write this
96126     ** item into the set table with bogus data.
96127     */
96128     case SRT_Set: {
96129       int r1;
96130       assert( pIn->nMem==1 );
96131       p->affinity = 
96132          sqlcipher3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
96133       r1 = sqlcipher3GetTempReg(pParse);
96134       sqlcipher3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
96135       sqlcipher3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
96136       sqlcipher3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
96137       sqlcipher3ReleaseTempReg(pParse, r1);
96138       break;
96139     }
96140
96141 #if 0  /* Never occurs on an ORDER BY query */
96142     /* If any row exist in the result set, record that fact and abort.
96143     */
96144     case SRT_Exists: {
96145       sqlcipher3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
96146       /* The LIMIT clause will terminate the loop for us */
96147       break;
96148     }
96149 #endif
96150
96151     /* If this is a scalar select that is part of an expression, then
96152     ** store the results in the appropriate memory cell and break out
96153     ** of the scan loop.
96154     */
96155     case SRT_Mem: {
96156       assert( pIn->nMem==1 );
96157       sqlcipher3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
96158       /* The LIMIT clause will jump out of the loop for us */
96159       break;
96160     }
96161 #endif /* #ifndef SQLCIPHER_OMIT_SUBQUERY */
96162
96163     /* The results are stored in a sequence of registers
96164     ** starting at pDest->iMem.  Then the co-routine yields.
96165     */
96166     case SRT_Coroutine: {
96167       if( pDest->iMem==0 ){
96168         pDest->iMem = sqlcipher3GetTempRange(pParse, pIn->nMem);
96169         pDest->nMem = pIn->nMem;
96170       }
96171       sqlcipher3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
96172       sqlcipher3VdbeAddOp1(v, OP_Yield, pDest->iParm);
96173       break;
96174     }
96175
96176     /* If none of the above, then the result destination must be
96177     ** SRT_Output.  This routine is never called with any other
96178     ** destination other than the ones handled above or SRT_Output.
96179     **
96180     ** For SRT_Output, results are stored in a sequence of registers.  
96181     ** Then the OP_ResultRow opcode is used to cause sqlcipher3_step() to
96182     ** return the next row of result.
96183     */
96184     default: {
96185       assert( pDest->eDest==SRT_Output );
96186       sqlcipher3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
96187       sqlcipher3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
96188       break;
96189     }
96190   }
96191
96192   /* Jump to the end of the loop if the LIMIT is reached.
96193   */
96194   if( p->iLimit ){
96195     sqlcipher3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
96196   }
96197
96198   /* Generate the subroutine return
96199   */
96200   sqlcipher3VdbeResolveLabel(v, iContinue);
96201   sqlcipher3VdbeAddOp1(v, OP_Return, regReturn);
96202
96203   return addr;
96204 }
96205
96206 /*
96207 ** Alternative compound select code generator for cases when there
96208 ** is an ORDER BY clause.
96209 **
96210 ** We assume a query of the following form:
96211 **
96212 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
96213 **
96214 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
96215 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
96216 ** co-routines.  Then run the co-routines in parallel and merge the results
96217 ** into the output.  In addition to the two coroutines (called selectA and
96218 ** selectB) there are 7 subroutines:
96219 **
96220 **    outA:    Move the output of the selectA coroutine into the output
96221 **             of the compound query.
96222 **
96223 **    outB:    Move the output of the selectB coroutine into the output
96224 **             of the compound query.  (Only generated for UNION and
96225 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
96226 **             appears only in B.)
96227 **
96228 **    AltB:    Called when there is data from both coroutines and A<B.
96229 **
96230 **    AeqB:    Called when there is data from both coroutines and A==B.
96231 **
96232 **    AgtB:    Called when there is data from both coroutines and A>B.
96233 **
96234 **    EofA:    Called when data is exhausted from selectA.
96235 **
96236 **    EofB:    Called when data is exhausted from selectB.
96237 **
96238 ** The implementation of the latter five subroutines depend on which 
96239 ** <operator> is used:
96240 **
96241 **
96242 **             UNION ALL         UNION            EXCEPT          INTERSECT
96243 **          -------------  -----------------  --------------  -----------------
96244 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
96245 **
96246 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
96247 **
96248 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
96249 **
96250 **   EofA:   outB, nextB      outB, nextB          halt             halt
96251 **
96252 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
96253 **
96254 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
96255 ** causes an immediate jump to EofA and an EOF on B following nextB causes
96256 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
96257 ** following nextX causes a jump to the end of the select processing.
96258 **
96259 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
96260 ** within the output subroutine.  The regPrev register set holds the previously
96261 ** output value.  A comparison is made against this value and the output
96262 ** is skipped if the next results would be the same as the previous.
96263 **
96264 ** The implementation plan is to implement the two coroutines and seven
96265 ** subroutines first, then put the control logic at the bottom.  Like this:
96266 **
96267 **          goto Init
96268 **     coA: coroutine for left query (A)
96269 **     coB: coroutine for right query (B)
96270 **    outA: output one row of A
96271 **    outB: output one row of B (UNION and UNION ALL only)
96272 **    EofA: ...
96273 **    EofB: ...
96274 **    AltB: ...
96275 **    AeqB: ...
96276 **    AgtB: ...
96277 **    Init: initialize coroutine registers
96278 **          yield coA
96279 **          if eof(A) goto EofA
96280 **          yield coB
96281 **          if eof(B) goto EofB
96282 **    Cmpr: Compare A, B
96283 **          Jump AltB, AeqB, AgtB
96284 **     End: ...
96285 **
96286 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
96287 ** actually called using Gosub and they do not Return.  EofA and EofB loop
96288 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
96289 ** and AgtB jump to either L2 or to one of EofA or EofB.
96290 */
96291 #ifndef SQLCIPHER_OMIT_COMPOUND_SELECT
96292 static int multiSelectOrderBy(
96293   Parse *pParse,        /* Parsing context */
96294   Select *p,            /* The right-most of SELECTs to be coded */
96295   SelectDest *pDest     /* What to do with query results */
96296 ){
96297   int i, j;             /* Loop counters */
96298   Select *pPrior;       /* Another SELECT immediately to our left */
96299   Vdbe *v;              /* Generate code to this VDBE */
96300   SelectDest destA;     /* Destination for coroutine A */
96301   SelectDest destB;     /* Destination for coroutine B */
96302   int regAddrA;         /* Address register for select-A coroutine */
96303   int regEofA;          /* Flag to indicate when select-A is complete */
96304   int regAddrB;         /* Address register for select-B coroutine */
96305   int regEofB;          /* Flag to indicate when select-B is complete */
96306   int addrSelectA;      /* Address of the select-A coroutine */
96307   int addrSelectB;      /* Address of the select-B coroutine */
96308   int regOutA;          /* Address register for the output-A subroutine */
96309   int regOutB;          /* Address register for the output-B subroutine */
96310   int addrOutA;         /* Address of the output-A subroutine */
96311   int addrOutB = 0;     /* Address of the output-B subroutine */
96312   int addrEofA;         /* Address of the select-A-exhausted subroutine */
96313   int addrEofB;         /* Address of the select-B-exhausted subroutine */
96314   int addrAltB;         /* Address of the A<B subroutine */
96315   int addrAeqB;         /* Address of the A==B subroutine */
96316   int addrAgtB;         /* Address of the A>B subroutine */
96317   int regLimitA;        /* Limit register for select-A */
96318   int regLimitB;        /* Limit register for select-A */
96319   int regPrev;          /* A range of registers to hold previous output */
96320   int savedLimit;       /* Saved value of p->iLimit */
96321   int savedOffset;      /* Saved value of p->iOffset */
96322   int labelCmpr;        /* Label for the start of the merge algorithm */
96323   int labelEnd;         /* Label for the end of the overall SELECT stmt */
96324   int j1;               /* Jump instructions that get retargetted */
96325   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
96326   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
96327   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
96328   sqlcipher3 *db;          /* Database connection */
96329   ExprList *pOrderBy;   /* The ORDER BY clause */
96330   int nOrderBy;         /* Number of terms in the ORDER BY clause */
96331   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
96332 #ifndef SQLCIPHER_OMIT_EXPLAIN
96333   int iSub1;            /* EQP id of left-hand query */
96334   int iSub2;            /* EQP id of right-hand query */
96335 #endif
96336
96337   assert( p->pOrderBy!=0 );
96338   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
96339   db = pParse->db;
96340   v = pParse->pVdbe;
96341   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
96342   labelEnd = sqlcipher3VdbeMakeLabel(v);
96343   labelCmpr = sqlcipher3VdbeMakeLabel(v);
96344
96345
96346   /* Patch up the ORDER BY clause
96347   */
96348   op = p->op;  
96349   pPrior = p->pPrior;
96350   assert( pPrior->pOrderBy==0 );
96351   pOrderBy = p->pOrderBy;
96352   assert( pOrderBy );
96353   nOrderBy = pOrderBy->nExpr;
96354
96355   /* For operators other than UNION ALL we have to make sure that
96356   ** the ORDER BY clause covers every term of the result set.  Add
96357   ** terms to the ORDER BY clause as necessary.
96358   */
96359   if( op!=TK_ALL ){
96360     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
96361       struct ExprList_item *pItem;
96362       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
96363         assert( pItem->iCol>0 );
96364         if( pItem->iCol==i ) break;
96365       }
96366       if( j==nOrderBy ){
96367         Expr *pNew = sqlcipher3Expr(db, TK_INTEGER, 0);
96368         if( pNew==0 ) return SQLCIPHER_NOMEM;
96369         pNew->flags |= EP_IntValue;
96370         pNew->u.iValue = i;
96371         pOrderBy = sqlcipher3ExprListAppend(pParse, pOrderBy, pNew);
96372         pOrderBy->a[nOrderBy++].iCol = (u16)i;
96373       }
96374     }
96375   }
96376
96377   /* Compute the comparison permutation and keyinfo that is used with
96378   ** the permutation used to determine if the next
96379   ** row of results comes from selectA or selectB.  Also add explicit
96380   ** collations to the ORDER BY clause terms so that when the subqueries
96381   ** to the right and the left are evaluated, they use the correct
96382   ** collation.
96383   */
96384   aPermute = sqlcipher3DbMallocRaw(db, sizeof(int)*nOrderBy);
96385   if( aPermute ){
96386     struct ExprList_item *pItem;
96387     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
96388       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
96389       aPermute[i] = pItem->iCol - 1;
96390     }
96391     pKeyMerge =
96392       sqlcipher3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
96393     if( pKeyMerge ){
96394       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
96395       pKeyMerge->nField = (u16)nOrderBy;
96396       pKeyMerge->enc = ENC(db);
96397       for(i=0; i<nOrderBy; i++){
96398         CollSeq *pColl;
96399         Expr *pTerm = pOrderBy->a[i].pExpr;
96400         if( pTerm->flags & EP_ExpCollate ){
96401           pColl = pTerm->pColl;
96402         }else{
96403           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
96404           pTerm->flags |= EP_ExpCollate;
96405           pTerm->pColl = pColl;
96406         }
96407         pKeyMerge->aColl[i] = pColl;
96408         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
96409       }
96410     }
96411   }else{
96412     pKeyMerge = 0;
96413   }
96414
96415   /* Reattach the ORDER BY clause to the query.
96416   */
96417   p->pOrderBy = pOrderBy;
96418   pPrior->pOrderBy = sqlcipher3ExprListDup(pParse->db, pOrderBy, 0);
96419
96420   /* Allocate a range of temporary registers and the KeyInfo needed
96421   ** for the logic that removes duplicate result rows when the
96422   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
96423   */
96424   if( op==TK_ALL ){
96425     regPrev = 0;
96426   }else{
96427     int nExpr = p->pEList->nExpr;
96428     assert( nOrderBy>=nExpr || db->mallocFailed );
96429     regPrev = sqlcipher3GetTempRange(pParse, nExpr+1);
96430     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regPrev);
96431     pKeyDup = sqlcipher3DbMallocZero(db,
96432                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
96433     if( pKeyDup ){
96434       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
96435       pKeyDup->nField = (u16)nExpr;
96436       pKeyDup->enc = ENC(db);
96437       for(i=0; i<nExpr; i++){
96438         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
96439         pKeyDup->aSortOrder[i] = 0;
96440       }
96441     }
96442   }
96443  
96444   /* Separate the left and the right query from one another
96445   */
96446   p->pPrior = 0;
96447   sqlcipher3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
96448   if( pPrior->pPrior==0 ){
96449     sqlcipher3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
96450   }
96451
96452   /* Compute the limit registers */
96453   computeLimitRegisters(pParse, p, labelEnd);
96454   if( p->iLimit && op==TK_ALL ){
96455     regLimitA = ++pParse->nMem;
96456     regLimitB = ++pParse->nMem;
96457     sqlcipher3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
96458                                   regLimitA);
96459     sqlcipher3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
96460   }else{
96461     regLimitA = regLimitB = 0;
96462   }
96463   sqlcipher3ExprDelete(db, p->pLimit);
96464   p->pLimit = 0;
96465   sqlcipher3ExprDelete(db, p->pOffset);
96466   p->pOffset = 0;
96467
96468   regAddrA = ++pParse->nMem;
96469   regEofA = ++pParse->nMem;
96470   regAddrB = ++pParse->nMem;
96471   regEofB = ++pParse->nMem;
96472   regOutA = ++pParse->nMem;
96473   regOutB = ++pParse->nMem;
96474   sqlcipher3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
96475   sqlcipher3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
96476
96477   /* Jump past the various subroutines and coroutines to the main
96478   ** merge loop
96479   */
96480   j1 = sqlcipher3VdbeAddOp0(v, OP_Goto);
96481   addrSelectA = sqlcipher3VdbeCurrentAddr(v);
96482
96483
96484   /* Generate a coroutine to evaluate the SELECT statement to the
96485   ** left of the compound operator - the "A" select.
96486   */
96487   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
96488   pPrior->iLimit = regLimitA;
96489   explainSetInteger(iSub1, pParse->iNextSelectId);
96490   sqlcipher3Select(pParse, pPrior, &destA);
96491   sqlcipher3VdbeAddOp2(v, OP_Integer, 1, regEofA);
96492   sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrA);
96493   VdbeNoopComment((v, "End coroutine for left SELECT"));
96494
96495   /* Generate a coroutine to evaluate the SELECT statement on 
96496   ** the right - the "B" select
96497   */
96498   addrSelectB = sqlcipher3VdbeCurrentAddr(v);
96499   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
96500   savedLimit = p->iLimit;
96501   savedOffset = p->iOffset;
96502   p->iLimit = regLimitB;
96503   p->iOffset = 0;  
96504   explainSetInteger(iSub2, pParse->iNextSelectId);
96505   sqlcipher3Select(pParse, p, &destB);
96506   p->iLimit = savedLimit;
96507   p->iOffset = savedOffset;
96508   sqlcipher3VdbeAddOp2(v, OP_Integer, 1, regEofB);
96509   sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrB);
96510   VdbeNoopComment((v, "End coroutine for right SELECT"));
96511
96512   /* Generate a subroutine that outputs the current row of the A
96513   ** select as the next output row of the compound select.
96514   */
96515   VdbeNoopComment((v, "Output routine for A"));
96516   addrOutA = generateOutputSubroutine(pParse,
96517                  p, &destA, pDest, regOutA,
96518                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
96519   
96520   /* Generate a subroutine that outputs the current row of the B
96521   ** select as the next output row of the compound select.
96522   */
96523   if( op==TK_ALL || op==TK_UNION ){
96524     VdbeNoopComment((v, "Output routine for B"));
96525     addrOutB = generateOutputSubroutine(pParse,
96526                  p, &destB, pDest, regOutB,
96527                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
96528   }
96529
96530   /* Generate a subroutine to run when the results from select A
96531   ** are exhausted and only data in select B remains.
96532   */
96533   VdbeNoopComment((v, "eof-A subroutine"));
96534   if( op==TK_EXCEPT || op==TK_INTERSECT ){
96535     addrEofA = sqlcipher3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
96536   }else{  
96537     addrEofA = sqlcipher3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
96538     sqlcipher3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
96539     sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrB);
96540     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
96541     p->nSelectRow += pPrior->nSelectRow;
96542   }
96543
96544   /* Generate a subroutine to run when the results from select B
96545   ** are exhausted and only data in select A remains.
96546   */
96547   if( op==TK_INTERSECT ){
96548     addrEofB = addrEofA;
96549     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
96550   }else{  
96551     VdbeNoopComment((v, "eof-B subroutine"));
96552     addrEofB = sqlcipher3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
96553     sqlcipher3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
96554     sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrA);
96555     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
96556   }
96557
96558   /* Generate code to handle the case of A<B
96559   */
96560   VdbeNoopComment((v, "A-lt-B subroutine"));
96561   addrAltB = sqlcipher3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
96562   sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrA);
96563   sqlcipher3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96564   sqlcipher3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96565
96566   /* Generate code to handle the case of A==B
96567   */
96568   if( op==TK_ALL ){
96569     addrAeqB = addrAltB;
96570   }else if( op==TK_INTERSECT ){
96571     addrAeqB = addrAltB;
96572     addrAltB++;
96573   }else{
96574     VdbeNoopComment((v, "A-eq-B subroutine"));
96575     addrAeqB =
96576     sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrA);
96577     sqlcipher3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96578     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96579   }
96580
96581   /* Generate code to handle the case of A>B
96582   */
96583   VdbeNoopComment((v, "A-gt-B subroutine"));
96584   addrAgtB = sqlcipher3VdbeCurrentAddr(v);
96585   if( op==TK_ALL || op==TK_UNION ){
96586     sqlcipher3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
96587   }
96588   sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrB);
96589   sqlcipher3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
96590   sqlcipher3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96591
96592   /* This code runs once to initialize everything.
96593   */
96594   sqlcipher3VdbeJumpHere(v, j1);
96595   sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regEofA);
96596   sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regEofB);
96597   sqlcipher3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
96598   sqlcipher3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
96599   sqlcipher3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96600   sqlcipher3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
96601
96602   /* Implement the main merge loop
96603   */
96604   sqlcipher3VdbeResolveLabel(v, labelCmpr);
96605   sqlcipher3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
96606   sqlcipher3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
96607                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
96608   sqlcipher3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
96609
96610   /* Release temporary registers
96611   */
96612   if( regPrev ){
96613     sqlcipher3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
96614   }
96615
96616   /* Jump to the this point in order to terminate the query.
96617   */
96618   sqlcipher3VdbeResolveLabel(v, labelEnd);
96619
96620   /* Set the number of output columns
96621   */
96622   if( pDest->eDest==SRT_Output ){
96623     Select *pFirst = pPrior;
96624     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96625     generateColumnNames(pParse, 0, pFirst->pEList);
96626   }
96627
96628   /* Reassembly the compound query so that it will be freed correctly
96629   ** by the calling function */
96630   if( p->pPrior ){
96631     sqlcipher3SelectDelete(db, p->pPrior);
96632   }
96633   p->pPrior = pPrior;
96634
96635   /*** TBD:  Insert subroutine calls to close cursors on incomplete
96636   **** subqueries ****/
96637   explainComposite(pParse, p->op, iSub1, iSub2, 0);
96638   return SQLCIPHER_OK;
96639 }
96640 #endif
96641
96642 #if !defined(SQLCIPHER_OMIT_SUBQUERY) || !defined(SQLCIPHER_OMIT_VIEW)
96643 /* Forward Declarations */
96644 static void substExprList(sqlcipher3*, ExprList*, int, ExprList*);
96645 static void substSelect(sqlcipher3*, Select *, int, ExprList *);
96646
96647 /*
96648 ** Scan through the expression pExpr.  Replace every reference to
96649 ** a column in table number iTable with a copy of the iColumn-th
96650 ** entry in pEList.  (But leave references to the ROWID column 
96651 ** unchanged.)
96652 **
96653 ** This routine is part of the flattening procedure.  A subquery
96654 ** whose result set is defined by pEList appears as entry in the
96655 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
96656 ** FORM clause entry is iTable.  This routine make the necessary 
96657 ** changes to pExpr so that it refers directly to the source table
96658 ** of the subquery rather the result set of the subquery.
96659 */
96660 static Expr *substExpr(
96661   sqlcipher3 *db,        /* Report malloc errors to this connection */
96662   Expr *pExpr,        /* Expr in which substitution occurs */
96663   int iTable,         /* Table to be substituted */
96664   ExprList *pEList    /* Substitute expressions */
96665 ){
96666   if( pExpr==0 ) return 0;
96667   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
96668     if( pExpr->iColumn<0 ){
96669       pExpr->op = TK_NULL;
96670     }else{
96671       Expr *pNew;
96672       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
96673       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
96674       pNew = sqlcipher3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
96675       if( pNew && pExpr->pColl ){
96676         pNew->pColl = pExpr->pColl;
96677       }
96678       sqlcipher3ExprDelete(db, pExpr);
96679       pExpr = pNew;
96680     }
96681   }else{
96682     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
96683     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
96684     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
96685       substSelect(db, pExpr->x.pSelect, iTable, pEList);
96686     }else{
96687       substExprList(db, pExpr->x.pList, iTable, pEList);
96688     }
96689   }
96690   return pExpr;
96691 }
96692 static void substExprList(
96693   sqlcipher3 *db,         /* Report malloc errors here */
96694   ExprList *pList,     /* List to scan and in which to make substitutes */
96695   int iTable,          /* Table to be substituted */
96696   ExprList *pEList     /* Substitute values */
96697 ){
96698   int i;
96699   if( pList==0 ) return;
96700   for(i=0; i<pList->nExpr; i++){
96701     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
96702   }
96703 }
96704 static void substSelect(
96705   sqlcipher3 *db,         /* Report malloc errors here */
96706   Select *p,           /* SELECT statement in which to make substitutions */
96707   int iTable,          /* Table to be replaced */
96708   ExprList *pEList     /* Substitute values */
96709 ){
96710   SrcList *pSrc;
96711   struct SrcList_item *pItem;
96712   int i;
96713   if( !p ) return;
96714   substExprList(db, p->pEList, iTable, pEList);
96715   substExprList(db, p->pGroupBy, iTable, pEList);
96716   substExprList(db, p->pOrderBy, iTable, pEList);
96717   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
96718   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
96719   substSelect(db, p->pPrior, iTable, pEList);
96720   pSrc = p->pSrc;
96721   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
96722   if( ALWAYS(pSrc) ){
96723     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
96724       substSelect(db, pItem->pSelect, iTable, pEList);
96725     }
96726   }
96727 }
96728 #endif /* !defined(SQLCIPHER_OMIT_SUBQUERY) || !defined(SQLCIPHER_OMIT_VIEW) */
96729
96730 #if !defined(SQLCIPHER_OMIT_SUBQUERY) || !defined(SQLCIPHER_OMIT_VIEW)
96731 /*
96732 ** This routine attempts to flatten subqueries in order to speed
96733 ** execution.  It returns 1 if it makes changes and 0 if no flattening
96734 ** occurs.
96735 **
96736 ** To understand the concept of flattening, consider the following
96737 ** query:
96738 **
96739 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
96740 **
96741 ** The default way of implementing this query is to execute the
96742 ** subquery first and store the results in a temporary table, then
96743 ** run the outer query on that temporary table.  This requires two
96744 ** passes over the data.  Furthermore, because the temporary table
96745 ** has no indices, the WHERE clause on the outer query cannot be
96746 ** optimized.
96747 **
96748 ** This routine attempts to rewrite queries such as the above into
96749 ** a single flat select, like this:
96750 **
96751 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
96752 **
96753 ** The code generated for this simpification gives the same result
96754 ** but only has to scan the data once.  And because indices might 
96755 ** exist on the table t1, a complete scan of the data might be
96756 ** avoided.
96757 **
96758 ** Flattening is only attempted if all of the following are true:
96759 **
96760 **   (1)  The subquery and the outer query do not both use aggregates.
96761 **
96762 **   (2)  The subquery is not an aggregate or the outer query is not a join.
96763 **
96764 **   (3)  The subquery is not the right operand of a left outer join
96765 **        (Originally ticket #306.  Strengthened by ticket #3300)
96766 **
96767 **   (4)  The subquery is not DISTINCT.
96768 **
96769 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
96770 **        sub-queries that were excluded from this optimization. Restriction 
96771 **        (4) has since been expanded to exclude all DISTINCT subqueries.
96772 **
96773 **   (6)  The subquery does not use aggregates or the outer query is not
96774 **        DISTINCT.
96775 **
96776 **   (7)  The subquery has a FROM clause.
96777 **
96778 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
96779 **
96780 **   (9)  The subquery does not use LIMIT or the outer query does not use
96781 **        aggregates.
96782 **
96783 **  (10)  The subquery does not use aggregates or the outer query does not
96784 **        use LIMIT.
96785 **
96786 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
96787 **
96788 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
96789 **        a separate restriction deriving from ticket #350.
96790 **
96791 **  (13)  The subquery and outer query do not both use LIMIT.
96792 **
96793 **  (14)  The subquery does not use OFFSET.
96794 **
96795 **  (15)  The outer query is not part of a compound select or the
96796 **        subquery does not have a LIMIT clause.
96797 **        (See ticket #2339 and ticket [02a8e81d44]).
96798 **
96799 **  (16)  The outer query is not an aggregate or the subquery does
96800 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
96801 **        until we introduced the group_concat() function.  
96802 **
96803 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
96804 **        compound clause made up entirely of non-aggregate queries, and 
96805 **        the parent query:
96806 **
96807 **          * is not itself part of a compound select,
96808 **          * is not an aggregate or DISTINCT query, and
96809 **          * has no other tables or sub-selects in the FROM clause.
96810 **
96811 **        The parent and sub-query may contain WHERE clauses. Subject to
96812 **        rules (11), (13) and (14), they may also contain ORDER BY,
96813 **        LIMIT and OFFSET clauses.
96814 **
96815 **  (18)  If the sub-query is a compound select, then all terms of the
96816 **        ORDER by clause of the parent must be simple references to 
96817 **        columns of the sub-query.
96818 **
96819 **  (19)  The subquery does not use LIMIT or the outer query does not
96820 **        have a WHERE clause.
96821 **
96822 **  (20)  If the sub-query is a compound select, then it must not use
96823 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
96824 **        somewhat by saying that the terms of the ORDER BY clause must
96825 **        appear as unmodified result columns in the outer query.  But
96826 **        have other optimizations in mind to deal with that case.
96827 **
96828 **  (21)  The subquery does not use LIMIT or the outer query is not
96829 **        DISTINCT.  (See ticket [752e1646fc]).
96830 **
96831 ** In this routine, the "p" parameter is a pointer to the outer query.
96832 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
96833 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
96834 **
96835 ** If flattening is not attempted, this routine is a no-op and returns 0.
96836 ** If flattening is attempted this routine returns 1.
96837 **
96838 ** All of the expression analysis must occur on both the outer query and
96839 ** the subquery before this routine runs.
96840 */
96841 static int flattenSubquery(
96842   Parse *pParse,       /* Parsing context */
96843   Select *p,           /* The parent or outer SELECT statement */
96844   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
96845   int isAgg,           /* True if outer SELECT uses aggregate functions */
96846   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
96847 ){
96848   const char *zSavedAuthContext = pParse->zAuthContext;
96849   Select *pParent;
96850   Select *pSub;       /* The inner query or "subquery" */
96851   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
96852   SrcList *pSrc;      /* The FROM clause of the outer query */
96853   SrcList *pSubSrc;   /* The FROM clause of the subquery */
96854   ExprList *pList;    /* The result set of the outer query */
96855   int iParent;        /* VDBE cursor number of the pSub result set temp table */
96856   int i;              /* Loop counter */
96857   Expr *pWhere;                    /* The WHERE clause */
96858   struct SrcList_item *pSubitem;   /* The subquery */
96859   sqlcipher3 *db = pParse->db;
96860
96861   /* Check to see if flattening is permitted.  Return 0 if not.
96862   */
96863   assert( p!=0 );
96864   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
96865   if( db->flags & SQLCIPHER_QueryFlattener ) return 0;
96866   pSrc = p->pSrc;
96867   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
96868   pSubitem = &pSrc->a[iFrom];
96869   iParent = pSubitem->iCursor;
96870   pSub = pSubitem->pSelect;
96871   assert( pSub!=0 );
96872   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
96873   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
96874   pSubSrc = pSub->pSrc;
96875   assert( pSubSrc );
96876   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
96877   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
96878   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
96879   ** became arbitrary expressions, we were forced to add restrictions (13)
96880   ** and (14). */
96881   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
96882   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
96883   if( p->pRightmost && pSub->pLimit ){
96884     return 0;                                            /* Restriction (15) */
96885   }
96886   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
96887   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
96888   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
96889      return 0;         /* Restrictions (8)(9) */
96890   }
96891   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
96892      return 0;         /* Restriction (6)  */
96893   }
96894   if( p->pOrderBy && pSub->pOrderBy ){
96895      return 0;                                           /* Restriction (11) */
96896   }
96897   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
96898   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
96899   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
96900      return 0;         /* Restriction (21) */
96901   }
96902
96903   /* OBSOLETE COMMENT 1:
96904   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
96905   ** not used as the right operand of an outer join.  Examples of why this
96906   ** is not allowed:
96907   **
96908   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
96909   **
96910   ** If we flatten the above, we would get
96911   **
96912   **         (t1 LEFT OUTER JOIN t2) JOIN t3
96913   **
96914   ** which is not at all the same thing.
96915   **
96916   ** OBSOLETE COMMENT 2:
96917   ** Restriction 12:  If the subquery is the right operand of a left outer
96918   ** join, make sure the subquery has no WHERE clause.
96919   ** An examples of why this is not allowed:
96920   **
96921   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
96922   **
96923   ** If we flatten the above, we would get
96924   **
96925   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
96926   **
96927   ** But the t2.x>0 test will always fail on a NULL row of t2, which
96928   ** effectively converts the OUTER JOIN into an INNER JOIN.
96929   **
96930   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
96931   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
96932   ** is fraught with danger.  Best to avoid the whole thing.  If the
96933   ** subquery is the right term of a LEFT JOIN, then do not flatten.
96934   */
96935   if( (pSubitem->jointype & JT_OUTER)!=0 ){
96936     return 0;
96937   }
96938
96939   /* Restriction 17: If the sub-query is a compound SELECT, then it must
96940   ** use only the UNION ALL operator. And none of the simple select queries
96941   ** that make up the compound SELECT are allowed to be aggregate or distinct
96942   ** queries.
96943   */
96944   if( pSub->pPrior ){
96945     if( pSub->pOrderBy ){
96946       return 0;  /* Restriction 20 */
96947     }
96948     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
96949       return 0;
96950     }
96951     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
96952       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
96953       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
96954       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
96955        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
96956        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
96957       ){
96958         return 0;
96959       }
96960     }
96961
96962     /* Restriction 18. */
96963     if( p->pOrderBy ){
96964       int ii;
96965       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
96966         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
96967       }
96968     }
96969   }
96970
96971   /***** If we reach this point, flattening is permitted. *****/
96972
96973   /* Authorize the subquery */
96974   pParse->zAuthContext = pSubitem->zName;
96975   sqlcipher3AuthCheck(pParse, SQLCIPHER_SELECT, 0, 0, 0);
96976   pParse->zAuthContext = zSavedAuthContext;
96977
96978   /* If the sub-query is a compound SELECT statement, then (by restrictions
96979   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
96980   ** be of the form:
96981   **
96982   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
96983   **
96984   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
96985   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
96986   ** OFFSET clauses and joins them to the left-hand-side of the original
96987   ** using UNION ALL operators. In this case N is the number of simple
96988   ** select statements in the compound sub-query.
96989   **
96990   ** Example:
96991   **
96992   **     SELECT a+1 FROM (
96993   **        SELECT x FROM tab
96994   **        UNION ALL
96995   **        SELECT y FROM tab
96996   **        UNION ALL
96997   **        SELECT abs(z*2) FROM tab2
96998   **     ) WHERE a!=5 ORDER BY 1
96999   **
97000   ** Transformed into:
97001   **
97002   **     SELECT x+1 FROM tab WHERE x+1!=5
97003   **     UNION ALL
97004   **     SELECT y+1 FROM tab WHERE y+1!=5
97005   **     UNION ALL
97006   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
97007   **     ORDER BY 1
97008   **
97009   ** We call this the "compound-subquery flattening".
97010   */
97011   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
97012     Select *pNew;
97013     ExprList *pOrderBy = p->pOrderBy;
97014     Expr *pLimit = p->pLimit;
97015     Select *pPrior = p->pPrior;
97016     p->pOrderBy = 0;
97017     p->pSrc = 0;
97018     p->pPrior = 0;
97019     p->pLimit = 0;
97020     pNew = sqlcipher3SelectDup(db, p, 0);
97021     p->pLimit = pLimit;
97022     p->pOrderBy = pOrderBy;
97023     p->pSrc = pSrc;
97024     p->op = TK_ALL;
97025     p->pRightmost = 0;
97026     if( pNew==0 ){
97027       pNew = pPrior;
97028     }else{
97029       pNew->pPrior = pPrior;
97030       pNew->pRightmost = 0;
97031     }
97032     p->pPrior = pNew;
97033     if( db->mallocFailed ) return 1;
97034   }
97035
97036   /* Begin flattening the iFrom-th entry of the FROM clause 
97037   ** in the outer query.
97038   */
97039   pSub = pSub1 = pSubitem->pSelect;
97040
97041   /* Delete the transient table structure associated with the
97042   ** subquery
97043   */
97044   sqlcipher3DbFree(db, pSubitem->zDatabase);
97045   sqlcipher3DbFree(db, pSubitem->zName);
97046   sqlcipher3DbFree(db, pSubitem->zAlias);
97047   pSubitem->zDatabase = 0;
97048   pSubitem->zName = 0;
97049   pSubitem->zAlias = 0;
97050   pSubitem->pSelect = 0;
97051
97052   /* Defer deleting the Table object associated with the
97053   ** subquery until code generation is
97054   ** complete, since there may still exist Expr.pTab entries that
97055   ** refer to the subquery even after flattening.  Ticket #3346.
97056   **
97057   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
97058   */
97059   if( ALWAYS(pSubitem->pTab!=0) ){
97060     Table *pTabToDel = pSubitem->pTab;
97061     if( pTabToDel->nRef==1 ){
97062       Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
97063       pTabToDel->pNextZombie = pToplevel->pZombieTab;
97064       pToplevel->pZombieTab = pTabToDel;
97065     }else{
97066       pTabToDel->nRef--;
97067     }
97068     pSubitem->pTab = 0;
97069   }
97070
97071   /* The following loop runs once for each term in a compound-subquery
97072   ** flattening (as described above).  If we are doing a different kind
97073   ** of flattening - a flattening other than a compound-subquery flattening -
97074   ** then this loop only runs once.
97075   **
97076   ** This loop moves all of the FROM elements of the subquery into the
97077   ** the FROM clause of the outer query.  Before doing this, remember
97078   ** the cursor number for the original outer query FROM element in
97079   ** iParent.  The iParent cursor will never be used.  Subsequent code
97080   ** will scan expressions looking for iParent references and replace
97081   ** those references with expressions that resolve to the subquery FROM
97082   ** elements we are now copying in.
97083   */
97084   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
97085     int nSubSrc;
97086     u8 jointype = 0;
97087     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
97088     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
97089     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
97090
97091     if( pSrc ){
97092       assert( pParent==p );  /* First time through the loop */
97093       jointype = pSubitem->jointype;
97094     }else{
97095       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
97096       pSrc = pParent->pSrc = sqlcipher3SrcListAppend(db, 0, 0, 0);
97097       if( pSrc==0 ){
97098         assert( db->mallocFailed );
97099         break;
97100       }
97101     }
97102
97103     /* The subquery uses a single slot of the FROM clause of the outer
97104     ** query.  If the subquery has more than one element in its FROM clause,
97105     ** then expand the outer query to make space for it to hold all elements
97106     ** of the subquery.
97107     **
97108     ** Example:
97109     **
97110     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
97111     **
97112     ** The outer query has 3 slots in its FROM clause.  One slot of the
97113     ** outer query (the middle slot) is used by the subquery.  The next
97114     ** block of code will expand the out query to 4 slots.  The middle
97115     ** slot is expanded to two slots in order to make space for the
97116     ** two elements in the FROM clause of the subquery.
97117     */
97118     if( nSubSrc>1 ){
97119       pParent->pSrc = pSrc = sqlcipher3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
97120       if( db->mallocFailed ){
97121         break;
97122       }
97123     }
97124
97125     /* Transfer the FROM clause terms from the subquery into the
97126     ** outer query.
97127     */
97128     for(i=0; i<nSubSrc; i++){
97129       sqlcipher3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
97130       pSrc->a[i+iFrom] = pSubSrc->a[i];
97131       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
97132     }
97133     pSrc->a[iFrom].jointype = jointype;
97134   
97135     /* Now begin substituting subquery result set expressions for 
97136     ** references to the iParent in the outer query.
97137     ** 
97138     ** Example:
97139     **
97140     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
97141     **   \                     \_____________ subquery __________/          /
97142     **    \_____________________ outer query ______________________________/
97143     **
97144     ** We look at every expression in the outer query and every place we see
97145     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
97146     */
97147     pList = pParent->pEList;
97148     for(i=0; i<pList->nExpr; i++){
97149       if( pList->a[i].zName==0 ){
97150         const char *zSpan = pList->a[i].zSpan;
97151         if( ALWAYS(zSpan) ){
97152           pList->a[i].zName = sqlcipher3DbStrDup(db, zSpan);
97153         }
97154       }
97155     }
97156     substExprList(db, pParent->pEList, iParent, pSub->pEList);
97157     if( isAgg ){
97158       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
97159       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97160     }
97161     if( pSub->pOrderBy ){
97162       assert( pParent->pOrderBy==0 );
97163       pParent->pOrderBy = pSub->pOrderBy;
97164       pSub->pOrderBy = 0;
97165     }else if( pParent->pOrderBy ){
97166       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
97167     }
97168     if( pSub->pWhere ){
97169       pWhere = sqlcipher3ExprDup(db, pSub->pWhere, 0);
97170     }else{
97171       pWhere = 0;
97172     }
97173     if( subqueryIsAgg ){
97174       assert( pParent->pHaving==0 );
97175       pParent->pHaving = pParent->pWhere;
97176       pParent->pWhere = pWhere;
97177       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97178       pParent->pHaving = sqlcipher3ExprAnd(db, pParent->pHaving, 
97179                                   sqlcipher3ExprDup(db, pSub->pHaving, 0));
97180       assert( pParent->pGroupBy==0 );
97181       pParent->pGroupBy = sqlcipher3ExprListDup(db, pSub->pGroupBy, 0);
97182     }else{
97183       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
97184       pParent->pWhere = sqlcipher3ExprAnd(db, pParent->pWhere, pWhere);
97185     }
97186   
97187     /* The flattened query is distinct if either the inner or the
97188     ** outer query is distinct. 
97189     */
97190     pParent->selFlags |= pSub->selFlags & SF_Distinct;
97191   
97192     /*
97193     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
97194     **
97195     ** One is tempted to try to add a and b to combine the limits.  But this
97196     ** does not work if either limit is negative.
97197     */
97198     if( pSub->pLimit ){
97199       pParent->pLimit = pSub->pLimit;
97200       pSub->pLimit = 0;
97201     }
97202   }
97203
97204   /* Finially, delete what is left of the subquery and return
97205   ** success.
97206   */
97207   sqlcipher3SelectDelete(db, pSub1);
97208
97209   return 1;
97210 }
97211 #endif /* !defined(SQLCIPHER_OMIT_SUBQUERY) || !defined(SQLCIPHER_OMIT_VIEW) */
97212
97213 /*
97214 ** Analyze the SELECT statement passed as an argument to see if it
97215 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
97216 ** it is, or 0 otherwise. At present, a query is considered to be
97217 ** a min()/max() query if:
97218 **
97219 **   1. There is a single object in the FROM clause.
97220 **
97221 **   2. There is a single expression in the result set, and it is
97222 **      either min(x) or max(x), where x is a column reference.
97223 */
97224 static u8 minMaxQuery(Select *p){
97225   Expr *pExpr;
97226   ExprList *pEList = p->pEList;
97227
97228   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
97229   pExpr = pEList->a[0].pExpr;
97230   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
97231   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
97232   pEList = pExpr->x.pList;
97233   if( pEList==0 || pEList->nExpr!=1 ) return 0;
97234   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
97235   assert( !ExprHasProperty(pExpr, EP_IntValue) );
97236   if( sqlcipher3StrICmp(pExpr->u.zToken,"min")==0 ){
97237     return WHERE_ORDERBY_MIN;
97238   }else if( sqlcipher3StrICmp(pExpr->u.zToken,"max")==0 ){
97239     return WHERE_ORDERBY_MAX;
97240   }
97241   return WHERE_ORDERBY_NORMAL;
97242 }
97243
97244 /*
97245 ** The select statement passed as the first argument is an aggregate query.
97246 ** The second argment is the associated aggregate-info object. This 
97247 ** function tests if the SELECT is of the form:
97248 **
97249 **   SELECT count(*) FROM <tbl>
97250 **
97251 ** where table is a database table, not a sub-select or view. If the query
97252 ** does match this pattern, then a pointer to the Table object representing
97253 ** <tbl> is returned. Otherwise, 0 is returned.
97254 */
97255 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
97256   Table *pTab;
97257   Expr *pExpr;
97258
97259   assert( !p->pGroupBy );
97260
97261   if( p->pWhere || p->pEList->nExpr!=1 
97262    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
97263   ){
97264     return 0;
97265   }
97266   pTab = p->pSrc->a[0].pTab;
97267   pExpr = p->pEList->a[0].pExpr;
97268   assert( pTab && !pTab->pSelect && pExpr );
97269
97270   if( IsVirtual(pTab) ) return 0;
97271   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
97272   if( (pAggInfo->aFunc[0].pFunc->flags&SQLCIPHER_FUNC_COUNT)==0 ) return 0;
97273   if( pExpr->flags&EP_Distinct ) return 0;
97274
97275   return pTab;
97276 }
97277
97278 /*
97279 ** If the source-list item passed as an argument was augmented with an
97280 ** INDEXED BY clause, then try to locate the specified index. If there
97281 ** was such a clause and the named index cannot be found, return 
97282 ** SQLCIPHER_ERROR and leave an error in pParse. Otherwise, populate 
97283 ** pFrom->pIndex and return SQLCIPHER_OK.
97284 */
97285 SQLCIPHER_PRIVATE int sqlcipher3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
97286   if( pFrom->pTab && pFrom->zIndex ){
97287     Table *pTab = pFrom->pTab;
97288     char *zIndex = pFrom->zIndex;
97289     Index *pIdx;
97290     for(pIdx=pTab->pIndex; 
97291         pIdx && sqlcipher3StrICmp(pIdx->zName, zIndex); 
97292         pIdx=pIdx->pNext
97293     );
97294     if( !pIdx ){
97295       sqlcipher3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
97296       pParse->checkSchema = 1;
97297       return SQLCIPHER_ERROR;
97298     }
97299     pFrom->pIndex = pIdx;
97300   }
97301   return SQLCIPHER_OK;
97302 }
97303
97304 /*
97305 ** This routine is a Walker callback for "expanding" a SELECT statement.
97306 ** "Expanding" means to do the following:
97307 **
97308 **    (1)  Make sure VDBE cursor numbers have been assigned to every
97309 **         element of the FROM clause.
97310 **
97311 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
97312 **         defines FROM clause.  When views appear in the FROM clause,
97313 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
97314 **         that implements the view.  A copy is made of the view's SELECT
97315 **         statement so that we can freely modify or delete that statement
97316 **         without worrying about messing up the presistent representation
97317 **         of the view.
97318 **
97319 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
97320 **         on joins and the ON and USING clause of joins.
97321 **
97322 **    (4)  Scan the list of columns in the result set (pEList) looking
97323 **         for instances of the "*" operator or the TABLE.* operator.
97324 **         If found, expand each "*" to be every column in every table
97325 **         and TABLE.* to be every column in TABLE.
97326 **
97327 */
97328 static int selectExpander(Walker *pWalker, Select *p){
97329   Parse *pParse = pWalker->pParse;
97330   int i, j, k;
97331   SrcList *pTabList;
97332   ExprList *pEList;
97333   struct SrcList_item *pFrom;
97334   sqlcipher3 *db = pParse->db;
97335
97336   if( db->mallocFailed  ){
97337     return WRC_Abort;
97338   }
97339   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
97340     return WRC_Prune;
97341   }
97342   p->selFlags |= SF_Expanded;
97343   pTabList = p->pSrc;
97344   pEList = p->pEList;
97345
97346   /* Make sure cursor numbers have been assigned to all entries in
97347   ** the FROM clause of the SELECT statement.
97348   */
97349   sqlcipher3SrcListAssignCursors(pParse, pTabList);
97350
97351   /* Look up every table named in the FROM clause of the select.  If
97352   ** an entry of the FROM clause is a subquery instead of a table or view,
97353   ** then create a transient table structure to describe the subquery.
97354   */
97355   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97356     Table *pTab;
97357     if( pFrom->pTab!=0 ){
97358       /* This statement has already been prepared.  There is no need
97359       ** to go further. */
97360       assert( i==0 );
97361       return WRC_Prune;
97362     }
97363     if( pFrom->zName==0 ){
97364 #ifndef SQLCIPHER_OMIT_SUBQUERY
97365       Select *pSel = pFrom->pSelect;
97366       /* A sub-query in the FROM clause of a SELECT */
97367       assert( pSel!=0 );
97368       assert( pFrom->pTab==0 );
97369       sqlcipher3WalkSelect(pWalker, pSel);
97370       pFrom->pTab = pTab = sqlcipher3DbMallocZero(db, sizeof(Table));
97371       if( pTab==0 ) return WRC_Abort;
97372       pTab->nRef = 1;
97373       pTab->zName = sqlcipher3MPrintf(db, "sqlcipher_subquery_%p_", (void*)pTab);
97374       while( pSel->pPrior ){ pSel = pSel->pPrior; }
97375       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
97376       pTab->iPKey = -1;
97377       pTab->nRowEst = 1000000;
97378       pTab->tabFlags |= TF_Ephemeral;
97379 #endif
97380     }else{
97381       /* An ordinary table or view name in the FROM clause */
97382       assert( pFrom->pTab==0 );
97383       pFrom->pTab = pTab = 
97384         sqlcipher3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
97385       if( pTab==0 ) return WRC_Abort;
97386       pTab->nRef++;
97387 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined (SQLCIPHER_OMIT_VIRTUALTABLE)
97388       if( pTab->pSelect || IsVirtual(pTab) ){
97389         /* We reach here if the named table is a really a view */
97390         if( sqlcipher3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
97391         assert( pFrom->pSelect==0 );
97392         pFrom->pSelect = sqlcipher3SelectDup(db, pTab->pSelect, 0);
97393         sqlcipher3WalkSelect(pWalker, pFrom->pSelect);
97394       }
97395 #endif
97396     }
97397
97398     /* Locate the index named by the INDEXED BY clause, if any. */
97399     if( sqlcipher3IndexedByLookup(pParse, pFrom) ){
97400       return WRC_Abort;
97401     }
97402   }
97403
97404   /* Process NATURAL keywords, and ON and USING clauses of joins.
97405   */
97406   if( db->mallocFailed || sqlcipherProcessJoin(pParse, p) ){
97407     return WRC_Abort;
97408   }
97409
97410   /* For every "*" that occurs in the column list, insert the names of
97411   ** all columns in all tables.  And for every TABLE.* insert the names
97412   ** of all columns in TABLE.  The parser inserted a special expression
97413   ** with the TK_ALL operator for each "*" that it found in the column list.
97414   ** The following code just has to locate the TK_ALL expressions and expand
97415   ** each one to the list of all columns in all tables.
97416   **
97417   ** The first loop just checks to see if there are any "*" operators
97418   ** that need expanding.
97419   */
97420   for(k=0; k<pEList->nExpr; k++){
97421     Expr *pE = pEList->a[k].pExpr;
97422     if( pE->op==TK_ALL ) break;
97423     assert( pE->op!=TK_DOT || pE->pRight!=0 );
97424     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
97425     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
97426   }
97427   if( k<pEList->nExpr ){
97428     /*
97429     ** If we get here it means the result set contains one or more "*"
97430     ** operators that need to be expanded.  Loop through each expression
97431     ** in the result set and expand them one by one.
97432     */
97433     struct ExprList_item *a = pEList->a;
97434     ExprList *pNew = 0;
97435     int flags = pParse->db->flags;
97436     int longNames = (flags & SQLCIPHER_FullColNames)!=0
97437                       && (flags & SQLCIPHER_ShortColNames)==0;
97438
97439     for(k=0; k<pEList->nExpr; k++){
97440       Expr *pE = a[k].pExpr;
97441       assert( pE->op!=TK_DOT || pE->pRight!=0 );
97442       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
97443         /* This particular expression does not need to be expanded.
97444         */
97445         pNew = sqlcipher3ExprListAppend(pParse, pNew, a[k].pExpr);
97446         if( pNew ){
97447           pNew->a[pNew->nExpr-1].zName = a[k].zName;
97448           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
97449           a[k].zName = 0;
97450           a[k].zSpan = 0;
97451         }
97452         a[k].pExpr = 0;
97453       }else{
97454         /* This expression is a "*" or a "TABLE.*" and needs to be
97455         ** expanded. */
97456         int tableSeen = 0;      /* Set to 1 when TABLE matches */
97457         char *zTName;            /* text of name of TABLE */
97458         if( pE->op==TK_DOT ){
97459           assert( pE->pLeft!=0 );
97460           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
97461           zTName = pE->pLeft->u.zToken;
97462         }else{
97463           zTName = 0;
97464         }
97465         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97466           Table *pTab = pFrom->pTab;
97467           char *zTabName = pFrom->zAlias;
97468           if( zTabName==0 ){
97469             zTabName = pTab->zName;
97470           }
97471           if( db->mallocFailed ) break;
97472           if( zTName && sqlcipher3StrICmp(zTName, zTabName)!=0 ){
97473             continue;
97474           }
97475           tableSeen = 1;
97476           for(j=0; j<pTab->nCol; j++){
97477             Expr *pExpr, *pRight;
97478             char *zName = pTab->aCol[j].zName;
97479             char *zColname;  /* The computed column name */
97480             char *zToFree;   /* Malloced string that needs to be freed */
97481             Token sColname;  /* Computed column name as a token */
97482
97483             /* If a column is marked as 'hidden' (currently only possible
97484             ** for virtual tables), do not include it in the expanded
97485             ** result-set list.
97486             */
97487             if( IsHiddenColumn(&pTab->aCol[j]) ){
97488               assert(IsVirtual(pTab));
97489               continue;
97490             }
97491
97492             if( i>0 && zTName==0 ){
97493               if( (pFrom->jointype & JT_NATURAL)!=0
97494                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
97495               ){
97496                 /* In a NATURAL join, omit the join columns from the 
97497                 ** table to the right of the join */
97498                 continue;
97499               }
97500               if( sqlcipher3IdListIndex(pFrom->pUsing, zName)>=0 ){
97501                 /* In a join with a USING clause, omit columns in the
97502                 ** using clause from the table on the right. */
97503                 continue;
97504               }
97505             }
97506             pRight = sqlcipher3Expr(db, TK_ID, zName);
97507             zColname = zName;
97508             zToFree = 0;
97509             if( longNames || pTabList->nSrc>1 ){
97510               Expr *pLeft;
97511               pLeft = sqlcipher3Expr(db, TK_ID, zTabName);
97512               pExpr = sqlcipher3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
97513               if( longNames ){
97514                 zColname = sqlcipher3MPrintf(db, "%s.%s", zTabName, zName);
97515                 zToFree = zColname;
97516               }
97517             }else{
97518               pExpr = pRight;
97519             }
97520             pNew = sqlcipher3ExprListAppend(pParse, pNew, pExpr);
97521             sColname.z = zColname;
97522             sColname.n = sqlcipher3Strlen30(zColname);
97523             sqlcipher3ExprListSetName(pParse, pNew, &sColname, 0);
97524             sqlcipher3DbFree(db, zToFree);
97525           }
97526         }
97527         if( !tableSeen ){
97528           if( zTName ){
97529             sqlcipher3ErrorMsg(pParse, "no such table: %s", zTName);
97530           }else{
97531             sqlcipher3ErrorMsg(pParse, "no tables specified");
97532           }
97533         }
97534       }
97535     }
97536     sqlcipher3ExprListDelete(db, pEList);
97537     p->pEList = pNew;
97538   }
97539 #if SQLCIPHER_MAX_COLUMN
97540   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLCIPHER_LIMIT_COLUMN] ){
97541     sqlcipher3ErrorMsg(pParse, "too many columns in result set");
97542   }
97543 #endif
97544   return WRC_Continue;
97545 }
97546
97547 /*
97548 ** No-op routine for the parse-tree walker.
97549 **
97550 ** When this routine is the Walker.xExprCallback then expression trees
97551 ** are walked without any actions being taken at each node.  Presumably,
97552 ** when this routine is used for Walker.xExprCallback then 
97553 ** Walker.xSelectCallback is set to do something useful for every 
97554 ** subquery in the parser tree.
97555 */
97556 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
97557   UNUSED_PARAMETER2(NotUsed, NotUsed2);
97558   return WRC_Continue;
97559 }
97560
97561 /*
97562 ** This routine "expands" a SELECT statement and all of its subqueries.
97563 ** For additional information on what it means to "expand" a SELECT
97564 ** statement, see the comment on the selectExpand worker callback above.
97565 **
97566 ** Expanding a SELECT statement is the first step in processing a
97567 ** SELECT statement.  The SELECT statement must be expanded before
97568 ** name resolution is performed.
97569 **
97570 ** If anything goes wrong, an error message is written into pParse.
97571 ** The calling function can detect the problem by looking at pParse->nErr
97572 ** and/or pParse->db->mallocFailed.
97573 */
97574 static void sqlcipher3SelectExpand(Parse *pParse, Select *pSelect){
97575   Walker w;
97576   w.xSelectCallback = selectExpander;
97577   w.xExprCallback = exprWalkNoop;
97578   w.pParse = pParse;
97579   sqlcipher3WalkSelect(&w, pSelect);
97580 }
97581
97582
97583 #ifndef SQLCIPHER_OMIT_SUBQUERY
97584 /*
97585 ** This is a Walker.xSelectCallback callback for the sqlcipher3SelectTypeInfo()
97586 ** interface.
97587 **
97588 ** For each FROM-clause subquery, add Column.zType and Column.zColl
97589 ** information to the Table structure that represents the result set
97590 ** of that subquery.
97591 **
97592 ** The Table structure that represents the result set was constructed
97593 ** by selectExpander() but the type and collation information was omitted
97594 ** at that point because identifiers had not yet been resolved.  This
97595 ** routine is called after identifier resolution.
97596 */
97597 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
97598   Parse *pParse;
97599   int i;
97600   SrcList *pTabList;
97601   struct SrcList_item *pFrom;
97602
97603   assert( p->selFlags & SF_Resolved );
97604   if( (p->selFlags & SF_HasTypeInfo)==0 ){
97605     p->selFlags |= SF_HasTypeInfo;
97606     pParse = pWalker->pParse;
97607     pTabList = p->pSrc;
97608     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97609       Table *pTab = pFrom->pTab;
97610       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
97611         /* A sub-query in the FROM clause of a SELECT */
97612         Select *pSel = pFrom->pSelect;
97613         assert( pSel );
97614         while( pSel->pPrior ) pSel = pSel->pPrior;
97615         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
97616       }
97617     }
97618   }
97619   return WRC_Continue;
97620 }
97621 #endif
97622
97623
97624 /*
97625 ** This routine adds datatype and collating sequence information to
97626 ** the Table structures of all FROM-clause subqueries in a
97627 ** SELECT statement.
97628 **
97629 ** Use this routine after name resolution.
97630 */
97631 static void sqlcipher3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
97632 #ifndef SQLCIPHER_OMIT_SUBQUERY
97633   Walker w;
97634   w.xSelectCallback = selectAddSubqueryTypeInfo;
97635   w.xExprCallback = exprWalkNoop;
97636   w.pParse = pParse;
97637   sqlcipher3WalkSelect(&w, pSelect);
97638 #endif
97639 }
97640
97641
97642 /*
97643 ** This routine sets of a SELECT statement for processing.  The
97644 ** following is accomplished:
97645 **
97646 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
97647 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
97648 **     *  ON and USING clauses are shifted into WHERE statements
97649 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
97650 **     *  Identifiers in expression are matched to tables.
97651 **
97652 ** This routine acts recursively on all subqueries within the SELECT.
97653 */
97654 SQLCIPHER_PRIVATE void sqlcipher3SelectPrep(
97655   Parse *pParse,         /* The parser context */
97656   Select *p,             /* The SELECT statement being coded. */
97657   NameContext *pOuterNC  /* Name context for container */
97658 ){
97659   sqlcipher3 *db;
97660   if( NEVER(p==0) ) return;
97661   db = pParse->db;
97662   if( p->selFlags & SF_HasTypeInfo ) return;
97663   sqlcipher3SelectExpand(pParse, p);
97664   if( pParse->nErr || db->mallocFailed ) return;
97665   sqlcipher3ResolveSelectNames(pParse, p, pOuterNC);
97666   if( pParse->nErr || db->mallocFailed ) return;
97667   sqlcipher3SelectAddTypeInfo(pParse, p);
97668 }
97669
97670 /*
97671 ** Reset the aggregate accumulator.
97672 **
97673 ** The aggregate accumulator is a set of memory cells that hold
97674 ** intermediate results while calculating an aggregate.  This
97675 ** routine simply stores NULLs in all of those memory cells.
97676 */
97677 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
97678   Vdbe *v = pParse->pVdbe;
97679   int i;
97680   struct AggInfo_func *pFunc;
97681   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
97682     return;
97683   }
97684   for(i=0; i<pAggInfo->nColumn; i++){
97685     sqlcipher3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
97686   }
97687   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
97688     sqlcipher3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
97689     if( pFunc->iDistinct>=0 ){
97690       Expr *pE = pFunc->pExpr;
97691       assert( !ExprHasProperty(pE, EP_xIsSelect) );
97692       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
97693         sqlcipher3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
97694            "argument");
97695         pFunc->iDistinct = -1;
97696       }else{
97697         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
97698         sqlcipher3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
97699                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
97700       }
97701     }
97702   }
97703 }
97704
97705 /*
97706 ** Invoke the OP_AggFinalize opcode for every aggregate function
97707 ** in the AggInfo structure.
97708 */
97709 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
97710   Vdbe *v = pParse->pVdbe;
97711   int i;
97712   struct AggInfo_func *pF;
97713   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
97714     ExprList *pList = pF->pExpr->x.pList;
97715     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
97716     sqlcipher3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
97717                       (void*)pF->pFunc, P4_FUNCDEF);
97718   }
97719 }
97720
97721 /*
97722 ** Update the accumulator memory cells for an aggregate based on
97723 ** the current cursor position.
97724 */
97725 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
97726   Vdbe *v = pParse->pVdbe;
97727   int i;
97728   struct AggInfo_func *pF;
97729   struct AggInfo_col *pC;
97730
97731   pAggInfo->directMode = 1;
97732   sqlcipher3ExprCacheClear(pParse);
97733   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
97734     int nArg;
97735     int addrNext = 0;
97736     int regAgg;
97737     ExprList *pList = pF->pExpr->x.pList;
97738     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
97739     if( pList ){
97740       nArg = pList->nExpr;
97741       regAgg = sqlcipher3GetTempRange(pParse, nArg);
97742       sqlcipher3ExprCodeExprList(pParse, pList, regAgg, 1);
97743     }else{
97744       nArg = 0;
97745       regAgg = 0;
97746     }
97747     if( pF->iDistinct>=0 ){
97748       addrNext = sqlcipher3VdbeMakeLabel(v);
97749       assert( nArg==1 );
97750       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
97751     }
97752     if( pF->pFunc->flags & SQLCIPHER_FUNC_NEEDCOLL ){
97753       CollSeq *pColl = 0;
97754       struct ExprList_item *pItem;
97755       int j;
97756       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
97757       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
97758         pColl = sqlcipher3ExprCollSeq(pParse, pItem->pExpr);
97759       }
97760       if( !pColl ){
97761         pColl = pParse->db->pDfltColl;
97762       }
97763       sqlcipher3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
97764     }
97765     sqlcipher3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
97766                       (void*)pF->pFunc, P4_FUNCDEF);
97767     sqlcipher3VdbeChangeP5(v, (u8)nArg);
97768     sqlcipher3ExprCacheAffinityChange(pParse, regAgg, nArg);
97769     sqlcipher3ReleaseTempRange(pParse, regAgg, nArg);
97770     if( addrNext ){
97771       sqlcipher3VdbeResolveLabel(v, addrNext);
97772       sqlcipher3ExprCacheClear(pParse);
97773     }
97774   }
97775
97776   /* Before populating the accumulator registers, clear the column cache.
97777   ** Otherwise, if any of the required column values are already present 
97778   ** in registers, sqlcipher3ExprCode() may use OP_SCopy to copy the value
97779   ** to pC->iMem. But by the time the value is used, the original register
97780   ** may have been used, invalidating the underlying buffer holding the
97781   ** text or blob value. See ticket [883034dcb5].
97782   **
97783   ** Another solution would be to change the OP_SCopy used to copy cached
97784   ** values to an OP_Copy.
97785   */
97786   sqlcipher3ExprCacheClear(pParse);
97787   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
97788     sqlcipher3ExprCode(pParse, pC->pExpr, pC->iMem);
97789   }
97790   pAggInfo->directMode = 0;
97791   sqlcipher3ExprCacheClear(pParse);
97792 }
97793
97794 /*
97795 ** Add a single OP_Explain instruction to the VDBE to explain a simple
97796 ** count(*) query ("SELECT count(*) FROM pTab").
97797 */
97798 #ifndef SQLCIPHER_OMIT_EXPLAIN
97799 static void explainSimpleCount(
97800   Parse *pParse,                  /* Parse context */
97801   Table *pTab,                    /* Table being queried */
97802   Index *pIdx                     /* Index used to optimize scan, or NULL */
97803 ){
97804   if( pParse->explain==2 ){
97805     char *zEqp = sqlcipher3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
97806         pTab->zName, 
97807         pIdx ? "USING COVERING INDEX " : "",
97808         pIdx ? pIdx->zName : "",
97809         pTab->nRowEst
97810     );
97811     sqlcipher3VdbeAddOp4(
97812         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
97813     );
97814   }
97815 }
97816 #else
97817 # define explainSimpleCount(a,b,c)
97818 #endif
97819
97820 /*
97821 ** Generate code for the SELECT statement given in the p argument.  
97822 **
97823 ** The results are distributed in various ways depending on the
97824 ** contents of the SelectDest structure pointed to by argument pDest
97825 ** as follows:
97826 **
97827 **     pDest->eDest    Result
97828 **     ------------    -------------------------------------------
97829 **     SRT_Output      Generate a row of output (using the OP_ResultRow
97830 **                     opcode) for each row in the result set.
97831 **
97832 **     SRT_Mem         Only valid if the result is a single column.
97833 **                     Store the first column of the first result row
97834 **                     in register pDest->iParm then abandon the rest
97835 **                     of the query.  This destination implies "LIMIT 1".
97836 **
97837 **     SRT_Set         The result must be a single column.  Store each
97838 **                     row of result as the key in table pDest->iParm. 
97839 **                     Apply the affinity pDest->affinity before storing
97840 **                     results.  Used to implement "IN (SELECT ...)".
97841 **
97842 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
97843 **
97844 **     SRT_Except      Remove results from the temporary table pDest->iParm.
97845 **
97846 **     SRT_Table       Store results in temporary table pDest->iParm.
97847 **                     This is like SRT_EphemTab except that the table
97848 **                     is assumed to already be open.
97849 **
97850 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
97851 **                     the result there. The cursor is left open after
97852 **                     returning.  This is like SRT_Table except that
97853 **                     this destination uses OP_OpenEphemeral to create
97854 **                     the table first.
97855 **
97856 **     SRT_Coroutine   Generate a co-routine that returns a new row of
97857 **                     results each time it is invoked.  The entry point
97858 **                     of the co-routine is stored in register pDest->iParm.
97859 **
97860 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
97861 **                     set is not empty.
97862 **
97863 **     SRT_Discard     Throw the results away.  This is used by SELECT
97864 **                     statements within triggers whose only purpose is
97865 **                     the side-effects of functions.
97866 **
97867 ** This routine returns the number of errors.  If any errors are
97868 ** encountered, then an appropriate error message is left in
97869 ** pParse->zErrMsg.
97870 **
97871 ** This routine does NOT free the Select structure passed in.  The
97872 ** calling function needs to do that.
97873 */
97874 SQLCIPHER_PRIVATE int sqlcipher3Select(
97875   Parse *pParse,         /* The parser context */
97876   Select *p,             /* The SELECT statement being coded. */
97877   SelectDest *pDest      /* What to do with the query results */
97878 ){
97879   int i, j;              /* Loop counters */
97880   WhereInfo *pWInfo;     /* Return from sqlcipher3WhereBegin() */
97881   Vdbe *v;               /* The virtual machine under construction */
97882   int isAgg;             /* True for select lists like "count(*)" */
97883   ExprList *pEList;      /* List of columns to extract. */
97884   SrcList *pTabList;     /* List of tables to select from */
97885   Expr *pWhere;          /* The WHERE clause.  May be NULL */
97886   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
97887   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
97888   Expr *pHaving;         /* The HAVING clause.  May be NULL */
97889   int isDistinct;        /* True if the DISTINCT keyword is present */
97890   int distinct;          /* Table to use for the distinct set */
97891   int rc = 1;            /* Value to return from this function */
97892   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
97893   int addrDistinctIndex; /* Address of an OP_OpenEphemeral instruction */
97894   AggInfo sAggInfo;      /* Information used by aggregate queries */
97895   int iEnd;              /* Address of the end of the query */
97896   sqlcipher3 *db;           /* The database connection */
97897
97898 #ifndef SQLCIPHER_OMIT_EXPLAIN
97899   int iRestoreSelectId = pParse->iSelectId;
97900   pParse->iSelectId = pParse->iNextSelectId++;
97901 #endif
97902
97903   db = pParse->db;
97904   if( p==0 || db->mallocFailed || pParse->nErr ){
97905     return 1;
97906   }
97907   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_SELECT, 0, 0, 0) ) return 1;
97908   memset(&sAggInfo, 0, sizeof(sAggInfo));
97909
97910   if( IgnorableOrderby(pDest) ){
97911     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
97912            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
97913     /* If ORDER BY makes no difference in the output then neither does
97914     ** DISTINCT so it can be removed too. */
97915     sqlcipher3ExprListDelete(db, p->pOrderBy);
97916     p->pOrderBy = 0;
97917     p->selFlags &= ~SF_Distinct;
97918   }
97919   sqlcipher3SelectPrep(pParse, p, 0);
97920   pOrderBy = p->pOrderBy;
97921   pTabList = p->pSrc;
97922   pEList = p->pEList;
97923   if( pParse->nErr || db->mallocFailed ){
97924     goto select_end;
97925   }
97926   isAgg = (p->selFlags & SF_Aggregate)!=0;
97927   assert( pEList!=0 );
97928
97929   /* Begin generating code.
97930   */
97931   v = sqlcipher3GetVdbe(pParse);
97932   if( v==0 ) goto select_end;
97933
97934   /* If writing to memory or generating a set
97935   ** only a single column may be output.
97936   */
97937 #ifndef SQLCIPHER_OMIT_SUBQUERY
97938   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
97939     goto select_end;
97940   }
97941 #endif
97942
97943   /* Generate code for all sub-queries in the FROM clause
97944   */
97945 #if !defined(SQLCIPHER_OMIT_SUBQUERY) || !defined(SQLCIPHER_OMIT_VIEW)
97946   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
97947     struct SrcList_item *pItem = &pTabList->a[i];
97948     SelectDest dest;
97949     Select *pSub = pItem->pSelect;
97950     int isAggSub;
97951
97952     if( pSub==0 ) continue;
97953     if( pItem->addrFillSub ){
97954       sqlcipher3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
97955       continue;
97956     }
97957
97958     /* Increment Parse.nHeight by the height of the largest expression
97959     ** tree refered to by this, the parent select. The child select
97960     ** may contain expression trees of at most
97961     ** (SQLCIPHER_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
97962     ** more conservative than necessary, but much easier than enforcing
97963     ** an exact limit.
97964     */
97965     pParse->nHeight += sqlcipher3SelectExprHeight(p);
97966
97967     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
97968     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
97969       /* This subquery can be absorbed into its parent. */
97970       if( isAggSub ){
97971         isAgg = 1;
97972         p->selFlags |= SF_Aggregate;
97973       }
97974       i = -1;
97975     }else{
97976       /* Generate a subroutine that will fill an ephemeral table with
97977       ** the content of this subquery.  pItem->addrFillSub will point
97978       ** to the address of the generated subroutine.  pItem->regReturn
97979       ** is a register allocated to hold the subroutine return address
97980       */
97981       int topAddr;
97982       int onceAddr = 0;
97983       int retAddr;
97984       assert( pItem->addrFillSub==0 );
97985       pItem->regReturn = ++pParse->nMem;
97986       topAddr = sqlcipher3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
97987       pItem->addrFillSub = topAddr+1;
97988       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
97989       if( pItem->isCorrelated==0 && pParse->pTriggerTab==0 ){
97990         /* If the subquery is no correlated and if we are not inside of
97991         ** a trigger, then we only need to compute the value of the subquery
97992         ** once. */
97993         int regOnce = ++pParse->nMem;
97994         onceAddr = sqlcipher3VdbeAddOp1(v, OP_Once, regOnce);
97995       }
97996       sqlcipher3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
97997       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
97998       sqlcipher3Select(pParse, pSub, &dest);
97999       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
98000       if( onceAddr ) sqlcipher3VdbeJumpHere(v, onceAddr);
98001       retAddr = sqlcipher3VdbeAddOp1(v, OP_Return, pItem->regReturn);
98002       VdbeComment((v, "end %s", pItem->pTab->zName));
98003       sqlcipher3VdbeChangeP1(v, topAddr, retAddr);
98004
98005     }
98006     if( /*pParse->nErr ||*/ db->mallocFailed ){
98007       goto select_end;
98008     }
98009     pParse->nHeight -= sqlcipher3SelectExprHeight(p);
98010     pTabList = p->pSrc;
98011     if( !IgnorableOrderby(pDest) ){
98012       pOrderBy = p->pOrderBy;
98013     }
98014   }
98015   pEList = p->pEList;
98016 #endif
98017   pWhere = p->pWhere;
98018   pGroupBy = p->pGroupBy;
98019   pHaving = p->pHaving;
98020   isDistinct = (p->selFlags & SF_Distinct)!=0;
98021
98022 #ifndef SQLCIPHER_OMIT_COMPOUND_SELECT
98023   /* If there is are a sequence of queries, do the earlier ones first.
98024   */
98025   if( p->pPrior ){
98026     if( p->pRightmost==0 ){
98027       Select *pLoop, *pRight = 0;
98028       int cnt = 0;
98029       int mxSelect;
98030       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
98031         pLoop->pRightmost = p;
98032         pLoop->pNext = pRight;
98033         pRight = pLoop;
98034       }
98035       mxSelect = db->aLimit[SQLCIPHER_LIMIT_COMPOUND_SELECT];
98036       if( mxSelect && cnt>mxSelect ){
98037         sqlcipher3ErrorMsg(pParse, "too many terms in compound SELECT");
98038         goto select_end;
98039       }
98040     }
98041     rc = multiSelect(pParse, p, pDest);
98042     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
98043     return rc;
98044   }
98045 #endif
98046
98047   /* If there is both a GROUP BY and an ORDER BY clause and they are
98048   ** identical, then disable the ORDER BY clause since the GROUP BY
98049   ** will cause elements to come out in the correct order.  This is
98050   ** an optimization - the correct answer should result regardless.
98051   ** Use the SQLCIPHER_GroupByOrder flag with SQLCIPHER_TESTCTRL_OPTIMIZER
98052   ** to disable this optimization for testing purposes.
98053   */
98054   if( sqlcipher3ExprListCompare(p->pGroupBy, pOrderBy)==0
98055          && (db->flags & SQLCIPHER_GroupByOrder)==0 ){
98056     pOrderBy = 0;
98057   }
98058
98059   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
98060   ** if the select-list is the same as the ORDER BY list, then this query
98061   ** can be rewritten as a GROUP BY. In other words, this:
98062   **
98063   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
98064   **
98065   ** is transformed to:
98066   **
98067   **     SELECT xyz FROM ... GROUP BY xyz
98068   **
98069   ** The second form is preferred as a single index (or temp-table) may be 
98070   ** used for both the ORDER BY and DISTINCT processing. As originally 
98071   ** written the query must use a temp-table for at least one of the ORDER 
98072   ** BY and DISTINCT, and an index or separate temp-table for the other.
98073   */
98074   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
98075    && sqlcipher3ExprListCompare(pOrderBy, p->pEList)==0
98076   ){
98077     p->selFlags &= ~SF_Distinct;
98078     p->pGroupBy = sqlcipher3ExprListDup(db, p->pEList, 0);
98079     pGroupBy = p->pGroupBy;
98080     pOrderBy = 0;
98081   }
98082
98083   /* If there is an ORDER BY clause, then this sorting
98084   ** index might end up being unused if the data can be 
98085   ** extracted in pre-sorted order.  If that is the case, then the
98086   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
98087   ** we figure out that the sorting index is not needed.  The addrSortIndex
98088   ** variable is used to facilitate that change.
98089   */
98090   if( pOrderBy ){
98091     KeyInfo *pKeyInfo;
98092     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
98093     pOrderBy->iECursor = pParse->nTab++;
98094     p->addrOpenEphm[2] = addrSortIndex =
98095       sqlcipher3VdbeAddOp4(v, OP_OpenEphemeral,
98096                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
98097                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98098   }else{
98099     addrSortIndex = -1;
98100   }
98101
98102   /* If the output is destined for a temporary table, open that table.
98103   */
98104   if( pDest->eDest==SRT_EphemTab ){
98105     sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
98106   }
98107
98108   /* Set the limiter.
98109   */
98110   iEnd = sqlcipher3VdbeMakeLabel(v);
98111   p->nSelectRow = (double)LARGEST_INT64;
98112   computeLimitRegisters(pParse, p, iEnd);
98113   if( p->iLimit==0 && addrSortIndex>=0 ){
98114     sqlcipher3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
98115     p->selFlags |= SF_UseSorter;
98116   }
98117
98118   /* Open a virtual index to use for the distinct set.
98119   */
98120   if( p->selFlags & SF_Distinct ){
98121     KeyInfo *pKeyInfo;
98122     distinct = pParse->nTab++;
98123     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
98124     addrDistinctIndex = sqlcipher3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
98125         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98126     sqlcipher3VdbeChangeP5(v, BTREE_UNORDERED);
98127   }else{
98128     distinct = addrDistinctIndex = -1;
98129   }
98130
98131   /* Aggregate and non-aggregate queries are handled differently */
98132   if( !isAgg && pGroupBy==0 ){
98133     ExprList *pDist = (isDistinct ? p->pEList : 0);
98134
98135     /* Begin the database scan. */
98136     pWInfo = sqlcipher3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, pDist, 0);
98137     if( pWInfo==0 ) goto select_end;
98138     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
98139
98140     /* If sorting index that was created by a prior OP_OpenEphemeral 
98141     ** instruction ended up not being needed, then change the OP_OpenEphemeral
98142     ** into an OP_Noop.
98143     */
98144     if( addrSortIndex>=0 && pOrderBy==0 ){
98145       sqlcipher3VdbeChangeToNoop(v, addrSortIndex);
98146       p->addrOpenEphm[2] = -1;
98147     }
98148
98149     if( pWInfo->eDistinct ){
98150       VdbeOp *pOp;                /* No longer required OpenEphemeral instr. */
98151      
98152       assert( addrDistinctIndex>=0 );
98153       pOp = sqlcipher3VdbeGetOp(v, addrDistinctIndex);
98154
98155       assert( isDistinct );
98156       assert( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED 
98157            || pWInfo->eDistinct==WHERE_DISTINCT_UNIQUE 
98158       );
98159       distinct = -1;
98160       if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED ){
98161         int iJump;
98162         int iExpr;
98163         int iFlag = ++pParse->nMem;
98164         int iBase = pParse->nMem+1;
98165         int iBase2 = iBase + pEList->nExpr;
98166         pParse->nMem += (pEList->nExpr*2);
98167
98168         /* Change the OP_OpenEphemeral coded earlier to an OP_Integer. The
98169         ** OP_Integer initializes the "first row" flag.  */
98170         pOp->opcode = OP_Integer;
98171         pOp->p1 = 1;
98172         pOp->p2 = iFlag;
98173
98174         sqlcipher3ExprCodeExprList(pParse, pEList, iBase, 1);
98175         iJump = sqlcipher3VdbeCurrentAddr(v) + 1 + pEList->nExpr + 1 + 1;
98176         sqlcipher3VdbeAddOp2(v, OP_If, iFlag, iJump-1);
98177         for(iExpr=0; iExpr<pEList->nExpr; iExpr++){
98178           CollSeq *pColl = sqlcipher3ExprCollSeq(pParse, pEList->a[iExpr].pExpr);
98179           sqlcipher3VdbeAddOp3(v, OP_Ne, iBase+iExpr, iJump, iBase2+iExpr);
98180           sqlcipher3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
98181           sqlcipher3VdbeChangeP5(v, SQLCIPHER_NULLEQ);
98182         }
98183         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iContinue);
98184
98185         sqlcipher3VdbeAddOp2(v, OP_Integer, 0, iFlag);
98186         assert( sqlcipher3VdbeCurrentAddr(v)==iJump );
98187         sqlcipher3VdbeAddOp3(v, OP_Move, iBase, iBase2, pEList->nExpr);
98188       }else{
98189         pOp->opcode = OP_Noop;
98190       }
98191     }
98192
98193     /* Use the standard inner loop. */
98194     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, pDest,
98195                     pWInfo->iContinue, pWInfo->iBreak);
98196
98197     /* End the database scan loop.
98198     */
98199     sqlcipher3WhereEnd(pWInfo);
98200   }else{
98201     /* This is the processing for aggregate queries */
98202     NameContext sNC;    /* Name context for processing aggregate information */
98203     int iAMem;          /* First Mem address for storing current GROUP BY */
98204     int iBMem;          /* First Mem address for previous GROUP BY */
98205     int iUseFlag;       /* Mem address holding flag indicating that at least
98206                         ** one row of the input to the aggregator has been
98207                         ** processed */
98208     int iAbortFlag;     /* Mem address which causes query abort if positive */
98209     int groupBySort;    /* Rows come from source in GROUP BY order */
98210     int addrEnd;        /* End of processing for this SELECT */
98211     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
98212     int sortOut = 0;    /* Output register from the sorter */
98213
98214     /* Remove any and all aliases between the result set and the
98215     ** GROUP BY clause.
98216     */
98217     if( pGroupBy ){
98218       int k;                        /* Loop counter */
98219       struct ExprList_item *pItem;  /* For looping over expression in a list */
98220
98221       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
98222         pItem->iAlias = 0;
98223       }
98224       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
98225         pItem->iAlias = 0;
98226       }
98227       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
98228     }else{
98229       p->nSelectRow = (double)1;
98230     }
98231
98232  
98233     /* Create a label to jump to when we want to abort the query */
98234     addrEnd = sqlcipher3VdbeMakeLabel(v);
98235
98236     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
98237     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
98238     ** SELECT statement.
98239     */
98240     memset(&sNC, 0, sizeof(sNC));
98241     sNC.pParse = pParse;
98242     sNC.pSrcList = pTabList;
98243     sNC.pAggInfo = &sAggInfo;
98244     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
98245     sAggInfo.pGroupBy = pGroupBy;
98246     sqlcipher3ExprAnalyzeAggList(&sNC, pEList);
98247     sqlcipher3ExprAnalyzeAggList(&sNC, pOrderBy);
98248     if( pHaving ){
98249       sqlcipher3ExprAnalyzeAggregates(&sNC, pHaving);
98250     }
98251     sAggInfo.nAccumulator = sAggInfo.nColumn;
98252     for(i=0; i<sAggInfo.nFunc; i++){
98253       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
98254       sqlcipher3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
98255     }
98256     if( db->mallocFailed ) goto select_end;
98257
98258     /* Processing for aggregates with GROUP BY is very different and
98259     ** much more complex than aggregates without a GROUP BY.
98260     */
98261     if( pGroupBy ){
98262       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
98263       int j1;             /* A-vs-B comparision jump */
98264       int addrOutputRow;  /* Start of subroutine that outputs a result row */
98265       int regOutputRow;   /* Return address register for output subroutine */
98266       int addrSetAbort;   /* Set the abort flag and return */
98267       int addrTopOfLoop;  /* Top of the input loop */
98268       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
98269       int addrReset;      /* Subroutine for resetting the accumulator */
98270       int regReset;       /* Return address register for reset subroutine */
98271
98272       /* If there is a GROUP BY clause we might need a sorting index to
98273       ** implement it.  Allocate that sorting index now.  If it turns out
98274       ** that we do not need it after all, the OP_SorterOpen instruction
98275       ** will be converted into a Noop.  
98276       */
98277       sAggInfo.sortingIdx = pParse->nTab++;
98278       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
98279       addrSortingIdx = sqlcipher3VdbeAddOp4(v, OP_SorterOpen, 
98280           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
98281           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98282
98283       /* Initialize memory locations used by GROUP BY aggregate processing
98284       */
98285       iUseFlag = ++pParse->nMem;
98286       iAbortFlag = ++pParse->nMem;
98287       regOutputRow = ++pParse->nMem;
98288       addrOutputRow = sqlcipher3VdbeMakeLabel(v);
98289       regReset = ++pParse->nMem;
98290       addrReset = sqlcipher3VdbeMakeLabel(v);
98291       iAMem = pParse->nMem + 1;
98292       pParse->nMem += pGroupBy->nExpr;
98293       iBMem = pParse->nMem + 1;
98294       pParse->nMem += pGroupBy->nExpr;
98295       sqlcipher3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
98296       VdbeComment((v, "clear abort flag"));
98297       sqlcipher3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
98298       VdbeComment((v, "indicate accumulator empty"));
98299
98300       /* Begin a loop that will extract all source rows in GROUP BY order.
98301       ** This might involve two separate loops with an OP_Sort in between, or
98302       ** it might be a single loop that uses an index to extract information
98303       ** in the right order to begin with.
98304       */
98305       sqlcipher3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
98306       pWInfo = sqlcipher3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
98307       if( pWInfo==0 ) goto select_end;
98308       if( pGroupBy==0 ){
98309         /* The optimizer is able to deliver rows in group by order so
98310         ** we do not have to sort.  The OP_OpenEphemeral table will be
98311         ** cancelled later because we still need to use the pKeyInfo
98312         */
98313         pGroupBy = p->pGroupBy;
98314         groupBySort = 0;
98315       }else{
98316         /* Rows are coming out in undetermined order.  We have to push
98317         ** each row into a sorting index, terminate the first loop,
98318         ** then loop over the sorting index in order to get the output
98319         ** in sorted order
98320         */
98321         int regBase;
98322         int regRecord;
98323         int nCol;
98324         int nGroupBy;
98325
98326         explainTempTable(pParse, 
98327             isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
98328
98329         groupBySort = 1;
98330         nGroupBy = pGroupBy->nExpr;
98331         nCol = nGroupBy + 1;
98332         j = nGroupBy+1;
98333         for(i=0; i<sAggInfo.nColumn; i++){
98334           if( sAggInfo.aCol[i].iSorterColumn>=j ){
98335             nCol++;
98336             j++;
98337           }
98338         }
98339         regBase = sqlcipher3GetTempRange(pParse, nCol);
98340         sqlcipher3ExprCacheClear(pParse);
98341         sqlcipher3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
98342         sqlcipher3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
98343         j = nGroupBy+1;
98344         for(i=0; i<sAggInfo.nColumn; i++){
98345           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
98346           if( pCol->iSorterColumn>=j ){
98347             int r1 = j + regBase;
98348             int r2;
98349
98350             r2 = sqlcipher3ExprCodeGetColumn(pParse, 
98351                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
98352             if( r1!=r2 ){
98353               sqlcipher3VdbeAddOp2(v, OP_SCopy, r2, r1);
98354             }
98355             j++;
98356           }
98357         }
98358         regRecord = sqlcipher3GetTempReg(pParse);
98359         sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
98360         sqlcipher3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
98361         sqlcipher3ReleaseTempReg(pParse, regRecord);
98362         sqlcipher3ReleaseTempRange(pParse, regBase, nCol);
98363         sqlcipher3WhereEnd(pWInfo);
98364         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
98365         sortOut = sqlcipher3GetTempReg(pParse);
98366         sqlcipher3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
98367         sqlcipher3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
98368         VdbeComment((v, "GROUP BY sort"));
98369         sAggInfo.useSortingIdx = 1;
98370         sqlcipher3ExprCacheClear(pParse);
98371       }
98372
98373       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
98374       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
98375       ** Then compare the current GROUP BY terms against the GROUP BY terms
98376       ** from the previous row currently stored in a0, a1, a2...
98377       */
98378       addrTopOfLoop = sqlcipher3VdbeCurrentAddr(v);
98379       sqlcipher3ExprCacheClear(pParse);
98380       if( groupBySort ){
98381         sqlcipher3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
98382       }
98383       for(j=0; j<pGroupBy->nExpr; j++){
98384         if( groupBySort ){
98385           sqlcipher3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
98386           if( j==0 ) sqlcipher3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
98387         }else{
98388           sAggInfo.directMode = 1;
98389           sqlcipher3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
98390         }
98391       }
98392       sqlcipher3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
98393                           (char*)pKeyInfo, P4_KEYINFO);
98394       j1 = sqlcipher3VdbeCurrentAddr(v);
98395       sqlcipher3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
98396
98397       /* Generate code that runs whenever the GROUP BY changes.
98398       ** Changes in the GROUP BY are detected by the previous code
98399       ** block.  If there were no changes, this block is skipped.
98400       **
98401       ** This code copies current group by terms in b0,b1,b2,...
98402       ** over to a0,a1,a2.  It then calls the output subroutine
98403       ** and resets the aggregate accumulator registers in preparation
98404       ** for the next GROUP BY batch.
98405       */
98406       sqlcipher3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
98407       sqlcipher3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
98408       VdbeComment((v, "output one row"));
98409       sqlcipher3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
98410       VdbeComment((v, "check abort flag"));
98411       sqlcipher3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
98412       VdbeComment((v, "reset accumulator"));
98413
98414       /* Update the aggregate accumulators based on the content of
98415       ** the current row
98416       */
98417       sqlcipher3VdbeJumpHere(v, j1);
98418       updateAccumulator(pParse, &sAggInfo);
98419       sqlcipher3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
98420       VdbeComment((v, "indicate data in accumulator"));
98421
98422       /* End of the loop
98423       */
98424       if( groupBySort ){
98425         sqlcipher3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
98426       }else{
98427         sqlcipher3WhereEnd(pWInfo);
98428         sqlcipher3VdbeChangeToNoop(v, addrSortingIdx);
98429       }
98430
98431       /* Output the final row of result
98432       */
98433       sqlcipher3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
98434       VdbeComment((v, "output final row"));
98435
98436       /* Jump over the subroutines
98437       */
98438       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
98439
98440       /* Generate a subroutine that outputs a single row of the result
98441       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
98442       ** is less than or equal to zero, the subroutine is a no-op.  If
98443       ** the processing calls for the query to abort, this subroutine
98444       ** increments the iAbortFlag memory location before returning in
98445       ** order to signal the caller to abort.
98446       */
98447       addrSetAbort = sqlcipher3VdbeCurrentAddr(v);
98448       sqlcipher3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
98449       VdbeComment((v, "set abort flag"));
98450       sqlcipher3VdbeAddOp1(v, OP_Return, regOutputRow);
98451       sqlcipher3VdbeResolveLabel(v, addrOutputRow);
98452       addrOutputRow = sqlcipher3VdbeCurrentAddr(v);
98453       sqlcipher3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
98454       VdbeComment((v, "Groupby result generator entry point"));
98455       sqlcipher3VdbeAddOp1(v, OP_Return, regOutputRow);
98456       finalizeAggFunctions(pParse, &sAggInfo);
98457       sqlcipher3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLCIPHER_JUMPIFNULL);
98458       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
98459                       distinct, pDest,
98460                       addrOutputRow+1, addrSetAbort);
98461       sqlcipher3VdbeAddOp1(v, OP_Return, regOutputRow);
98462       VdbeComment((v, "end groupby result generator"));
98463
98464       /* Generate a subroutine that will reset the group-by accumulator
98465       */
98466       sqlcipher3VdbeResolveLabel(v, addrReset);
98467       resetAccumulator(pParse, &sAggInfo);
98468       sqlcipher3VdbeAddOp1(v, OP_Return, regReset);
98469      
98470     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
98471     else {
98472       ExprList *pDel = 0;
98473 #ifndef SQLCIPHER_OMIT_BTREECOUNT
98474       Table *pTab;
98475       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
98476         /* If isSimpleCount() returns a pointer to a Table structure, then
98477         ** the SQL statement is of the form:
98478         **
98479         **   SELECT count(*) FROM <tbl>
98480         **
98481         ** where the Table structure returned represents table <tbl>.
98482         **
98483         ** This statement is so common that it is optimized specially. The
98484         ** OP_Count instruction is executed either on the intkey table that
98485         ** contains the data for table <tbl> or on one of its indexes. It
98486         ** is better to execute the op on an index, as indexes are almost
98487         ** always spread across less pages than their corresponding tables.
98488         */
98489         const int iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
98490         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
98491         Index *pIdx;                         /* Iterator variable */
98492         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
98493         Index *pBest = 0;                    /* Best index found so far */
98494         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
98495
98496         sqlcipher3CodeVerifySchema(pParse, iDb);
98497         sqlcipher3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
98498
98499         /* Search for the index that has the least amount of columns. If
98500         ** there is such an index, and it has less columns than the table
98501         ** does, then we can assume that it consumes less space on disk and
98502         ** will therefore be cheaper to scan to determine the query result.
98503         ** In this case set iRoot to the root page number of the index b-tree
98504         ** and pKeyInfo to the KeyInfo structure required to navigate the
98505         ** index.
98506         **
98507         ** (2011-04-15) Do not do a full scan of an unordered index.
98508         **
98509         ** In practice the KeyInfo structure will not be used. It is only 
98510         ** passed to keep OP_OpenRead happy.
98511         */
98512         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98513           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
98514             pBest = pIdx;
98515           }
98516         }
98517         if( pBest && pBest->nColumn<pTab->nCol ){
98518           iRoot = pBest->tnum;
98519           pKeyInfo = sqlcipher3IndexKeyinfo(pParse, pBest);
98520         }
98521
98522         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
98523         sqlcipher3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
98524         if( pKeyInfo ){
98525           sqlcipher3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
98526         }
98527         sqlcipher3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
98528         sqlcipher3VdbeAddOp1(v, OP_Close, iCsr);
98529         explainSimpleCount(pParse, pTab, pBest);
98530       }else
98531 #endif /* SQLCIPHER_OMIT_BTREECOUNT */
98532       {
98533         /* Check if the query is of one of the following forms:
98534         **
98535         **   SELECT min(x) FROM ...
98536         **   SELECT max(x) FROM ...
98537         **
98538         ** If it is, then ask the code in where.c to attempt to sort results
98539         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
98540         ** If where.c is able to produce results sorted in this order, then
98541         ** add vdbe code to break out of the processing loop after the 
98542         ** first iteration (since the first iteration of the loop is 
98543         ** guaranteed to operate on the row with the minimum or maximum 
98544         ** value of x, the only row required).
98545         **
98546         ** A special flag must be passed to sqlcipher3WhereBegin() to slightly
98547         ** modify behaviour as follows:
98548         **
98549         **   + If the query is a "SELECT min(x)", then the loop coded by
98550         **     where.c should not iterate over any values with a NULL value
98551         **     for x.
98552         **
98553         **   + The optimizer code in where.c (the thing that decides which
98554         **     index or indices to use) should place a different priority on 
98555         **     satisfying the 'ORDER BY' clause than it does in other cases.
98556         **     Refer to code and comments in where.c for details.
98557         */
98558         ExprList *pMinMax = 0;
98559         u8 flag = minMaxQuery(p);
98560         if( flag ){
98561           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
98562           pMinMax = sqlcipher3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
98563           pDel = pMinMax;
98564           if( pMinMax && !db->mallocFailed ){
98565             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
98566             pMinMax->a[0].pExpr->op = TK_COLUMN;
98567           }
98568         }
98569   
98570         /* This case runs if the aggregate has no GROUP BY clause.  The
98571         ** processing is much simpler since there is only a single row
98572         ** of output.
98573         */
98574         resetAccumulator(pParse, &sAggInfo);
98575         pWInfo = sqlcipher3WhereBegin(pParse, pTabList, pWhere, &pMinMax, 0, flag);
98576         if( pWInfo==0 ){
98577           sqlcipher3ExprListDelete(db, pDel);
98578           goto select_end;
98579         }
98580         updateAccumulator(pParse, &sAggInfo);
98581         if( !pMinMax && flag ){
98582           sqlcipher3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
98583           VdbeComment((v, "%s() by index",
98584                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
98585         }
98586         sqlcipher3WhereEnd(pWInfo);
98587         finalizeAggFunctions(pParse, &sAggInfo);
98588       }
98589
98590       pOrderBy = 0;
98591       sqlcipher3ExprIfFalse(pParse, pHaving, addrEnd, SQLCIPHER_JUMPIFNULL);
98592       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
98593                       pDest, addrEnd, addrEnd);
98594       sqlcipher3ExprListDelete(db, pDel);
98595     }
98596     sqlcipher3VdbeResolveLabel(v, addrEnd);
98597     
98598   } /* endif aggregate query */
98599
98600   if( distinct>=0 ){
98601     explainTempTable(pParse, "DISTINCT");
98602   }
98603
98604   /* If there is an ORDER BY clause, then we need to sort the results
98605   ** and send them to the callback one by one.
98606   */
98607   if( pOrderBy ){
98608     explainTempTable(pParse, "ORDER BY");
98609     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
98610   }
98611
98612   /* Jump here to skip this query
98613   */
98614   sqlcipher3VdbeResolveLabel(v, iEnd);
98615
98616   /* The SELECT was successfully coded.   Set the return code to 0
98617   ** to indicate no errors.
98618   */
98619   rc = 0;
98620
98621   /* Control jumps to here if an error is encountered above, or upon
98622   ** successful coding of the SELECT.
98623   */
98624 select_end:
98625   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
98626
98627   /* Identify column names if results of the SELECT are to be output.
98628   */
98629   if( rc==SQLCIPHER_OK && pDest->eDest==SRT_Output ){
98630     generateColumnNames(pParse, pTabList, pEList);
98631   }
98632
98633   sqlcipher3DbFree(db, sAggInfo.aCol);
98634   sqlcipher3DbFree(db, sAggInfo.aFunc);
98635   return rc;
98636 }
98637
98638 #if defined(SQLCIPHER_DEBUG)
98639 /*
98640 *******************************************************************************
98641 ** The following code is used for testing and debugging only.  The code
98642 ** that follows does not appear in normal builds.
98643 **
98644 ** These routines are used to print out the content of all or part of a 
98645 ** parse structures such as Select or Expr.  Such printouts are useful
98646 ** for helping to understand what is happening inside the code generator
98647 ** during the execution of complex SELECT statements.
98648 **
98649 ** These routine are not called anywhere from within the normal
98650 ** code base.  Then are intended to be called from within the debugger
98651 ** or from temporary "printf" statements inserted for debugging.
98652 */
98653 SQLCIPHER_PRIVATE void sqlcipher3PrintExpr(Expr *p){
98654   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
98655     sqlcipher3DebugPrintf("(%s", p->u.zToken);
98656   }else{
98657     sqlcipher3DebugPrintf("(%d", p->op);
98658   }
98659   if( p->pLeft ){
98660     sqlcipher3DebugPrintf(" ");
98661     sqlcipher3PrintExpr(p->pLeft);
98662   }
98663   if( p->pRight ){
98664     sqlcipher3DebugPrintf(" ");
98665     sqlcipher3PrintExpr(p->pRight);
98666   }
98667   sqlcipher3DebugPrintf(")");
98668 }
98669 SQLCIPHER_PRIVATE void sqlcipher3PrintExprList(ExprList *pList){
98670   int i;
98671   for(i=0; i<pList->nExpr; i++){
98672     sqlcipher3PrintExpr(pList->a[i].pExpr);
98673     if( i<pList->nExpr-1 ){
98674       sqlcipher3DebugPrintf(", ");
98675     }
98676   }
98677 }
98678 SQLCIPHER_PRIVATE void sqlcipher3PrintSelect(Select *p, int indent){
98679   sqlcipher3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
98680   sqlcipher3PrintExprList(p->pEList);
98681   sqlcipher3DebugPrintf("\n");
98682   if( p->pSrc ){
98683     char *zPrefix;
98684     int i;
98685     zPrefix = "FROM";
98686     for(i=0; i<p->pSrc->nSrc; i++){
98687       struct SrcList_item *pItem = &p->pSrc->a[i];
98688       sqlcipher3DebugPrintf("%*s ", indent+6, zPrefix);
98689       zPrefix = "";
98690       if( pItem->pSelect ){
98691         sqlcipher3DebugPrintf("(\n");
98692         sqlcipher3PrintSelect(pItem->pSelect, indent+10);
98693         sqlcipher3DebugPrintf("%*s)", indent+8, "");
98694       }else if( pItem->zName ){
98695         sqlcipher3DebugPrintf("%s", pItem->zName);
98696       }
98697       if( pItem->pTab ){
98698         sqlcipher3DebugPrintf("(table: %s)", pItem->pTab->zName);
98699       }
98700       if( pItem->zAlias ){
98701         sqlcipher3DebugPrintf(" AS %s", pItem->zAlias);
98702       }
98703       if( i<p->pSrc->nSrc-1 ){
98704         sqlcipher3DebugPrintf(",");
98705       }
98706       sqlcipher3DebugPrintf("\n");
98707     }
98708   }
98709   if( p->pWhere ){
98710     sqlcipher3DebugPrintf("%*s WHERE ", indent, "");
98711     sqlcipher3PrintExpr(p->pWhere);
98712     sqlcipher3DebugPrintf("\n");
98713   }
98714   if( p->pGroupBy ){
98715     sqlcipher3DebugPrintf("%*s GROUP BY ", indent, "");
98716     sqlcipher3PrintExprList(p->pGroupBy);
98717     sqlcipher3DebugPrintf("\n");
98718   }
98719   if( p->pHaving ){
98720     sqlcipher3DebugPrintf("%*s HAVING ", indent, "");
98721     sqlcipher3PrintExpr(p->pHaving);
98722     sqlcipher3DebugPrintf("\n");
98723   }
98724   if( p->pOrderBy ){
98725     sqlcipher3DebugPrintf("%*s ORDER BY ", indent, "");
98726     sqlcipher3PrintExprList(p->pOrderBy);
98727     sqlcipher3DebugPrintf("\n");
98728   }
98729 }
98730 /* End of the structure debug printing code
98731 *****************************************************************************/
98732 #endif /* defined(SQLCIPHER_TEST) || defined(SQLCIPHER_DEBUG) */
98733
98734 /************** End of select.c **********************************************/
98735 /************** Begin file table.c *******************************************/
98736 /*
98737 ** 2001 September 15
98738 **
98739 ** The author disclaims copyright to this source code.  In place of
98740 ** a legal notice, here is a blessing:
98741 **
98742 **    May you do good and not evil.
98743 **    May you find forgiveness for yourself and forgive others.
98744 **    May you share freely, never taking more than you give.
98745 **
98746 *************************************************************************
98747 ** This file contains the sqlcipher3_get_table() and sqlcipher3_free_table()
98748 ** interface routines.  These are just wrappers around the main
98749 ** interface routine of sqlcipher3_exec().
98750 **
98751 ** These routines are in a separate files so that they will not be linked
98752 ** if they are not used.
98753 */
98754 /* #include <stdlib.h> */
98755 /* #include <string.h> */
98756
98757 #ifndef SQLCIPHER_OMIT_GET_TABLE
98758
98759 /*
98760 ** This structure is used to pass data from sqlcipher3_get_table() through
98761 ** to the callback function is uses to build the result.
98762 */
98763 typedef struct TabResult {
98764   char **azResult;   /* Accumulated output */
98765   char *zErrMsg;     /* Error message text, if an error occurs */
98766   int nAlloc;        /* Slots allocated for azResult[] */
98767   int nRow;          /* Number of rows in the result */
98768   int nColumn;       /* Number of columns in the result */
98769   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
98770   int rc;            /* Return code from sqlcipher3_exec() */
98771 } TabResult;
98772
98773 /*
98774 ** This routine is called once for each row in the result table.  Its job
98775 ** is to fill in the TabResult structure appropriately, allocating new
98776 ** memory as necessary.
98777 */
98778 static int sqlcipher3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
98779   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
98780   int need;                         /* Slots needed in p->azResult[] */
98781   int i;                            /* Loop counter */
98782   char *z;                          /* A single column of result */
98783
98784   /* Make sure there is enough space in p->azResult to hold everything
98785   ** we need to remember from this invocation of the callback.
98786   */
98787   if( p->nRow==0 && argv!=0 ){
98788     need = nCol*2;
98789   }else{
98790     need = nCol;
98791   }
98792   if( p->nData + need > p->nAlloc ){
98793     char **azNew;
98794     p->nAlloc = p->nAlloc*2 + need;
98795     azNew = sqlcipher3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
98796     if( azNew==0 ) goto malloc_failed;
98797     p->azResult = azNew;
98798   }
98799
98800   /* If this is the first row, then generate an extra row containing
98801   ** the names of all columns.
98802   */
98803   if( p->nRow==0 ){
98804     p->nColumn = nCol;
98805     for(i=0; i<nCol; i++){
98806       z = sqlcipher3_mprintf("%s", colv[i]);
98807       if( z==0 ) goto malloc_failed;
98808       p->azResult[p->nData++] = z;
98809     }
98810   }else if( p->nColumn!=nCol ){
98811     sqlcipher3_free(p->zErrMsg);
98812     p->zErrMsg = sqlcipher3_mprintf(
98813        "sqlcipher3_get_table() called with two or more incompatible queries"
98814     );
98815     p->rc = SQLCIPHER_ERROR;
98816     return 1;
98817   }
98818
98819   /* Copy over the row data
98820   */
98821   if( argv!=0 ){
98822     for(i=0; i<nCol; i++){
98823       if( argv[i]==0 ){
98824         z = 0;
98825       }else{
98826         int n = sqlcipher3Strlen30(argv[i])+1;
98827         z = sqlcipher3_malloc( n );
98828         if( z==0 ) goto malloc_failed;
98829         memcpy(z, argv[i], n);
98830       }
98831       p->azResult[p->nData++] = z;
98832     }
98833     p->nRow++;
98834   }
98835   return 0;
98836
98837 malloc_failed:
98838   p->rc = SQLCIPHER_NOMEM;
98839   return 1;
98840 }
98841
98842 /*
98843 ** Query the database.  But instead of invoking a callback for each row,
98844 ** malloc() for space to hold the result and return the entire results
98845 ** at the conclusion of the call.
98846 **
98847 ** The result that is written to ***pazResult is held in memory obtained
98848 ** from malloc().  But the caller cannot free this memory directly.  
98849 ** Instead, the entire table should be passed to sqlcipher3_free_table() when
98850 ** the calling procedure is finished using it.
98851 */
98852 SQLCIPHER_API int sqlcipher3_get_table(
98853   sqlcipher3 *db,                /* The database on which the SQL executes */
98854   const char *zSql,           /* The SQL to be executed */
98855   char ***pazResult,          /* Write the result table here */
98856   int *pnRow,                 /* Write the number of rows in the result here */
98857   int *pnColumn,              /* Write the number of columns of result here */
98858   char **pzErrMsg             /* Write error messages here */
98859 ){
98860   int rc;
98861   TabResult res;
98862
98863   *pazResult = 0;
98864   if( pnColumn ) *pnColumn = 0;
98865   if( pnRow ) *pnRow = 0;
98866   if( pzErrMsg ) *pzErrMsg = 0;
98867   res.zErrMsg = 0;
98868   res.nRow = 0;
98869   res.nColumn = 0;
98870   res.nData = 1;
98871   res.nAlloc = 20;
98872   res.rc = SQLCIPHER_OK;
98873   res.azResult = sqlcipher3_malloc(sizeof(char*)*res.nAlloc );
98874   if( res.azResult==0 ){
98875      db->errCode = SQLCIPHER_NOMEM;
98876      return SQLCIPHER_NOMEM;
98877   }
98878   res.azResult[0] = 0;
98879   rc = sqlcipher3_exec(db, zSql, sqlcipher3_get_table_cb, &res, pzErrMsg);
98880   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
98881   res.azResult[0] = SQLCIPHER_INT_TO_PTR(res.nData);
98882   if( (rc&0xff)==SQLCIPHER_ABORT ){
98883     sqlcipher3_free_table(&res.azResult[1]);
98884     if( res.zErrMsg ){
98885       if( pzErrMsg ){
98886         sqlcipher3_free(*pzErrMsg);
98887         *pzErrMsg = sqlcipher3_mprintf("%s",res.zErrMsg);
98888       }
98889       sqlcipher3_free(res.zErrMsg);
98890     }
98891     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
98892     return res.rc;
98893   }
98894   sqlcipher3_free(res.zErrMsg);
98895   if( rc!=SQLCIPHER_OK ){
98896     sqlcipher3_free_table(&res.azResult[1]);
98897     return rc;
98898   }
98899   if( res.nAlloc>res.nData ){
98900     char **azNew;
98901     azNew = sqlcipher3_realloc( res.azResult, sizeof(char*)*res.nData );
98902     if( azNew==0 ){
98903       sqlcipher3_free_table(&res.azResult[1]);
98904       db->errCode = SQLCIPHER_NOMEM;
98905       return SQLCIPHER_NOMEM;
98906     }
98907     res.azResult = azNew;
98908   }
98909   *pazResult = &res.azResult[1];
98910   if( pnColumn ) *pnColumn = res.nColumn;
98911   if( pnRow ) *pnRow = res.nRow;
98912   return rc;
98913 }
98914
98915 /*
98916 ** This routine frees the space the sqlcipher3_get_table() malloced.
98917 */
98918 SQLCIPHER_API void sqlcipher3_free_table(
98919   char **azResult            /* Result returned from from sqlcipher3_get_table() */
98920 ){
98921   if( azResult ){
98922     int i, n;
98923     azResult--;
98924     assert( azResult!=0 );
98925     n = SQLCIPHER_PTR_TO_INT(azResult[0]);
98926     for(i=1; i<n; i++){ if( azResult[i] ) sqlcipher3_free(azResult[i]); }
98927     sqlcipher3_free(azResult);
98928   }
98929 }
98930
98931 #endif /* SQLCIPHER_OMIT_GET_TABLE */
98932
98933 /************** End of table.c ***********************************************/
98934 /************** Begin file trigger.c *****************************************/
98935 /*
98936 **
98937 ** The author disclaims copyright to this source code.  In place of
98938 ** a legal notice, here is a blessing:
98939 **
98940 **    May you do good and not evil.
98941 **    May you find forgiveness for yourself and forgive others.
98942 **    May you share freely, never taking more than you give.
98943 **
98944 *************************************************************************
98945 ** This file contains the implementation for TRIGGERs
98946 */
98947
98948 #ifndef SQLCIPHER_OMIT_TRIGGER
98949 /*
98950 ** Delete a linked list of TriggerStep structures.
98951 */
98952 SQLCIPHER_PRIVATE void sqlcipher3DeleteTriggerStep(sqlcipher3 *db, TriggerStep *pTriggerStep){
98953   while( pTriggerStep ){
98954     TriggerStep * pTmp = pTriggerStep;
98955     pTriggerStep = pTriggerStep->pNext;
98956
98957     sqlcipher3ExprDelete(db, pTmp->pWhere);
98958     sqlcipher3ExprListDelete(db, pTmp->pExprList);
98959     sqlcipher3SelectDelete(db, pTmp->pSelect);
98960     sqlcipher3IdListDelete(db, pTmp->pIdList);
98961
98962     sqlcipher3DbFree(db, pTmp);
98963   }
98964 }
98965
98966 /*
98967 ** Given table pTab, return a list of all the triggers attached to 
98968 ** the table. The list is connected by Trigger.pNext pointers.
98969 **
98970 ** All of the triggers on pTab that are in the same database as pTab
98971 ** are already attached to pTab->pTrigger.  But there might be additional
98972 ** triggers on pTab in the TEMP schema.  This routine prepends all
98973 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
98974 ** and returns the combined list.
98975 **
98976 ** To state it another way:  This routine returns a list of all triggers
98977 ** that fire off of pTab.  The list will include any TEMP triggers on
98978 ** pTab as well as the triggers lised in pTab->pTrigger.
98979 */
98980 SQLCIPHER_PRIVATE Trigger *sqlcipher3TriggerList(Parse *pParse, Table *pTab){
98981   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
98982   Trigger *pList = 0;                  /* List of triggers to return */
98983
98984   if( pParse->disableTriggers ){
98985     return 0;
98986   }
98987
98988   if( pTmpSchema!=pTab->pSchema ){
98989     HashElem *p;
98990     assert( sqlcipher3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
98991     for(p=sqlcipherHashFirst(&pTmpSchema->trigHash); p; p=sqlcipherHashNext(p)){
98992       Trigger *pTrig = (Trigger *)sqlcipherHashData(p);
98993       if( pTrig->pTabSchema==pTab->pSchema
98994        && 0==sqlcipher3StrICmp(pTrig->table, pTab->zName) 
98995       ){
98996         pTrig->pNext = (pList ? pList : pTab->pTrigger);
98997         pList = pTrig;
98998       }
98999     }
99000   }
99001
99002   return (pList ? pList : pTab->pTrigger);
99003 }
99004
99005 /*
99006 ** This is called by the parser when it sees a CREATE TRIGGER statement
99007 ** up to the point of the BEGIN before the trigger actions.  A Trigger
99008 ** structure is generated based on the information available and stored
99009 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
99010 ** sqlcipher3FinishTrigger() function is called to complete the trigger
99011 ** construction process.
99012 */
99013 SQLCIPHER_PRIVATE void sqlcipher3BeginTrigger(
99014   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
99015   Token *pName1,      /* The name of the trigger */
99016   Token *pName2,      /* The name of the trigger */
99017   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
99018   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
99019   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
99020   SrcList *pTableName,/* The name of the table/view the trigger applies to */
99021   Expr *pWhen,        /* WHEN clause */
99022   int isTemp,         /* True if the TEMPORARY keyword is present */
99023   int noErr           /* Suppress errors if the trigger already exists */
99024 ){
99025   Trigger *pTrigger = 0;  /* The new trigger */
99026   Table *pTab;            /* Table that the trigger fires off of */
99027   char *zName = 0;        /* Name of the trigger */
99028   sqlcipher3 *db = pParse->db;  /* The database connection */
99029   int iDb;                /* The database to store the trigger in */
99030   Token *pName;           /* The unqualified db name */
99031   DbFixer sFix;           /* State vector for the DB fixer */
99032   int iTabDb;             /* Index of the database holding pTab */
99033
99034   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
99035   assert( pName2!=0 );
99036   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
99037   assert( op>0 && op<0xff );
99038   if( isTemp ){
99039     /* If TEMP was specified, then the trigger name may not be qualified. */
99040     if( pName2->n>0 ){
99041       sqlcipher3ErrorMsg(pParse, "temporary trigger may not have qualified name");
99042       goto trigger_cleanup;
99043     }
99044     iDb = 1;
99045     pName = pName1;
99046   }else{
99047     /* Figure out the db that the the trigger will be created in */
99048     iDb = sqlcipher3TwoPartName(pParse, pName1, pName2, &pName);
99049     if( iDb<0 ){
99050       goto trigger_cleanup;
99051     }
99052   }
99053   if( !pTableName || db->mallocFailed ){
99054     goto trigger_cleanup;
99055   }
99056
99057   /* A long-standing parser bug is that this syntax was allowed:
99058   **
99059   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
99060   **                                                 ^^^^^^^^
99061   **
99062   ** To maintain backwards compatibility, ignore the database
99063   ** name on pTableName if we are reparsing our of SQLCIPHER_MASTER.
99064   */
99065   if( db->init.busy && iDb!=1 ){
99066     sqlcipher3DbFree(db, pTableName->a[0].zDatabase);
99067     pTableName->a[0].zDatabase = 0;
99068   }
99069
99070   /* If the trigger name was unqualified, and the table is a temp table,
99071   ** then set iDb to 1 to create the trigger in the temporary database.
99072   ** If sqlcipher3SrcListLookup() returns 0, indicating the table does not
99073   ** exist, the error is caught by the block below.
99074   */
99075   pTab = sqlcipher3SrcListLookup(pParse, pTableName);
99076   if( db->init.busy==0 && pName2->n==0 && pTab
99077         && pTab->pSchema==db->aDb[1].pSchema ){
99078     iDb = 1;
99079   }
99080
99081   /* Ensure the table name matches database name and that the table exists */
99082   if( db->mallocFailed ) goto trigger_cleanup;
99083   assert( pTableName->nSrc==1 );
99084   if( sqlcipher3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
99085       sqlcipher3FixSrcList(&sFix, pTableName) ){
99086     goto trigger_cleanup;
99087   }
99088   pTab = sqlcipher3SrcListLookup(pParse, pTableName);
99089   if( !pTab ){
99090     /* The table does not exist. */
99091     if( db->init.iDb==1 ){
99092       /* Ticket #3810.
99093       ** Normally, whenever a table is dropped, all associated triggers are
99094       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
99095       ** and the table is dropped by a different database connection, the
99096       ** trigger is not visible to the database connection that does the
99097       ** drop so the trigger cannot be dropped.  This results in an
99098       ** "orphaned trigger" - a trigger whose associated table is missing.
99099       */
99100       db->init.orphanTrigger = 1;
99101     }
99102     goto trigger_cleanup;
99103   }
99104   if( IsVirtual(pTab) ){
99105     sqlcipher3ErrorMsg(pParse, "cannot create triggers on virtual tables");
99106     goto trigger_cleanup;
99107   }
99108
99109   /* Check that the trigger name is not reserved and that no trigger of the
99110   ** specified name exists */
99111   zName = sqlcipher3NameFromToken(db, pName);
99112   if( !zName || SQLCIPHER_OK!=sqlcipher3CheckObjectName(pParse, zName) ){
99113     goto trigger_cleanup;
99114   }
99115   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
99116   if( sqlcipher3HashFind(&(db->aDb[iDb].pSchema->trigHash),
99117                       zName, sqlcipher3Strlen30(zName)) ){
99118     if( !noErr ){
99119       sqlcipher3ErrorMsg(pParse, "trigger %T already exists", pName);
99120     }else{
99121       assert( !db->init.busy );
99122       sqlcipher3CodeVerifySchema(pParse, iDb);
99123     }
99124     goto trigger_cleanup;
99125   }
99126
99127   /* Do not create a trigger on a system table */
99128   if( sqlcipher3StrNICmp(pTab->zName, "sqlcipher_", 7)==0 ){
99129     sqlcipher3ErrorMsg(pParse, "cannot create trigger on system table");
99130     pParse->nErr++;
99131     goto trigger_cleanup;
99132   }
99133
99134   /* INSTEAD of triggers are only for views and views only support INSTEAD
99135   ** of triggers.
99136   */
99137   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
99138     sqlcipher3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
99139         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
99140     goto trigger_cleanup;
99141   }
99142   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
99143     sqlcipher3ErrorMsg(pParse, "cannot create INSTEAD OF"
99144         " trigger on table: %S", pTableName, 0);
99145     goto trigger_cleanup;
99146   }
99147   iTabDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
99148
99149 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
99150   {
99151     int code = SQLCIPHER_CREATE_TRIGGER;
99152     const char *zDb = db->aDb[iTabDb].zName;
99153     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
99154     if( iTabDb==1 || isTemp ) code = SQLCIPHER_CREATE_TEMP_TRIGGER;
99155     if( sqlcipher3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
99156       goto trigger_cleanup;
99157     }
99158     if( sqlcipher3AuthCheck(pParse, SQLCIPHER_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
99159       goto trigger_cleanup;
99160     }
99161   }
99162 #endif
99163
99164   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
99165   ** cannot appear on views.  So we might as well translate every
99166   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
99167   ** elsewhere.
99168   */
99169   if (tr_tm == TK_INSTEAD){
99170     tr_tm = TK_BEFORE;
99171   }
99172
99173   /* Build the Trigger object */
99174   pTrigger = (Trigger*)sqlcipher3DbMallocZero(db, sizeof(Trigger));
99175   if( pTrigger==0 ) goto trigger_cleanup;
99176   pTrigger->zName = zName;
99177   zName = 0;
99178   pTrigger->table = sqlcipher3DbStrDup(db, pTableName->a[0].zName);
99179   pTrigger->pSchema = db->aDb[iDb].pSchema;
99180   pTrigger->pTabSchema = pTab->pSchema;
99181   pTrigger->op = (u8)op;
99182   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
99183   pTrigger->pWhen = sqlcipher3ExprDup(db, pWhen, EXPRDUP_REDUCE);
99184   pTrigger->pColumns = sqlcipher3IdListDup(db, pColumns);
99185   assert( pParse->pNewTrigger==0 );
99186   pParse->pNewTrigger = pTrigger;
99187
99188 trigger_cleanup:
99189   sqlcipher3DbFree(db, zName);
99190   sqlcipher3SrcListDelete(db, pTableName);
99191   sqlcipher3IdListDelete(db, pColumns);
99192   sqlcipher3ExprDelete(db, pWhen);
99193   if( !pParse->pNewTrigger ){
99194     sqlcipher3DeleteTrigger(db, pTrigger);
99195   }else{
99196     assert( pParse->pNewTrigger==pTrigger );
99197   }
99198 }
99199
99200 /*
99201 ** This routine is called after all of the trigger actions have been parsed
99202 ** in order to complete the process of building the trigger.
99203 */
99204 SQLCIPHER_PRIVATE void sqlcipher3FinishTrigger(
99205   Parse *pParse,          /* Parser context */
99206   TriggerStep *pStepList, /* The triggered program */
99207   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
99208 ){
99209   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
99210   char *zName;                            /* Name of trigger */
99211   sqlcipher3 *db = pParse->db;               /* The database */
99212   DbFixer sFix;                           /* Fixer object */
99213   int iDb;                                /* Database containing the trigger */
99214   Token nameToken;                        /* Trigger name for error reporting */
99215
99216   pParse->pNewTrigger = 0;
99217   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
99218   zName = pTrig->zName;
99219   iDb = sqlcipher3SchemaToIndex(pParse->db, pTrig->pSchema);
99220   pTrig->step_list = pStepList;
99221   while( pStepList ){
99222     pStepList->pTrig = pTrig;
99223     pStepList = pStepList->pNext;
99224   }
99225   nameToken.z = pTrig->zName;
99226   nameToken.n = sqlcipher3Strlen30(nameToken.z);
99227   if( sqlcipher3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
99228           && sqlcipher3FixTriggerStep(&sFix, pTrig->step_list) ){
99229     goto triggerfinish_cleanup;
99230   }
99231
99232   /* if we are not initializing,
99233   ** build the sqlcipher_master entry
99234   */
99235   if( !db->init.busy ){
99236     Vdbe *v;
99237     char *z;
99238
99239     /* Make an entry in the sqlcipher_master table */
99240     v = sqlcipher3GetVdbe(pParse);
99241     if( v==0 ) goto triggerfinish_cleanup;
99242     sqlcipher3BeginWriteOperation(pParse, 0, iDb);
99243     z = sqlcipher3DbStrNDup(db, (char*)pAll->z, pAll->n);
99244     sqlcipher3NestedParse(pParse,
99245        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
99246        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
99247        pTrig->table, z);
99248     sqlcipher3DbFree(db, z);
99249     sqlcipher3ChangeCookie(pParse, iDb);
99250     sqlcipher3VdbeAddParseSchemaOp(v, iDb,
99251         sqlcipher3MPrintf(db, "type='trigger' AND name='%q'", zName));
99252   }
99253
99254   if( db->init.busy ){
99255     Trigger *pLink = pTrig;
99256     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
99257     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
99258     pTrig = sqlcipher3HashInsert(pHash, zName, sqlcipher3Strlen30(zName), pTrig);
99259     if( pTrig ){
99260       db->mallocFailed = 1;
99261     }else if( pLink->pSchema==pLink->pTabSchema ){
99262       Table *pTab;
99263       int n = sqlcipher3Strlen30(pLink->table);
99264       pTab = sqlcipher3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
99265       assert( pTab!=0 );
99266       pLink->pNext = pTab->pTrigger;
99267       pTab->pTrigger = pLink;
99268     }
99269   }
99270
99271 triggerfinish_cleanup:
99272   sqlcipher3DeleteTrigger(db, pTrig);
99273   assert( !pParse->pNewTrigger );
99274   sqlcipher3DeleteTriggerStep(db, pStepList);
99275 }
99276
99277 /*
99278 ** Turn a SELECT statement (that the pSelect parameter points to) into
99279 ** a trigger step.  Return a pointer to a TriggerStep structure.
99280 **
99281 ** The parser calls this routine when it finds a SELECT statement in
99282 ** body of a TRIGGER.  
99283 */
99284 SQLCIPHER_PRIVATE TriggerStep *sqlcipher3TriggerSelectStep(sqlcipher3 *db, Select *pSelect){
99285   TriggerStep *pTriggerStep = sqlcipher3DbMallocZero(db, sizeof(TriggerStep));
99286   if( pTriggerStep==0 ) {
99287     sqlcipher3SelectDelete(db, pSelect);
99288     return 0;
99289   }
99290   pTriggerStep->op = TK_SELECT;
99291   pTriggerStep->pSelect = pSelect;
99292   pTriggerStep->orconf = OE_Default;
99293   return pTriggerStep;
99294 }
99295
99296 /*
99297 ** Allocate space to hold a new trigger step.  The allocated space
99298 ** holds both the TriggerStep object and the TriggerStep.target.z string.
99299 **
99300 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
99301 */
99302 static TriggerStep *triggerStepAllocate(
99303   sqlcipher3 *db,                /* Database connection */
99304   u8 op,                      /* Trigger opcode */
99305   Token *pName                /* The target name */
99306 ){
99307   TriggerStep *pTriggerStep;
99308
99309   pTriggerStep = sqlcipher3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
99310   if( pTriggerStep ){
99311     char *z = (char*)&pTriggerStep[1];
99312     memcpy(z, pName->z, pName->n);
99313     pTriggerStep->target.z = z;
99314     pTriggerStep->target.n = pName->n;
99315     pTriggerStep->op = op;
99316   }
99317   return pTriggerStep;
99318 }
99319
99320 /*
99321 ** Build a trigger step out of an INSERT statement.  Return a pointer
99322 ** to the new trigger step.
99323 **
99324 ** The parser calls this routine when it sees an INSERT inside the
99325 ** body of a trigger.
99326 */
99327 SQLCIPHER_PRIVATE TriggerStep *sqlcipher3TriggerInsertStep(
99328   sqlcipher3 *db,        /* The database connection */
99329   Token *pTableName,  /* Name of the table into which we insert */
99330   IdList *pColumn,    /* List of columns in pTableName to insert into */
99331   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
99332   Select *pSelect,    /* A SELECT statement that supplies values */
99333   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
99334 ){
99335   TriggerStep *pTriggerStep;
99336
99337   assert(pEList == 0 || pSelect == 0);
99338   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
99339
99340   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
99341   if( pTriggerStep ){
99342     pTriggerStep->pSelect = sqlcipher3SelectDup(db, pSelect, EXPRDUP_REDUCE);
99343     pTriggerStep->pIdList = pColumn;
99344     pTriggerStep->pExprList = sqlcipher3ExprListDup(db, pEList, EXPRDUP_REDUCE);
99345     pTriggerStep->orconf = orconf;
99346   }else{
99347     sqlcipher3IdListDelete(db, pColumn);
99348   }
99349   sqlcipher3ExprListDelete(db, pEList);
99350   sqlcipher3SelectDelete(db, pSelect);
99351
99352   return pTriggerStep;
99353 }
99354
99355 /*
99356 ** Construct a trigger step that implements an UPDATE statement and return
99357 ** a pointer to that trigger step.  The parser calls this routine when it
99358 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
99359 */
99360 SQLCIPHER_PRIVATE TriggerStep *sqlcipher3TriggerUpdateStep(
99361   sqlcipher3 *db,         /* The database connection */
99362   Token *pTableName,   /* Name of the table to be updated */
99363   ExprList *pEList,    /* The SET clause: list of column and new values */
99364   Expr *pWhere,        /* The WHERE clause */
99365   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
99366 ){
99367   TriggerStep *pTriggerStep;
99368
99369   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
99370   if( pTriggerStep ){
99371     pTriggerStep->pExprList = sqlcipher3ExprListDup(db, pEList, EXPRDUP_REDUCE);
99372     pTriggerStep->pWhere = sqlcipher3ExprDup(db, pWhere, EXPRDUP_REDUCE);
99373     pTriggerStep->orconf = orconf;
99374   }
99375   sqlcipher3ExprListDelete(db, pEList);
99376   sqlcipher3ExprDelete(db, pWhere);
99377   return pTriggerStep;
99378 }
99379
99380 /*
99381 ** Construct a trigger step that implements a DELETE statement and return
99382 ** a pointer to that trigger step.  The parser calls this routine when it
99383 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
99384 */
99385 SQLCIPHER_PRIVATE TriggerStep *sqlcipher3TriggerDeleteStep(
99386   sqlcipher3 *db,            /* Database connection */
99387   Token *pTableName,      /* The table from which rows are deleted */
99388   Expr *pWhere            /* The WHERE clause */
99389 ){
99390   TriggerStep *pTriggerStep;
99391
99392   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
99393   if( pTriggerStep ){
99394     pTriggerStep->pWhere = sqlcipher3ExprDup(db, pWhere, EXPRDUP_REDUCE);
99395     pTriggerStep->orconf = OE_Default;
99396   }
99397   sqlcipher3ExprDelete(db, pWhere);
99398   return pTriggerStep;
99399 }
99400
99401 /* 
99402 ** Recursively delete a Trigger structure
99403 */
99404 SQLCIPHER_PRIVATE void sqlcipher3DeleteTrigger(sqlcipher3 *db, Trigger *pTrigger){
99405   if( pTrigger==0 ) return;
99406   sqlcipher3DeleteTriggerStep(db, pTrigger->step_list);
99407   sqlcipher3DbFree(db, pTrigger->zName);
99408   sqlcipher3DbFree(db, pTrigger->table);
99409   sqlcipher3ExprDelete(db, pTrigger->pWhen);
99410   sqlcipher3IdListDelete(db, pTrigger->pColumns);
99411   sqlcipher3DbFree(db, pTrigger);
99412 }
99413
99414 /*
99415 ** This function is called to drop a trigger from the database schema. 
99416 **
99417 ** This may be called directly from the parser and therefore identifies
99418 ** the trigger by name.  The sqlcipher3DropTriggerPtr() routine does the
99419 ** same job as this routine except it takes a pointer to the trigger
99420 ** instead of the trigger name.
99421 **/
99422 SQLCIPHER_PRIVATE void sqlcipher3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
99423   Trigger *pTrigger = 0;
99424   int i;
99425   const char *zDb;
99426   const char *zName;
99427   int nName;
99428   sqlcipher3 *db = pParse->db;
99429
99430   if( db->mallocFailed ) goto drop_trigger_cleanup;
99431   if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
99432     goto drop_trigger_cleanup;
99433   }
99434
99435   assert( pName->nSrc==1 );
99436   zDb = pName->a[0].zDatabase;
99437   zName = pName->a[0].zName;
99438   nName = sqlcipher3Strlen30(zName);
99439   assert( zDb!=0 || sqlcipher3BtreeHoldsAllMutexes(db) );
99440   for(i=OMIT_TEMPDB; i<db->nDb; i++){
99441     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
99442     if( zDb && sqlcipher3StrICmp(db->aDb[j].zName, zDb) ) continue;
99443     assert( sqlcipher3SchemaMutexHeld(db, j, 0) );
99444     pTrigger = sqlcipher3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
99445     if( pTrigger ) break;
99446   }
99447   if( !pTrigger ){
99448     if( !noErr ){
99449       sqlcipher3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
99450     }else{
99451       sqlcipher3CodeVerifyNamedSchema(pParse, zDb);
99452     }
99453     pParse->checkSchema = 1;
99454     goto drop_trigger_cleanup;
99455   }
99456   sqlcipher3DropTriggerPtr(pParse, pTrigger);
99457
99458 drop_trigger_cleanup:
99459   sqlcipher3SrcListDelete(db, pName);
99460 }
99461
99462 /*
99463 ** Return a pointer to the Table structure for the table that a trigger
99464 ** is set on.
99465 */
99466 static Table *tableOfTrigger(Trigger *pTrigger){
99467   int n = sqlcipher3Strlen30(pTrigger->table);
99468   return sqlcipher3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
99469 }
99470
99471
99472 /*
99473 ** Drop a trigger given a pointer to that trigger. 
99474 */
99475 SQLCIPHER_PRIVATE void sqlcipher3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
99476   Table   *pTable;
99477   Vdbe *v;
99478   sqlcipher3 *db = pParse->db;
99479   int iDb;
99480
99481   iDb = sqlcipher3SchemaToIndex(pParse->db, pTrigger->pSchema);
99482   assert( iDb>=0 && iDb<db->nDb );
99483   pTable = tableOfTrigger(pTrigger);
99484   assert( pTable );
99485   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
99486 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
99487   {
99488     int code = SQLCIPHER_DROP_TRIGGER;
99489     const char *zDb = db->aDb[iDb].zName;
99490     const char *zTab = SCHEMA_TABLE(iDb);
99491     if( iDb==1 ) code = SQLCIPHER_DROP_TEMP_TRIGGER;
99492     if( sqlcipher3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
99493       sqlcipher3AuthCheck(pParse, SQLCIPHER_DELETE, zTab, 0, zDb) ){
99494       return;
99495     }
99496   }
99497 #endif
99498
99499   /* Generate code to destroy the database record of the trigger.
99500   */
99501   assert( pTable!=0 );
99502   if( (v = sqlcipher3GetVdbe(pParse))!=0 ){
99503     int base;
99504     static const VdbeOpList dropTrigger[] = {
99505       { OP_Rewind,     0, ADDR(9),  0},
99506       { OP_String8,    0, 1,        0}, /* 1 */
99507       { OP_Column,     0, 1,        2},
99508       { OP_Ne,         2, ADDR(8),  1},
99509       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
99510       { OP_Column,     0, 0,        2},
99511       { OP_Ne,         2, ADDR(8),  1},
99512       { OP_Delete,     0, 0,        0},
99513       { OP_Next,       0, ADDR(1),  0}, /* 8 */
99514     };
99515
99516     sqlcipher3BeginWriteOperation(pParse, 0, iDb);
99517     sqlcipher3OpenMasterTable(pParse, iDb);
99518     base = sqlcipher3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
99519     sqlcipher3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
99520     sqlcipher3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
99521     sqlcipher3ChangeCookie(pParse, iDb);
99522     sqlcipher3VdbeAddOp2(v, OP_Close, 0, 0);
99523     sqlcipher3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
99524     if( pParse->nMem<3 ){
99525       pParse->nMem = 3;
99526     }
99527   }
99528 }
99529
99530 /*
99531 ** Remove a trigger from the hash tables of the sqlcipher* pointer.
99532 */
99533 SQLCIPHER_PRIVATE void sqlcipher3UnlinkAndDeleteTrigger(sqlcipher3 *db, int iDb, const char *zName){
99534   Trigger *pTrigger;
99535   Hash *pHash;
99536
99537   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
99538   pHash = &(db->aDb[iDb].pSchema->trigHash);
99539   pTrigger = sqlcipher3HashInsert(pHash, zName, sqlcipher3Strlen30(zName), 0);
99540   if( ALWAYS(pTrigger) ){
99541     if( pTrigger->pSchema==pTrigger->pTabSchema ){
99542       Table *pTab = tableOfTrigger(pTrigger);
99543       Trigger **pp;
99544       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
99545       *pp = (*pp)->pNext;
99546     }
99547     sqlcipher3DeleteTrigger(db, pTrigger);
99548     db->flags |= SQLCIPHER_InternChanges;
99549   }
99550 }
99551
99552 /*
99553 ** pEList is the SET clause of an UPDATE statement.  Each entry
99554 ** in pEList is of the format <id>=<expr>.  If any of the entries
99555 ** in pEList have an <id> which matches an identifier in pIdList,
99556 ** then return TRUE.  If pIdList==NULL, then it is considered a
99557 ** wildcard that matches anything.  Likewise if pEList==NULL then
99558 ** it matches anything so always return true.  Return false only
99559 ** if there is no match.
99560 */
99561 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
99562   int e;
99563   if( pIdList==0 || NEVER(pEList==0) ) return 1;
99564   for(e=0; e<pEList->nExpr; e++){
99565     if( sqlcipher3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
99566   }
99567   return 0; 
99568 }
99569
99570 /*
99571 ** Return a list of all triggers on table pTab if there exists at least
99572 ** one trigger that must be fired when an operation of type 'op' is 
99573 ** performed on the table, and, if that operation is an UPDATE, if at
99574 ** least one of the columns in pChanges is being modified.
99575 */
99576 SQLCIPHER_PRIVATE Trigger *sqlcipher3TriggersExist(
99577   Parse *pParse,          /* Parse context */
99578   Table *pTab,            /* The table the contains the triggers */
99579   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
99580   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
99581   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
99582 ){
99583   int mask = 0;
99584   Trigger *pList = 0;
99585   Trigger *p;
99586
99587   if( (pParse->db->flags & SQLCIPHER_EnableTrigger)!=0 ){
99588     pList = sqlcipher3TriggerList(pParse, pTab);
99589   }
99590   assert( pList==0 || IsVirtual(pTab)==0 );
99591   for(p=pList; p; p=p->pNext){
99592     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
99593       mask |= p->tr_tm;
99594     }
99595   }
99596   if( pMask ){
99597     *pMask = mask;
99598   }
99599   return (mask ? pList : 0);
99600 }
99601
99602 /*
99603 ** Convert the pStep->target token into a SrcList and return a pointer
99604 ** to that SrcList.
99605 **
99606 ** This routine adds a specific database name, if needed, to the target when
99607 ** forming the SrcList.  This prevents a trigger in one database from
99608 ** referring to a target in another database.  An exception is when the
99609 ** trigger is in TEMP in which case it can refer to any other database it
99610 ** wants.
99611 */
99612 static SrcList *targetSrcList(
99613   Parse *pParse,       /* The parsing context */
99614   TriggerStep *pStep   /* The trigger containing the target token */
99615 ){
99616   int iDb;             /* Index of the database to use */
99617   SrcList *pSrc;       /* SrcList to be returned */
99618
99619   pSrc = sqlcipher3SrcListAppend(pParse->db, 0, &pStep->target, 0);
99620   if( pSrc ){
99621     assert( pSrc->nSrc>0 );
99622     assert( pSrc->a!=0 );
99623     iDb = sqlcipher3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
99624     if( iDb==0 || iDb>=2 ){
99625       sqlcipher3 *db = pParse->db;
99626       assert( iDb<pParse->db->nDb );
99627       pSrc->a[pSrc->nSrc-1].zDatabase = sqlcipher3DbStrDup(db, db->aDb[iDb].zName);
99628     }
99629   }
99630   return pSrc;
99631 }
99632
99633 /*
99634 ** Generate VDBE code for the statements inside the body of a single 
99635 ** trigger.
99636 */
99637 static int codeTriggerProgram(
99638   Parse *pParse,            /* The parser context */
99639   TriggerStep *pStepList,   /* List of statements inside the trigger body */
99640   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
99641 ){
99642   TriggerStep *pStep;
99643   Vdbe *v = pParse->pVdbe;
99644   sqlcipher3 *db = pParse->db;
99645
99646   assert( pParse->pTriggerTab && pParse->pToplevel );
99647   assert( pStepList );
99648   assert( v!=0 );
99649   for(pStep=pStepList; pStep; pStep=pStep->pNext){
99650     /* Figure out the ON CONFLICT policy that will be used for this step
99651     ** of the trigger program. If the statement that caused this trigger
99652     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
99653     ** the ON CONFLICT policy that was specified as part of the trigger
99654     ** step statement. Example:
99655     **
99656     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
99657     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
99658     **   END;
99659     **
99660     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
99661     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
99662     */
99663     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
99664
99665     switch( pStep->op ){
99666       case TK_UPDATE: {
99667         sqlcipher3Update(pParse, 
99668           targetSrcList(pParse, pStep),
99669           sqlcipher3ExprListDup(db, pStep->pExprList, 0), 
99670           sqlcipher3ExprDup(db, pStep->pWhere, 0), 
99671           pParse->eOrconf
99672         );
99673         break;
99674       }
99675       case TK_INSERT: {
99676         sqlcipher3Insert(pParse, 
99677           targetSrcList(pParse, pStep),
99678           sqlcipher3ExprListDup(db, pStep->pExprList, 0), 
99679           sqlcipher3SelectDup(db, pStep->pSelect, 0), 
99680           sqlcipher3IdListDup(db, pStep->pIdList), 
99681           pParse->eOrconf
99682         );
99683         break;
99684       }
99685       case TK_DELETE: {
99686         sqlcipher3DeleteFrom(pParse, 
99687           targetSrcList(pParse, pStep),
99688           sqlcipher3ExprDup(db, pStep->pWhere, 0)
99689         );
99690         break;
99691       }
99692       default: assert( pStep->op==TK_SELECT ); {
99693         SelectDest sDest;
99694         Select *pSelect = sqlcipher3SelectDup(db, pStep->pSelect, 0);
99695         sqlcipher3SelectDestInit(&sDest, SRT_Discard, 0);
99696         sqlcipher3Select(pParse, pSelect, &sDest);
99697         sqlcipher3SelectDelete(db, pSelect);
99698         break;
99699       }
99700     } 
99701     if( pStep->op!=TK_SELECT ){
99702       sqlcipher3VdbeAddOp0(v, OP_ResetCount);
99703     }
99704   }
99705
99706   return 0;
99707 }
99708
99709 #ifdef SQLCIPHER_DEBUG
99710 /*
99711 ** This function is used to add VdbeComment() annotations to a VDBE
99712 ** program. It is not used in production code, only for debugging.
99713 */
99714 static const char *onErrorText(int onError){
99715   switch( onError ){
99716     case OE_Abort:    return "abort";
99717     case OE_Rollback: return "rollback";
99718     case OE_Fail:     return "fail";
99719     case OE_Replace:  return "replace";
99720     case OE_Ignore:   return "ignore";
99721     case OE_Default:  return "default";
99722   }
99723   return "n/a";
99724 }
99725 #endif
99726
99727 /*
99728 ** Parse context structure pFrom has just been used to create a sub-vdbe
99729 ** (trigger program). If an error has occurred, transfer error information
99730 ** from pFrom to pTo.
99731 */
99732 static void transferParseError(Parse *pTo, Parse *pFrom){
99733   assert( pFrom->zErrMsg==0 || pFrom->nErr );
99734   assert( pTo->zErrMsg==0 || pTo->nErr );
99735   if( pTo->nErr==0 ){
99736     pTo->zErrMsg = pFrom->zErrMsg;
99737     pTo->nErr = pFrom->nErr;
99738   }else{
99739     sqlcipher3DbFree(pFrom->db, pFrom->zErrMsg);
99740   }
99741 }
99742
99743 /*
99744 ** Create and populate a new TriggerPrg object with a sub-program 
99745 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
99746 */
99747 static TriggerPrg *codeRowTrigger(
99748   Parse *pParse,       /* Current parse context */
99749   Trigger *pTrigger,   /* Trigger to code */
99750   Table *pTab,         /* The table pTrigger is attached to */
99751   int orconf           /* ON CONFLICT policy to code trigger program with */
99752 ){
99753   Parse *pTop = sqlcipher3ParseToplevel(pParse);
99754   sqlcipher3 *db = pParse->db;   /* Database handle */
99755   TriggerPrg *pPrg;           /* Value to return */
99756   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
99757   Vdbe *v;                    /* Temporary VM */
99758   NameContext sNC;            /* Name context for sub-vdbe */
99759   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
99760   Parse *pSubParse;           /* Parse context for sub-vdbe */
99761   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
99762
99763   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
99764   assert( pTop->pVdbe );
99765
99766   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
99767   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
99768   ** list of the top-level Parse object sooner rather than later.  */
99769   pPrg = sqlcipher3DbMallocZero(db, sizeof(TriggerPrg));
99770   if( !pPrg ) return 0;
99771   pPrg->pNext = pTop->pTriggerPrg;
99772   pTop->pTriggerPrg = pPrg;
99773   pPrg->pProgram = pProgram = sqlcipher3DbMallocZero(db, sizeof(SubProgram));
99774   if( !pProgram ) return 0;
99775   sqlcipher3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
99776   pPrg->pTrigger = pTrigger;
99777   pPrg->orconf = orconf;
99778   pPrg->aColmask[0] = 0xffffffff;
99779   pPrg->aColmask[1] = 0xffffffff;
99780
99781   /* Allocate and populate a new Parse context to use for coding the 
99782   ** trigger sub-program.  */
99783   pSubParse = sqlcipher3StackAllocZero(db, sizeof(Parse));
99784   if( !pSubParse ) return 0;
99785   memset(&sNC, 0, sizeof(sNC));
99786   sNC.pParse = pSubParse;
99787   pSubParse->db = db;
99788   pSubParse->pTriggerTab = pTab;
99789   pSubParse->pToplevel = pTop;
99790   pSubParse->zAuthContext = pTrigger->zName;
99791   pSubParse->eTriggerOp = pTrigger->op;
99792   pSubParse->nQueryLoop = pParse->nQueryLoop;
99793
99794   v = sqlcipher3GetVdbe(pSubParse);
99795   if( v ){
99796     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
99797       pTrigger->zName, onErrorText(orconf),
99798       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
99799         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
99800         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
99801         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
99802       pTab->zName
99803     ));
99804 #ifndef SQLCIPHER_OMIT_TRACE
99805     sqlcipher3VdbeChangeP4(v, -1, 
99806       sqlcipher3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
99807     );
99808 #endif
99809
99810     /* If one was specified, code the WHEN clause. If it evaluates to false
99811     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
99812     ** OP_Halt inserted at the end of the program.  */
99813     if( pTrigger->pWhen ){
99814       pWhen = sqlcipher3ExprDup(db, pTrigger->pWhen, 0);
99815       if( SQLCIPHER_OK==sqlcipher3ResolveExprNames(&sNC, pWhen) 
99816        && db->mallocFailed==0 
99817       ){
99818         iEndTrigger = sqlcipher3VdbeMakeLabel(v);
99819         sqlcipher3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLCIPHER_JUMPIFNULL);
99820       }
99821       sqlcipher3ExprDelete(db, pWhen);
99822     }
99823
99824     /* Code the trigger program into the sub-vdbe. */
99825     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
99826
99827     /* Insert an OP_Halt at the end of the sub-program. */
99828     if( iEndTrigger ){
99829       sqlcipher3VdbeResolveLabel(v, iEndTrigger);
99830     }
99831     sqlcipher3VdbeAddOp0(v, OP_Halt);
99832     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
99833
99834     transferParseError(pParse, pSubParse);
99835     if( db->mallocFailed==0 ){
99836       pProgram->aOp = sqlcipher3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
99837     }
99838     pProgram->nMem = pSubParse->nMem;
99839     pProgram->nCsr = pSubParse->nTab;
99840     pProgram->token = (void *)pTrigger;
99841     pPrg->aColmask[0] = pSubParse->oldmask;
99842     pPrg->aColmask[1] = pSubParse->newmask;
99843     sqlcipher3VdbeDelete(v);
99844   }
99845
99846   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
99847   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
99848   sqlcipher3StackFree(db, pSubParse);
99849
99850   return pPrg;
99851 }
99852     
99853 /*
99854 ** Return a pointer to a TriggerPrg object containing the sub-program for
99855 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
99856 ** TriggerPrg object exists, a new object is allocated and populated before
99857 ** being returned.
99858 */
99859 static TriggerPrg *getRowTrigger(
99860   Parse *pParse,       /* Current parse context */
99861   Trigger *pTrigger,   /* Trigger to code */
99862   Table *pTab,         /* The table trigger pTrigger is attached to */
99863   int orconf           /* ON CONFLICT algorithm. */
99864 ){
99865   Parse *pRoot = sqlcipher3ParseToplevel(pParse);
99866   TriggerPrg *pPrg;
99867
99868   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
99869
99870   /* It may be that this trigger has already been coded (or is in the
99871   ** process of being coded). If this is the case, then an entry with
99872   ** a matching TriggerPrg.pTrigger field will be present somewhere
99873   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
99874   for(pPrg=pRoot->pTriggerPrg; 
99875       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
99876       pPrg=pPrg->pNext
99877   );
99878
99879   /* If an existing TriggerPrg could not be located, create a new one. */
99880   if( !pPrg ){
99881     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
99882   }
99883
99884   return pPrg;
99885 }
99886
99887 /*
99888 ** Generate code for the trigger program associated with trigger p on 
99889 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
99890 ** function are the same as those described in the header function for
99891 ** sqlcipher3CodeRowTrigger()
99892 */
99893 SQLCIPHER_PRIVATE void sqlcipher3CodeRowTriggerDirect(
99894   Parse *pParse,       /* Parse context */
99895   Trigger *p,          /* Trigger to code */
99896   Table *pTab,         /* The table to code triggers from */
99897   int reg,             /* Reg array containing OLD.* and NEW.* values */
99898   int orconf,          /* ON CONFLICT policy */
99899   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
99900 ){
99901   Vdbe *v = sqlcipher3GetVdbe(pParse); /* Main VM */
99902   TriggerPrg *pPrg;
99903   pPrg = getRowTrigger(pParse, p, pTab, orconf);
99904   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
99905
99906   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
99907   ** is a pointer to the sub-vdbe containing the trigger program.  */
99908   if( pPrg ){
99909     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLCIPHER_RecTriggers));
99910
99911     sqlcipher3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
99912     sqlcipher3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
99913     VdbeComment(
99914         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
99915
99916     /* Set the P5 operand of the OP_Program instruction to non-zero if
99917     ** recursive invocation of this trigger program is disallowed. Recursive
99918     ** invocation is disallowed if (a) the sub-program is really a trigger,
99919     ** not a foreign key action, and (b) the flag to enable recursive triggers
99920     ** is clear.  */
99921     sqlcipher3VdbeChangeP5(v, (u8)bRecursive);
99922   }
99923 }
99924
99925 /*
99926 ** This is called to code the required FOR EACH ROW triggers for an operation
99927 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
99928 ** is given by the op paramater. The tr_tm parameter determines whether the
99929 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
99930 ** parameter pChanges is passed the list of columns being modified.
99931 **
99932 ** If there are no triggers that fire at the specified time for the specified
99933 ** operation on pTab, this function is a no-op.
99934 **
99935 ** The reg argument is the address of the first in an array of registers 
99936 ** that contain the values substituted for the new.* and old.* references
99937 ** in the trigger program. If N is the number of columns in table pTab
99938 ** (a copy of pTab->nCol), then registers are populated as follows:
99939 **
99940 **   Register       Contains
99941 **   ------------------------------------------------------
99942 **   reg+0          OLD.rowid
99943 **   reg+1          OLD.* value of left-most column of pTab
99944 **   ...            ...
99945 **   reg+N          OLD.* value of right-most column of pTab
99946 **   reg+N+1        NEW.rowid
99947 **   reg+N+2        OLD.* value of left-most column of pTab
99948 **   ...            ...
99949 **   reg+N+N+1      NEW.* value of right-most column of pTab
99950 **
99951 ** For ON DELETE triggers, the registers containing the NEW.* values will
99952 ** never be accessed by the trigger program, so they are not allocated or 
99953 ** populated by the caller (there is no data to populate them with anyway). 
99954 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
99955 ** are never accessed, and so are not allocated by the caller. So, for an
99956 ** ON INSERT trigger, the value passed to this function as parameter reg
99957 ** is not a readable register, although registers (reg+N) through 
99958 ** (reg+N+N+1) are.
99959 **
99960 ** Parameter orconf is the default conflict resolution algorithm for the
99961 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
99962 ** is the instruction that control should jump to if a trigger program
99963 ** raises an IGNORE exception.
99964 */
99965 SQLCIPHER_PRIVATE void sqlcipher3CodeRowTrigger(
99966   Parse *pParse,       /* Parse context */
99967   Trigger *pTrigger,   /* List of triggers on table pTab */
99968   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
99969   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
99970   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
99971   Table *pTab,         /* The table to code triggers from */
99972   int reg,             /* The first in an array of registers (see above) */
99973   int orconf,          /* ON CONFLICT policy */
99974   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
99975 ){
99976   Trigger *p;          /* Used to iterate through pTrigger list */
99977
99978   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
99979   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
99980   assert( (op==TK_UPDATE)==(pChanges!=0) );
99981
99982   for(p=pTrigger; p; p=p->pNext){
99983
99984     /* Sanity checking:  The schema for the trigger and for the table are
99985     ** always defined.  The trigger must be in the same schema as the table
99986     ** or else it must be a TEMP trigger. */
99987     assert( p->pSchema!=0 );
99988     assert( p->pTabSchema!=0 );
99989     assert( p->pSchema==p->pTabSchema 
99990          || p->pSchema==pParse->db->aDb[1].pSchema );
99991
99992     /* Determine whether we should code this trigger */
99993     if( p->op==op 
99994      && p->tr_tm==tr_tm 
99995      && checkColumnOverlap(p->pColumns, pChanges)
99996     ){
99997       sqlcipher3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
99998     }
99999   }
100000 }
100001
100002 /*
100003 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
100004 ** This function returns a 32-bit bitmask indicating which columns of the 
100005 ** old.* or new.* tables actually are used by triggers. This information 
100006 ** may be used by the caller, for example, to avoid having to load the entire
100007 ** old.* record into memory when executing an UPDATE or DELETE command.
100008 **
100009 ** Bit 0 of the returned mask is set if the left-most column of the
100010 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
100011 ** the second leftmost column value is required, and so on. If there
100012 ** are more than 32 columns in the table, and at least one of the columns
100013 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
100014 **
100015 ** It is not possible to determine if the old.rowid or new.rowid column is 
100016 ** accessed by triggers. The caller must always assume that it is.
100017 **
100018 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
100019 ** applies to the old.* table. If 1, the new.* table.
100020 **
100021 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
100022 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
100023 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
100024 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
100025 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
100026 */
100027 SQLCIPHER_PRIVATE u32 sqlcipher3TriggerColmask(
100028   Parse *pParse,       /* Parse context */
100029   Trigger *pTrigger,   /* List of triggers on table pTab */
100030   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
100031   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
100032   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100033   Table *pTab,         /* The table to code triggers from */
100034   int orconf           /* Default ON CONFLICT policy for trigger steps */
100035 ){
100036   const int op = pChanges ? TK_UPDATE : TK_DELETE;
100037   u32 mask = 0;
100038   Trigger *p;
100039
100040   assert( isNew==1 || isNew==0 );
100041   for(p=pTrigger; p; p=p->pNext){
100042     if( p->op==op && (tr_tm&p->tr_tm)
100043      && checkColumnOverlap(p->pColumns,pChanges)
100044     ){
100045       TriggerPrg *pPrg;
100046       pPrg = getRowTrigger(pParse, p, pTab, orconf);
100047       if( pPrg ){
100048         mask |= pPrg->aColmask[isNew];
100049       }
100050     }
100051   }
100052
100053   return mask;
100054 }
100055
100056 #endif /* !defined(SQLCIPHER_OMIT_TRIGGER) */
100057
100058 /************** End of trigger.c *********************************************/
100059 /************** Begin file update.c ******************************************/
100060 /*
100061 ** 2001 September 15
100062 **
100063 ** The author disclaims copyright to this source code.  In place of
100064 ** a legal notice, here is a blessing:
100065 **
100066 **    May you do good and not evil.
100067 **    May you find forgiveness for yourself and forgive others.
100068 **    May you share freely, never taking more than you give.
100069 **
100070 *************************************************************************
100071 ** This file contains C code routines that are called by the parser
100072 ** to handle UPDATE statements.
100073 */
100074
100075 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
100076 /* Forward declaration */
100077 static void updateVirtualTable(
100078   Parse *pParse,       /* The parsing context */
100079   SrcList *pSrc,       /* The virtual table to be modified */
100080   Table *pTab,         /* The virtual table */
100081   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
100082   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
100083   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
100084   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
100085   int onError          /* ON CONFLICT strategy */
100086 );
100087 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
100088
100089 /*
100090 ** The most recently coded instruction was an OP_Column to retrieve the
100091 ** i-th column of table pTab. This routine sets the P4 parameter of the 
100092 ** OP_Column to the default value, if any.
100093 **
100094 ** The default value of a column is specified by a DEFAULT clause in the 
100095 ** column definition. This was either supplied by the user when the table
100096 ** was created, or added later to the table definition by an ALTER TABLE
100097 ** command. If the latter, then the row-records in the table btree on disk
100098 ** may not contain a value for the column and the default value, taken
100099 ** from the P4 parameter of the OP_Column instruction, is returned instead.
100100 ** If the former, then all row-records are guaranteed to include a value
100101 ** for the column and the P4 value is not required.
100102 **
100103 ** Column definitions created by an ALTER TABLE command may only have 
100104 ** literal default values specified: a number, null or a string. (If a more
100105 ** complicated default expression value was provided, it is evaluated 
100106 ** when the ALTER TABLE is executed and one of the literal values written
100107 ** into the sqlcipher_master table.)
100108 **
100109 ** Therefore, the P4 parameter is only required if the default value for
100110 ** the column is a literal number, string or null. The sqlcipher3ValueFromExpr()
100111 ** function is capable of transforming these types of expressions into
100112 ** sqlcipher3_value objects.
100113 **
100114 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
100115 ** on register iReg. This is used when an equivalent integer value is 
100116 ** stored in place of an 8-byte floating point value in order to save 
100117 ** space.
100118 */
100119 SQLCIPHER_PRIVATE void sqlcipher3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
100120   assert( pTab!=0 );
100121   if( !pTab->pSelect ){
100122     sqlcipher3_value *pValue;
100123     u8 enc = ENC(sqlcipher3VdbeDb(v));
100124     Column *pCol = &pTab->aCol[i];
100125     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
100126     assert( i<pTab->nCol );
100127     sqlcipher3ValueFromExpr(sqlcipher3VdbeDb(v), pCol->pDflt, enc, 
100128                          pCol->affinity, &pValue);
100129     if( pValue ){
100130       sqlcipher3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
100131     }
100132 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
100133     if( iReg>=0 && pTab->aCol[i].affinity==SQLCIPHER_AFF_REAL ){
100134       sqlcipher3VdbeAddOp1(v, OP_RealAffinity, iReg);
100135     }
100136 #endif
100137   }
100138 }
100139
100140 /*
100141 ** Process an UPDATE statement.
100142 **
100143 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
100144 **          \_______/ \________/     \______/       \________________/
100145 *            onError   pTabList      pChanges             pWhere
100146 */
100147 SQLCIPHER_PRIVATE void sqlcipher3Update(
100148   Parse *pParse,         /* The parser context */
100149   SrcList *pTabList,     /* The table in which we should change things */
100150   ExprList *pChanges,    /* Things to be changed */
100151   Expr *pWhere,          /* The WHERE clause.  May be null */
100152   int onError            /* How to handle constraint errors */
100153 ){
100154   int i, j;              /* Loop counters */
100155   Table *pTab;           /* The table to be updated */
100156   int addr = 0;          /* VDBE instruction address of the start of the loop */
100157   WhereInfo *pWInfo;     /* Information about the WHERE clause */
100158   Vdbe *v;               /* The virtual database engine */
100159   Index *pIdx;           /* For looping over indices */
100160   int nIdx;              /* Number of indices that need updating */
100161   int iCur;              /* VDBE Cursor number of pTab */
100162   sqlcipher3 *db;           /* The database structure */
100163   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
100164   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
100165                          ** an expression for the i-th column of the table.
100166                          ** aXRef[i]==-1 if the i-th column is not changed. */
100167   int chngRowid;         /* True if the record number is being changed */
100168   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
100169   int openAll = 0;       /* True if all indices need to be opened */
100170   AuthContext sContext;  /* The authorization context */
100171   NameContext sNC;       /* The name-context to resolve expressions in */
100172   int iDb;               /* Database containing the table being updated */
100173   int okOnePass;         /* True for one-pass algorithm without the FIFO */
100174   int hasFK;             /* True if foreign key processing is required */
100175
100176 #ifndef SQLCIPHER_OMIT_TRIGGER
100177   int isView;            /* True when updating a view (INSTEAD OF trigger) */
100178   Trigger *pTrigger;     /* List of triggers on pTab, if required */
100179   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100180 #endif
100181   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
100182
100183   /* Register Allocations */
100184   int regRowCount = 0;   /* A count of rows changed */
100185   int regOldRowid;       /* The old rowid */
100186   int regNewRowid;       /* The new rowid */
100187   int regNew;
100188   int regOld = 0;
100189   int regRowSet = 0;     /* Rowset of rows to be updated */
100190
100191   memset(&sContext, 0, sizeof(sContext));
100192   db = pParse->db;
100193   if( pParse->nErr || db->mallocFailed ){
100194     goto update_cleanup;
100195   }
100196   assert( pTabList->nSrc==1 );
100197
100198   /* Locate the table which we want to update. 
100199   */
100200   pTab = sqlcipher3SrcListLookup(pParse, pTabList);
100201   if( pTab==0 ) goto update_cleanup;
100202   iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
100203
100204   /* Figure out if we have any triggers and if the table being
100205   ** updated is a view.
100206   */
100207 #ifndef SQLCIPHER_OMIT_TRIGGER
100208   pTrigger = sqlcipher3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
100209   isView = pTab->pSelect!=0;
100210   assert( pTrigger || tmask==0 );
100211 #else
100212 # define pTrigger 0
100213 # define isView 0
100214 # define tmask 0
100215 #endif
100216 #ifdef SQLCIPHER_OMIT_VIEW
100217 # undef isView
100218 # define isView 0
100219 #endif
100220
100221   if( sqlcipher3ViewGetColumnNames(pParse, pTab) ){
100222     goto update_cleanup;
100223   }
100224   if( sqlcipher3IsReadOnly(pParse, pTab, tmask) ){
100225     goto update_cleanup;
100226   }
100227   aXRef = sqlcipher3DbMallocRaw(db, sizeof(int) * pTab->nCol );
100228   if( aXRef==0 ) goto update_cleanup;
100229   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
100230
100231   /* Allocate a cursors for the main database table and for all indices.
100232   ** The index cursors might not be used, but if they are used they
100233   ** need to occur right after the database cursor.  So go ahead and
100234   ** allocate enough space, just in case.
100235   */
100236   pTabList->a[0].iCursor = iCur = pParse->nTab++;
100237   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100238     pParse->nTab++;
100239   }
100240
100241   /* Initialize the name-context */
100242   memset(&sNC, 0, sizeof(sNC));
100243   sNC.pParse = pParse;
100244   sNC.pSrcList = pTabList;
100245
100246   /* Resolve the column names in all the expressions of the
100247   ** of the UPDATE statement.  Also find the column index
100248   ** for each column to be updated in the pChanges array.  For each
100249   ** column to be updated, make sure we have authorization to change
100250   ** that column.
100251   */
100252   chngRowid = 0;
100253   for(i=0; i<pChanges->nExpr; i++){
100254     if( sqlcipher3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
100255       goto update_cleanup;
100256     }
100257     for(j=0; j<pTab->nCol; j++){
100258       if( sqlcipher3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
100259         if( j==pTab->iPKey ){
100260           chngRowid = 1;
100261           pRowidExpr = pChanges->a[i].pExpr;
100262         }
100263         aXRef[j] = i;
100264         break;
100265       }
100266     }
100267     if( j>=pTab->nCol ){
100268       if( sqlcipher3IsRowid(pChanges->a[i].zName) ){
100269         chngRowid = 1;
100270         pRowidExpr = pChanges->a[i].pExpr;
100271       }else{
100272         sqlcipher3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
100273         pParse->checkSchema = 1;
100274         goto update_cleanup;
100275       }
100276     }
100277 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
100278     {
100279       int rc;
100280       rc = sqlcipher3AuthCheck(pParse, SQLCIPHER_UPDATE, pTab->zName,
100281                            pTab->aCol[j].zName, db->aDb[iDb].zName);
100282       if( rc==SQLCIPHER_DENY ){
100283         goto update_cleanup;
100284       }else if( rc==SQLCIPHER_IGNORE ){
100285         aXRef[j] = -1;
100286       }
100287     }
100288 #endif
100289   }
100290
100291   hasFK = sqlcipher3FkRequired(pParse, pTab, aXRef, chngRowid);
100292
100293   /* Allocate memory for the array aRegIdx[].  There is one entry in the
100294   ** array for each index associated with table being updated.  Fill in
100295   ** the value with a register number for indices that are to be used
100296   ** and with zero for unused indices.
100297   */
100298   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
100299   if( nIdx>0 ){
100300     aRegIdx = sqlcipher3DbMallocRaw(db, sizeof(Index*) * nIdx );
100301     if( aRegIdx==0 ) goto update_cleanup;
100302   }
100303   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
100304     int reg;
100305     if( hasFK || chngRowid ){
100306       reg = ++pParse->nMem;
100307     }else{
100308       reg = 0;
100309       for(i=0; i<pIdx->nColumn; i++){
100310         if( aXRef[pIdx->aiColumn[i]]>=0 ){
100311           reg = ++pParse->nMem;
100312           break;
100313         }
100314       }
100315     }
100316     aRegIdx[j] = reg;
100317   }
100318
100319   /* Begin generating code. */
100320   v = sqlcipher3GetVdbe(pParse);
100321   if( v==0 ) goto update_cleanup;
100322   if( pParse->nested==0 ) sqlcipher3VdbeCountChanges(v);
100323   sqlcipher3BeginWriteOperation(pParse, 1, iDb);
100324
100325 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
100326   /* Virtual tables must be handled separately */
100327   if( IsVirtual(pTab) ){
100328     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
100329                        pWhere, onError);
100330     pWhere = 0;
100331     pTabList = 0;
100332     goto update_cleanup;
100333   }
100334 #endif
100335
100336   /* Allocate required registers. */
100337   regOldRowid = regNewRowid = ++pParse->nMem;
100338   if( pTrigger || hasFK ){
100339     regOld = pParse->nMem + 1;
100340     pParse->nMem += pTab->nCol;
100341   }
100342   if( chngRowid || pTrigger || hasFK ){
100343     regNewRowid = ++pParse->nMem;
100344   }
100345   regNew = pParse->nMem + 1;
100346   pParse->nMem += pTab->nCol;
100347
100348   /* Start the view context. */
100349   if( isView ){
100350     sqlcipher3AuthContextPush(pParse, &sContext, pTab->zName);
100351   }
100352
100353   /* If we are trying to update a view, realize that view into
100354   ** a ephemeral table.
100355   */
100356 #if !defined(SQLCIPHER_OMIT_VIEW) && !defined(SQLCIPHER_OMIT_TRIGGER)
100357   if( isView ){
100358     sqlcipher3MaterializeView(pParse, pTab, pWhere, iCur);
100359   }
100360 #endif
100361
100362   /* Resolve the column names in all the expressions in the
100363   ** WHERE clause.
100364   */
100365   if( sqlcipher3ResolveExprNames(&sNC, pWhere) ){
100366     goto update_cleanup;
100367   }
100368
100369   /* Begin the database scan
100370   */
100371   sqlcipher3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
100372   pWInfo = sqlcipher3WhereBegin(
100373       pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED
100374   );
100375   if( pWInfo==0 ) goto update_cleanup;
100376   okOnePass = pWInfo->okOnePass;
100377
100378   /* Remember the rowid of every item to be updated.
100379   */
100380   sqlcipher3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
100381   if( !okOnePass ){
100382     regRowSet = ++pParse->nMem;
100383     sqlcipher3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
100384   }
100385
100386   /* End the database scan loop.
100387   */
100388   sqlcipher3WhereEnd(pWInfo);
100389
100390   /* Initialize the count of updated rows
100391   */
100392   if( (db->flags & SQLCIPHER_CountRows) && !pParse->pTriggerTab ){
100393     regRowCount = ++pParse->nMem;
100394     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
100395   }
100396
100397   if( !isView ){
100398     /* 
100399     ** Open every index that needs updating.  Note that if any
100400     ** index could potentially invoke a REPLACE conflict resolution 
100401     ** action, then we need to open all indices because we might need
100402     ** to be deleting some records.
100403     */
100404     if( !okOnePass ) sqlcipher3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
100405     if( onError==OE_Replace ){
100406       openAll = 1;
100407     }else{
100408       openAll = 0;
100409       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100410         if( pIdx->onError==OE_Replace ){
100411           openAll = 1;
100412           break;
100413         }
100414       }
100415     }
100416     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
100417       assert( aRegIdx );
100418       if( openAll || aRegIdx[i]>0 ){
100419         KeyInfo *pKey = sqlcipher3IndexKeyinfo(pParse, pIdx);
100420         sqlcipher3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
100421                        (char*)pKey, P4_KEYINFO_HANDOFF);
100422         assert( pParse->nTab>iCur+i+1 );
100423       }
100424     }
100425   }
100426
100427   /* Top of the update loop */
100428   if( okOnePass ){
100429     int a1 = sqlcipher3VdbeAddOp1(v, OP_NotNull, regOldRowid);
100430     addr = sqlcipher3VdbeAddOp0(v, OP_Goto);
100431     sqlcipher3VdbeJumpHere(v, a1);
100432   }else{
100433     addr = sqlcipher3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
100434   }
100435
100436   /* Make cursor iCur point to the record that is being updated. If
100437   ** this record does not exist for some reason (deleted by a trigger,
100438   ** for example, then jump to the next iteration of the RowSet loop.  */
100439   sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
100440
100441   /* If the record number will change, set register regNewRowid to
100442   ** contain the new value. If the record number is not being modified,
100443   ** then regNewRowid is the same register as regOldRowid, which is
100444   ** already populated.  */
100445   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
100446   if( chngRowid ){
100447     sqlcipher3ExprCode(pParse, pRowidExpr, regNewRowid);
100448     sqlcipher3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
100449   }
100450
100451   /* If there are triggers on this table, populate an array of registers 
100452   ** with the required old.* column data.  */
100453   if( hasFK || pTrigger ){
100454     u32 oldmask = (hasFK ? sqlcipher3FkOldmask(pParse, pTab) : 0);
100455     oldmask |= sqlcipher3TriggerColmask(pParse, 
100456         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
100457     );
100458     for(i=0; i<pTab->nCol; i++){
100459       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
100460         sqlcipher3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
100461       }else{
100462         sqlcipher3VdbeAddOp2(v, OP_Null, 0, regOld+i);
100463       }
100464     }
100465     if( chngRowid==0 ){
100466       sqlcipher3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
100467     }
100468   }
100469
100470   /* Populate the array of registers beginning at regNew with the new
100471   ** row data. This array is used to check constaints, create the new
100472   ** table and index records, and as the values for any new.* references
100473   ** made by triggers.
100474   **
100475   ** If there are one or more BEFORE triggers, then do not populate the
100476   ** registers associated with columns that are (a) not modified by
100477   ** this UPDATE statement and (b) not accessed by new.* references. The
100478   ** values for registers not modified by the UPDATE must be reloaded from 
100479   ** the database after the BEFORE triggers are fired anyway (as the trigger 
100480   ** may have modified them). So not loading those that are not going to
100481   ** be used eliminates some redundant opcodes.
100482   */
100483   newmask = sqlcipher3TriggerColmask(
100484       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
100485   );
100486   for(i=0; i<pTab->nCol; i++){
100487     if( i==pTab->iPKey ){
100488       sqlcipher3VdbeAddOp2(v, OP_Null, 0, regNew+i);
100489     }else{
100490       j = aXRef[i];
100491       if( j>=0 ){
100492         sqlcipher3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
100493       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
100494         /* This branch loads the value of a column that will not be changed 
100495         ** into a register. This is done if there are no BEFORE triggers, or
100496         ** if there are one or more BEFORE triggers that use this value via
100497         ** a new.* reference in a trigger program.
100498         */
100499         testcase( i==31 );
100500         testcase( i==32 );
100501         sqlcipher3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
100502         sqlcipher3ColumnDefault(v, pTab, i, regNew+i);
100503       }
100504     }
100505   }
100506
100507   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
100508   ** verified. One could argue that this is wrong.
100509   */
100510   if( tmask&TRIGGER_BEFORE ){
100511     sqlcipher3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
100512     sqlcipher3TableAffinityStr(v, pTab);
100513     sqlcipher3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
100514         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
100515
100516     /* The row-trigger may have deleted the row being updated. In this
100517     ** case, jump to the next row. No updates or AFTER triggers are 
100518     ** required. This behaviour - what happens when the row being updated
100519     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
100520     ** documentation.
100521     */
100522     sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
100523
100524     /* If it did not delete it, the row-trigger may still have modified 
100525     ** some of the columns of the row being updated. Load the values for 
100526     ** all columns not modified by the update statement into their 
100527     ** registers in case this has happened.
100528     */
100529     for(i=0; i<pTab->nCol; i++){
100530       if( aXRef[i]<0 && i!=pTab->iPKey ){
100531         sqlcipher3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
100532         sqlcipher3ColumnDefault(v, pTab, i, regNew+i);
100533       }
100534     }
100535   }
100536
100537   if( !isView ){
100538     int j1;                       /* Address of jump instruction */
100539
100540     /* Do constraint checks. */
100541     sqlcipher3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
100542         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
100543
100544     /* Do FK constraint checks. */
100545     if( hasFK ){
100546       sqlcipher3FkCheck(pParse, pTab, regOldRowid, 0);
100547     }
100548
100549     /* Delete the index entries associated with the current record.  */
100550     j1 = sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
100551     sqlcipher3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
100552   
100553     /* If changing the record number, delete the old record.  */
100554     if( hasFK || chngRowid ){
100555       sqlcipher3VdbeAddOp2(v, OP_Delete, iCur, 0);
100556     }
100557     sqlcipher3VdbeJumpHere(v, j1);
100558
100559     if( hasFK ){
100560       sqlcipher3FkCheck(pParse, pTab, 0, regNewRowid);
100561     }
100562   
100563     /* Insert the new index entries and the new record. */
100564     sqlcipher3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
100565
100566     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
100567     ** handle rows (possibly in other tables) that refer via a foreign key
100568     ** to the row just updated. */ 
100569     if( hasFK ){
100570       sqlcipher3FkActions(pParse, pTab, pChanges, regOldRowid);
100571     }
100572   }
100573
100574   /* Increment the row counter 
100575   */
100576   if( (db->flags & SQLCIPHER_CountRows) && !pParse->pTriggerTab){
100577     sqlcipher3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
100578   }
100579
100580   sqlcipher3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
100581       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
100582
100583   /* Repeat the above with the next record to be updated, until
100584   ** all record selected by the WHERE clause have been updated.
100585   */
100586   sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addr);
100587   sqlcipher3VdbeJumpHere(v, addr);
100588
100589   /* Close all tables */
100590   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
100591     assert( aRegIdx );
100592     if( openAll || aRegIdx[i]>0 ){
100593       sqlcipher3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
100594     }
100595   }
100596   sqlcipher3VdbeAddOp2(v, OP_Close, iCur, 0);
100597
100598   /* Update the sqlcipher_sequence table by storing the content of the
100599   ** maximum rowid counter values recorded while inserting into
100600   ** autoincrement tables.
100601   */
100602   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
100603     sqlcipher3AutoincrementEnd(pParse);
100604   }
100605
100606   /*
100607   ** Return the number of rows that were changed. If this routine is 
100608   ** generating code because of a call to sqlcipher3NestedParse(), do not
100609   ** invoke the callback function.
100610   */
100611   if( (db->flags&SQLCIPHER_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
100612     sqlcipher3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
100613     sqlcipher3VdbeSetNumCols(v, 1);
100614     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLCIPHER_STATIC);
100615   }
100616
100617 update_cleanup:
100618   sqlcipher3AuthContextPop(&sContext);
100619   sqlcipher3DbFree(db, aRegIdx);
100620   sqlcipher3DbFree(db, aXRef);
100621   sqlcipher3SrcListDelete(db, pTabList);
100622   sqlcipher3ExprListDelete(db, pChanges);
100623   sqlcipher3ExprDelete(db, pWhere);
100624   return;
100625 }
100626 /* Make sure "isView" and other macros defined above are undefined. Otherwise
100627 ** thely may interfere with compilation of other functions in this file
100628 ** (or in another file, if this file becomes part of the amalgamation).  */
100629 #ifdef isView
100630  #undef isView
100631 #endif
100632 #ifdef pTrigger
100633  #undef pTrigger
100634 #endif
100635
100636 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
100637 /*
100638 ** Generate code for an UPDATE of a virtual table.
100639 **
100640 ** The strategy is that we create an ephemerial table that contains
100641 ** for each row to be changed:
100642 **
100643 **   (A)  The original rowid of that row.
100644 **   (B)  The revised rowid for the row. (note1)
100645 **   (C)  The content of every column in the row.
100646 **
100647 ** Then we loop over this ephemeral table and for each row in
100648 ** the ephermeral table call VUpdate.
100649 **
100650 ** When finished, drop the ephemeral table.
100651 **
100652 ** (note1) Actually, if we know in advance that (A) is always the same
100653 ** as (B) we only store (A), then duplicate (A) when pulling
100654 ** it out of the ephemeral table before calling VUpdate.
100655 */
100656 static void updateVirtualTable(
100657   Parse *pParse,       /* The parsing context */
100658   SrcList *pSrc,       /* The virtual table to be modified */
100659   Table *pTab,         /* The virtual table */
100660   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
100661   Expr *pRowid,        /* Expression used to recompute the rowid */
100662   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
100663   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
100664   int onError          /* ON CONFLICT strategy */
100665 ){
100666   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
100667   ExprList *pEList = 0;     /* The result set of the SELECT statement */
100668   Select *pSelect = 0;      /* The SELECT statement */
100669   Expr *pExpr;              /* Temporary expression */
100670   int ephemTab;             /* Table holding the result of the SELECT */
100671   int i;                    /* Loop counter */
100672   int addr;                 /* Address of top of loop */
100673   int iReg;                 /* First register in set passed to OP_VUpdate */
100674   sqlcipher3 *db = pParse->db; /* Database connection */
100675   const char *pVTab = (const char*)sqlcipher3GetVTable(db, pTab);
100676   SelectDest dest;
100677
100678   /* Construct the SELECT statement that will find the new values for
100679   ** all updated rows. 
100680   */
100681   pEList = sqlcipher3ExprListAppend(pParse, 0, sqlcipher3Expr(db, TK_ID, "_rowid_"));
100682   if( pRowid ){
100683     pEList = sqlcipher3ExprListAppend(pParse, pEList,
100684                                    sqlcipher3ExprDup(db, pRowid, 0));
100685   }
100686   assert( pTab->iPKey<0 );
100687   for(i=0; i<pTab->nCol; i++){
100688     if( aXRef[i]>=0 ){
100689       pExpr = sqlcipher3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
100690     }else{
100691       pExpr = sqlcipher3Expr(db, TK_ID, pTab->aCol[i].zName);
100692     }
100693     pEList = sqlcipher3ExprListAppend(pParse, pEList, pExpr);
100694   }
100695   pSelect = sqlcipher3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
100696   
100697   /* Create the ephemeral table into which the update results will
100698   ** be stored.
100699   */
100700   assert( v );
100701   ephemTab = pParse->nTab++;
100702   sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
100703   sqlcipher3VdbeChangeP5(v, BTREE_UNORDERED);
100704
100705   /* fill the ephemeral table 
100706   */
100707   sqlcipher3SelectDestInit(&dest, SRT_Table, ephemTab);
100708   sqlcipher3Select(pParse, pSelect, &dest);
100709
100710   /* Generate code to scan the ephemeral table and call VUpdate. */
100711   iReg = ++pParse->nMem;
100712   pParse->nMem += pTab->nCol+1;
100713   addr = sqlcipher3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
100714   sqlcipher3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
100715   sqlcipher3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
100716   for(i=0; i<pTab->nCol; i++){
100717     sqlcipher3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
100718   }
100719   sqlcipher3VtabMakeWritable(pParse, pTab);
100720   sqlcipher3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
100721   sqlcipher3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
100722   sqlcipher3MayAbort(pParse);
100723   sqlcipher3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
100724   sqlcipher3VdbeJumpHere(v, addr);
100725   sqlcipher3VdbeAddOp2(v, OP_Close, ephemTab, 0);
100726
100727   /* Cleanup */
100728   sqlcipher3SelectDelete(db, pSelect);  
100729 }
100730 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
100731
100732 /************** End of update.c **********************************************/
100733 /************** Begin file vacuum.c ******************************************/
100734 /*
100735 ** 2003 April 6
100736 **
100737 ** The author disclaims copyright to this source code.  In place of
100738 ** a legal notice, here is a blessing:
100739 **
100740 **    May you do good and not evil.
100741 **    May you find forgiveness for yourself and forgive others.
100742 **    May you share freely, never taking more than you give.
100743 **
100744 *************************************************************************
100745 ** This file contains code used to implement the VACUUM command.
100746 **
100747 ** Most of the code in this file may be omitted by defining the
100748 ** SQLCIPHER_OMIT_VACUUM macro.
100749 */
100750
100751 #if !defined(SQLCIPHER_OMIT_VACUUM) && !defined(SQLCIPHER_OMIT_ATTACH)
100752 /*
100753 ** Finalize a prepared statement.  If there was an error, store the
100754 ** text of the error message in *pzErrMsg.  Return the result code.
100755 */
100756 static int vacuumFinalize(sqlcipher3 *db, sqlcipher3_stmt *pStmt, char **pzErrMsg){
100757   int rc;
100758   rc = sqlcipher3VdbeFinalize((Vdbe*)pStmt);
100759   if( rc ){
100760     sqlcipher3SetString(pzErrMsg, db, sqlcipher3_errmsg(db));
100761   }
100762   return rc;
100763 }
100764
100765 /*
100766 ** Execute zSql on database db. Return an error code.
100767 */
100768 static int execSql(sqlcipher3 *db, char **pzErrMsg, const char *zSql){
100769   sqlcipher3_stmt *pStmt;
100770   VVA_ONLY( int rc; )
100771   if( !zSql ){
100772     return SQLCIPHER_NOMEM;
100773   }
100774   if( SQLCIPHER_OK!=sqlcipher3_prepare(db, zSql, -1, &pStmt, 0) ){
100775     sqlcipher3SetString(pzErrMsg, db, sqlcipher3_errmsg(db));
100776     return sqlcipher3_errcode(db);
100777   }
100778   VVA_ONLY( rc = ) sqlcipher3_step(pStmt);
100779   assert( rc!=SQLCIPHER_ROW || (db->flags&SQLCIPHER_CountRows) );
100780   return vacuumFinalize(db, pStmt, pzErrMsg);
100781 }
100782
100783 /*
100784 ** Execute zSql on database db. The statement returns exactly
100785 ** one column. Execute this as SQL on the same database.
100786 */
100787 static int execExecSql(sqlcipher3 *db, char **pzErrMsg, const char *zSql){
100788   sqlcipher3_stmt *pStmt;
100789   int rc;
100790
100791   rc = sqlcipher3_prepare(db, zSql, -1, &pStmt, 0);
100792   if( rc!=SQLCIPHER_OK ) return rc;
100793
100794   while( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
100795     rc = execSql(db, pzErrMsg, (char*)sqlcipher3_column_text(pStmt, 0));
100796     if( rc!=SQLCIPHER_OK ){
100797       vacuumFinalize(db, pStmt, pzErrMsg);
100798       return rc;
100799     }
100800   }
100801
100802   return vacuumFinalize(db, pStmt, pzErrMsg);
100803 }
100804
100805 /*
100806 ** The non-standard VACUUM command is used to clean up the database,
100807 ** collapse free space, etc.  It is modelled after the VACUUM command
100808 ** in PostgreSQL.
100809 **
100810 ** In version 1.0.x of SQLite, the VACUUM command would call
100811 ** gdbm_reorganize() on all the database tables.  But beginning
100812 ** with 2.0.0, SQLite no longer uses GDBM so this command has
100813 ** become a no-op.
100814 */
100815 SQLCIPHER_PRIVATE void sqlcipher3Vacuum(Parse *pParse){
100816   Vdbe *v = sqlcipher3GetVdbe(pParse);
100817   if( v ){
100818     sqlcipher3VdbeAddOp2(v, OP_Vacuum, 0, 0);
100819   }
100820   return;
100821 }
100822
100823 /*
100824 ** This routine implements the OP_Vacuum opcode of the VDBE.
100825 */
100826 SQLCIPHER_PRIVATE int sqlcipher3RunVacuum(char **pzErrMsg, sqlcipher3 *db){
100827   int rc = SQLCIPHER_OK;     /* Return code from service routines */
100828   Btree *pMain;           /* The database being vacuumed */
100829   Btree *pTemp;           /* The temporary database we vacuum into */
100830   char *zSql = 0;         /* SQL statements */
100831   int saved_flags;        /* Saved value of the db->flags */
100832   int saved_nChange;      /* Saved value of db->nChange */
100833   int saved_nTotalChange; /* Saved value of db->nTotalChange */
100834   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
100835   Db *pDb = 0;            /* Database to detach at end of vacuum */
100836   int isMemDb;            /* True if vacuuming a :memory: database */
100837   int nRes;               /* Bytes of reserved space at the end of each page */
100838   int nDb;                /* Number of attached databases */
100839
100840   if( !db->autoCommit ){
100841     sqlcipher3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
100842     return SQLCIPHER_ERROR;
100843   }
100844   if( db->activeVdbeCnt>1 ){
100845     sqlcipher3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
100846     return SQLCIPHER_ERROR;
100847   }
100848
100849   /* Save the current value of the database flags so that it can be 
100850   ** restored before returning. Then set the writable-schema flag, and
100851   ** disable CHECK and foreign key constraints.  */
100852   saved_flags = db->flags;
100853   saved_nChange = db->nChange;
100854   saved_nTotalChange = db->nTotalChange;
100855   saved_xTrace = db->xTrace;
100856   db->flags |= SQLCIPHER_WriteSchema | SQLCIPHER_IgnoreChecks | SQLCIPHER_PreferBuiltin;
100857   db->flags &= ~(SQLCIPHER_ForeignKeys | SQLCIPHER_ReverseOrder);
100858   db->xTrace = 0;
100859
100860   pMain = db->aDb[0].pBt;
100861   isMemDb = sqlcipher3PagerIsMemdb(sqlcipher3BtreePager(pMain));
100862
100863   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
100864   ** can be set to 'off' for this file, as it is not recovered if a crash
100865   ** occurs anyway. The integrity of the database is maintained by a
100866   ** (possibly synchronous) transaction opened on the main database before
100867   ** sqlcipher3BtreeCopyFile() is called.
100868   **
100869   ** An optimisation would be to use a non-journaled pager.
100870   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
100871   ** that actually made the VACUUM run slower.  Very little journalling
100872   ** actually occurs when doing a vacuum since the vacuum_db is initially
100873   ** empty.  Only the journal header is written.  Apparently it takes more
100874   ** time to parse and run the PRAGMA to turn journalling off than it does
100875   ** to write the journal header file.
100876   */
100877   nDb = db->nDb;
100878   if( sqlcipher3TempInMemory(db) ){
100879     zSql = "ATTACH ':memory:' AS vacuum_db;";
100880   }else{
100881     zSql = "ATTACH '' AS vacuum_db;";
100882   }
100883   rc = execSql(db, pzErrMsg, zSql);
100884   if( db->nDb>nDb ){
100885     pDb = &db->aDb[db->nDb-1];
100886     assert( strcmp(pDb->zName,"vacuum_db")==0 );
100887   }
100888   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100889   pTemp = db->aDb[db->nDb-1].pBt;
100890
100891   /* The call to execSql() to attach the temp database has left the file
100892   ** locked (as there was more than one active statement when the transaction
100893   ** to read the schema was concluded. Unlock it here so that this doesn't
100894   ** cause problems for the call to BtreeSetPageSize() below.  */
100895   sqlcipher3BtreeCommit(pTemp);
100896
100897   nRes = sqlcipher3BtreeGetReserve(pMain);
100898
100899   /* A VACUUM cannot change the pagesize of an encrypted database. */
100900 #ifdef SQLCIPHER_HAS_CODEC
100901   if( db->nextPagesize ){
100902     extern void sqlcipher3CodecGetKey(sqlcipher3*, int, void**, int*);
100903     int nKey = 0;
100904     char *zKey = NULL;
100905     sqlcipher3CodecGetKey(db, 0, (void**)&zKey, &nKey);
100906     if( nKey ) db->nextPagesize = 0;
100907   }
100908 #endif
100909
100910   /* Do not attempt to change the page size for a WAL database */
100911   if( sqlcipher3PagerGetJournalMode(sqlcipher3BtreePager(pMain))
100912                                                ==PAGER_JOURNALMODE_WAL ){
100913     db->nextPagesize = 0;
100914   }
100915
100916   if( sqlcipher3BtreeSetPageSize(pTemp, sqlcipher3BtreeGetPageSize(pMain), nRes, 0)
100917    || (!isMemDb && sqlcipher3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
100918    || NEVER(db->mallocFailed)
100919   ){
100920     rc = SQLCIPHER_NOMEM;
100921     goto end_of_vacuum;
100922   }
100923   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
100924   if( rc!=SQLCIPHER_OK ){
100925     goto end_of_vacuum;
100926   }
100927
100928 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
100929   sqlcipher3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
100930                                            sqlcipher3BtreeGetAutoVacuum(pMain));
100931 #endif
100932
100933   /* Begin a transaction */
100934   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
100935   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100936
100937   /* Query the schema of the main database. Create a mirror schema
100938   ** in the temporary database.
100939   */
100940   rc = execExecSql(db, pzErrMsg,
100941       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
100942       "  FROM sqlcipher_master WHERE type='table' AND name!='sqlcipher_sequence'"
100943       "   AND rootpage>0"
100944   );
100945   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100946   rc = execExecSql(db, pzErrMsg,
100947       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
100948       "  FROM sqlcipher_master WHERE sql LIKE 'CREATE INDEX %' ");
100949   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100950   rc = execExecSql(db, pzErrMsg,
100951       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
100952       "  FROM sqlcipher_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
100953   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100954
100955   /* Loop through the tables in the main database. For each, do
100956   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
100957   ** the contents to the temporary database.
100958   */
100959   rc = execExecSql(db, pzErrMsg,
100960       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
100961       "|| ' SELECT * FROM main.' || quote(name) || ';'"
100962       "FROM main.sqlcipher_master "
100963       "WHERE type = 'table' AND name!='sqlcipher_sequence' "
100964       "  AND rootpage>0"
100965   );
100966   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100967
100968   /* Copy over the sequence table
100969   */
100970   rc = execExecSql(db, pzErrMsg,
100971       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
100972       "FROM vacuum_db.sqlcipher_master WHERE name='sqlcipher_sequence' "
100973   );
100974   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100975   rc = execExecSql(db, pzErrMsg,
100976       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
100977       "|| ' SELECT * FROM main.' || quote(name) || ';' "
100978       "FROM vacuum_db.sqlcipher_master WHERE name=='sqlcipher_sequence';"
100979   );
100980   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100981
100982
100983   /* Copy the triggers, views, and virtual tables from the main database
100984   ** over to the temporary database.  None of these objects has any
100985   ** associated storage, so all we have to do is copy their entries
100986   ** from the SQLCIPHER_MASTER table.
100987   */
100988   rc = execSql(db, pzErrMsg,
100989       "INSERT INTO vacuum_db.sqlcipher_master "
100990       "  SELECT type, name, tbl_name, rootpage, sql"
100991       "    FROM main.sqlcipher_master"
100992       "   WHERE type='view' OR type='trigger'"
100993       "      OR (type='table' AND rootpage=0)"
100994   );
100995   if( rc ) goto end_of_vacuum;
100996
100997   /* At this point, there is a write transaction open on both the 
100998   ** vacuum database and the main database. Assuming no error occurs,
100999   ** both transactions are closed by this block - the main database
101000   ** transaction by sqlcipher3BtreeCopyFile() and the other by an explicit
101001   ** call to sqlcipher3BtreeCommit().
101002   */
101003   {
101004     u32 meta;
101005     int i;
101006
101007     /* This array determines which meta meta values are preserved in the
101008     ** vacuum.  Even entries are the meta value number and odd entries
101009     ** are an increment to apply to the meta value after the vacuum.
101010     ** The increment is used to increase the schema cookie so that other
101011     ** connections to the same database will know to reread the schema.
101012     */
101013     static const unsigned char aCopy[] = {
101014        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
101015        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
101016        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
101017        BTREE_USER_VERSION,       0,  /* Preserve the user version */
101018     };
101019
101020     assert( 1==sqlcipher3BtreeIsInTrans(pTemp) );
101021     assert( 1==sqlcipher3BtreeIsInTrans(pMain) );
101022
101023     /* Copy Btree meta values */
101024     for(i=0; i<ArraySize(aCopy); i+=2){
101025       /* GetMeta() and UpdateMeta() cannot fail in this context because
101026       ** we already have page 1 loaded into cache and marked dirty. */
101027       sqlcipher3BtreeGetMeta(pMain, aCopy[i], &meta);
101028       rc = sqlcipher3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
101029       if( NEVER(rc!=SQLCIPHER_OK) ) goto end_of_vacuum;
101030     }
101031
101032     rc = sqlcipher3BtreeCopyFile(pMain, pTemp);
101033     if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
101034     rc = sqlcipher3BtreeCommit(pTemp);
101035     if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
101036 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
101037     sqlcipher3BtreeSetAutoVacuum(pMain, sqlcipher3BtreeGetAutoVacuum(pTemp));
101038 #endif
101039   }
101040
101041   assert( rc==SQLCIPHER_OK );
101042   rc = sqlcipher3BtreeSetPageSize(pMain, sqlcipher3BtreeGetPageSize(pTemp), nRes,1);
101043
101044 end_of_vacuum:
101045   /* Restore the original value of db->flags */
101046   db->flags = saved_flags;
101047   db->nChange = saved_nChange;
101048   db->nTotalChange = saved_nTotalChange;
101049   db->xTrace = saved_xTrace;
101050   sqlcipher3BtreeSetPageSize(pMain, -1, -1, 1);
101051
101052   /* Currently there is an SQL level transaction open on the vacuum
101053   ** database. No locks are held on any other files (since the main file
101054   ** was committed at the btree level). So it safe to end the transaction
101055   ** by manually setting the autoCommit flag to true and detaching the
101056   ** vacuum database. The vacuum_db journal file is deleted when the pager
101057   ** is closed by the DETACH.
101058   */
101059   db->autoCommit = 1;
101060
101061   if( pDb ){
101062     sqlcipher3BtreeClose(pDb->pBt);
101063     pDb->pBt = 0;
101064     pDb->pSchema = 0;
101065   }
101066
101067   /* This both clears the schemas and reduces the size of the db->aDb[]
101068   ** array. */ 
101069   sqlcipher3ResetInternalSchema(db, -1);
101070
101071   return rc;
101072 }
101073
101074 #endif  /* SQLCIPHER_OMIT_VACUUM && SQLCIPHER_OMIT_ATTACH */
101075
101076 /************** End of vacuum.c **********************************************/
101077 /************** Begin file vtab.c ********************************************/
101078 /*
101079 ** 2006 June 10
101080 **
101081 ** The author disclaims copyright to this source code.  In place of
101082 ** a legal notice, here is a blessing:
101083 **
101084 **    May you do good and not evil.
101085 **    May you find forgiveness for yourself and forgive others.
101086 **    May you share freely, never taking more than you give.
101087 **
101088 *************************************************************************
101089 ** This file contains code used to help implement virtual tables.
101090 */
101091 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
101092
101093 /*
101094 ** Before a virtual table xCreate() or xConnect() method is invoked, the
101095 ** sqlcipher3.pVtabCtx member variable is set to point to an instance of
101096 ** this struct allocated on the stack. It is used by the implementation of 
101097 ** the sqlcipher3_declare_vtab() and sqlcipher3_vtab_config() APIs, both of which
101098 ** are invoked only from within xCreate and xConnect methods.
101099 */
101100 struct VtabCtx {
101101   Table *pTab;
101102   VTable *pVTable;
101103 };
101104
101105 /*
101106 ** The actual function that does the work of creating a new module.
101107 ** This function implements the sqlcipher3_create_module() and
101108 ** sqlcipher3_create_module_v2() interfaces.
101109 */
101110 static int createModule(
101111   sqlcipher3 *db,                    /* Database in which module is registered */
101112   const char *zName,              /* Name assigned to this module */
101113   const sqlcipher3_module *pModule,  /* The definition of the module */
101114   void *pAux,                     /* Context pointer for xCreate/xConnect */
101115   void (*xDestroy)(void *)        /* Module destructor function */
101116 ){
101117   int rc, nName;
101118   Module *pMod;
101119
101120   sqlcipher3_mutex_enter(db->mutex);
101121   nName = sqlcipher3Strlen30(zName);
101122   pMod = (Module *)sqlcipher3DbMallocRaw(db, sizeof(Module) + nName + 1);
101123   if( pMod ){
101124     Module *pDel;
101125     char *zCopy = (char *)(&pMod[1]);
101126     memcpy(zCopy, zName, nName+1);
101127     pMod->zName = zCopy;
101128     pMod->pModule = pModule;
101129     pMod->pAux = pAux;
101130     pMod->xDestroy = xDestroy;
101131     pDel = (Module *)sqlcipher3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
101132     if( pDel && pDel->xDestroy ){
101133       sqlcipher3ResetInternalSchema(db, -1);
101134       pDel->xDestroy(pDel->pAux);
101135     }
101136     sqlcipher3DbFree(db, pDel);
101137     if( pDel==pMod ){
101138       db->mallocFailed = 1;
101139     }
101140   }else if( xDestroy ){
101141     xDestroy(pAux);
101142   }
101143   rc = sqlcipher3ApiExit(db, SQLCIPHER_OK);
101144   sqlcipher3_mutex_leave(db->mutex);
101145   return rc;
101146 }
101147
101148
101149 /*
101150 ** External API function used to create a new virtual-table module.
101151 */
101152 SQLCIPHER_API int sqlcipher3_create_module(
101153   sqlcipher3 *db,                    /* Database in which module is registered */
101154   const char *zName,              /* Name assigned to this module */
101155   const sqlcipher3_module *pModule,  /* The definition of the module */
101156   void *pAux                      /* Context pointer for xCreate/xConnect */
101157 ){
101158   return createModule(db, zName, pModule, pAux, 0);
101159 }
101160
101161 /*
101162 ** External API function used to create a new virtual-table module.
101163 */
101164 SQLCIPHER_API int sqlcipher3_create_module_v2(
101165   sqlcipher3 *db,                    /* Database in which module is registered */
101166   const char *zName,              /* Name assigned to this module */
101167   const sqlcipher3_module *pModule,  /* The definition of the module */
101168   void *pAux,                     /* Context pointer for xCreate/xConnect */
101169   void (*xDestroy)(void *)        /* Module destructor function */
101170 ){
101171   return createModule(db, zName, pModule, pAux, xDestroy);
101172 }
101173
101174 /*
101175 ** Lock the virtual table so that it cannot be disconnected.
101176 ** Locks nest.  Every lock should have a corresponding unlock.
101177 ** If an unlock is omitted, resources leaks will occur.  
101178 **
101179 ** If a disconnect is attempted while a virtual table is locked,
101180 ** the disconnect is deferred until all locks have been removed.
101181 */
101182 SQLCIPHER_PRIVATE void sqlcipher3VtabLock(VTable *pVTab){
101183   pVTab->nRef++;
101184 }
101185
101186
101187 /*
101188 ** pTab is a pointer to a Table structure representing a virtual-table.
101189 ** Return a pointer to the VTable object used by connection db to access 
101190 ** this virtual-table, if one has been created, or NULL otherwise.
101191 */
101192 SQLCIPHER_PRIVATE VTable *sqlcipher3GetVTable(sqlcipher3 *db, Table *pTab){
101193   VTable *pVtab;
101194   assert( IsVirtual(pTab) );
101195   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
101196   return pVtab;
101197 }
101198
101199 /*
101200 ** Decrement the ref-count on a virtual table object. When the ref-count
101201 ** reaches zero, call the xDisconnect() method to delete the object.
101202 */
101203 SQLCIPHER_PRIVATE void sqlcipher3VtabUnlock(VTable *pVTab){
101204   sqlcipher3 *db = pVTab->db;
101205
101206   assert( db );
101207   assert( pVTab->nRef>0 );
101208   assert( sqlcipher3SafetyCheckOk(db) );
101209
101210   pVTab->nRef--;
101211   if( pVTab->nRef==0 ){
101212     sqlcipher3_vtab *p = pVTab->pVtab;
101213     if( p ){
101214       p->pModule->xDisconnect(p);
101215     }
101216     sqlcipher3DbFree(db, pVTab);
101217   }
101218 }
101219
101220 /*
101221 ** Table p is a virtual table. This function moves all elements in the
101222 ** p->pVTable list to the sqlcipher3.pDisconnect lists of their associated
101223 ** database connections to be disconnected at the next opportunity. 
101224 ** Except, if argument db is not NULL, then the entry associated with
101225 ** connection db is left in the p->pVTable list.
101226 */
101227 static VTable *vtabDisconnectAll(sqlcipher3 *db, Table *p){
101228   VTable *pRet = 0;
101229   VTable *pVTable = p->pVTable;
101230   p->pVTable = 0;
101231
101232   /* Assert that the mutex (if any) associated with the BtShared database 
101233   ** that contains table p is held by the caller. See header comments 
101234   ** above function sqlcipher3VtabUnlockList() for an explanation of why
101235   ** this makes it safe to access the sqlcipher3.pDisconnect list of any
101236   ** database connection that may have an entry in the p->pVTable list.
101237   */
101238   assert( db==0 || sqlcipher3SchemaMutexHeld(db, 0, p->pSchema) );
101239
101240   while( pVTable ){
101241     sqlcipher3 *db2 = pVTable->db;
101242     VTable *pNext = pVTable->pNext;
101243     assert( db2 );
101244     if( db2==db ){
101245       pRet = pVTable;
101246       p->pVTable = pRet;
101247       pRet->pNext = 0;
101248     }else{
101249       pVTable->pNext = db2->pDisconnect;
101250       db2->pDisconnect = pVTable;
101251     }
101252     pVTable = pNext;
101253   }
101254
101255   assert( !db || pRet );
101256   return pRet;
101257 }
101258
101259
101260 /*
101261 ** Disconnect all the virtual table objects in the sqlcipher3.pDisconnect list.
101262 **
101263 ** This function may only be called when the mutexes associated with all
101264 ** shared b-tree databases opened using connection db are held by the 
101265 ** caller. This is done to protect the sqlcipher3.pDisconnect list. The
101266 ** sqlcipher3.pDisconnect list is accessed only as follows:
101267 **
101268 **   1) By this function. In this case, all BtShared mutexes and the mutex
101269 **      associated with the database handle itself must be held.
101270 **
101271 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
101272 **      the sqlcipher3.pDisconnect list. In this case either the BtShared mutex
101273 **      associated with the database the virtual table is stored in is held
101274 **      or, if the virtual table is stored in a non-sharable database, then
101275 **      the database handle mutex is held.
101276 **
101277 ** As a result, a sqlcipher3.pDisconnect cannot be accessed simultaneously 
101278 ** by multiple threads. It is thread-safe.
101279 */
101280 SQLCIPHER_PRIVATE void sqlcipher3VtabUnlockList(sqlcipher3 *db){
101281   VTable *p = db->pDisconnect;
101282   db->pDisconnect = 0;
101283
101284   assert( sqlcipher3BtreeHoldsAllMutexes(db) );
101285   assert( sqlcipher3_mutex_held(db->mutex) );
101286
101287   if( p ){
101288     sqlcipher3ExpirePreparedStatements(db);
101289     do {
101290       VTable *pNext = p->pNext;
101291       sqlcipher3VtabUnlock(p);
101292       p = pNext;
101293     }while( p );
101294   }
101295 }
101296
101297 /*
101298 ** Clear any and all virtual-table information from the Table record.
101299 ** This routine is called, for example, just before deleting the Table
101300 ** record.
101301 **
101302 ** Since it is a virtual-table, the Table structure contains a pointer
101303 ** to the head of a linked list of VTable structures. Each VTable 
101304 ** structure is associated with a single sqlcipher3* user of the schema.
101305 ** The reference count of the VTable structure associated with database 
101306 ** connection db is decremented immediately (which may lead to the 
101307 ** structure being xDisconnected and free). Any other VTable structures
101308 ** in the list are moved to the sqlcipher3.pDisconnect list of the associated 
101309 ** database connection.
101310 */
101311 SQLCIPHER_PRIVATE void sqlcipher3VtabClear(sqlcipher3 *db, Table *p){
101312   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
101313   if( p->azModuleArg ){
101314     int i;
101315     for(i=0; i<p->nModuleArg; i++){
101316       sqlcipher3DbFree(db, p->azModuleArg[i]);
101317     }
101318     sqlcipher3DbFree(db, p->azModuleArg);
101319   }
101320 }
101321
101322 /*
101323 ** Add a new module argument to pTable->azModuleArg[].
101324 ** The string is not copied - the pointer is stored.  The
101325 ** string will be freed automatically when the table is
101326 ** deleted.
101327 */
101328 static void addModuleArgument(sqlcipher3 *db, Table *pTable, char *zArg){
101329   int i = pTable->nModuleArg++;
101330   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
101331   char **azModuleArg;
101332   azModuleArg = sqlcipher3DbRealloc(db, pTable->azModuleArg, nBytes);
101333   if( azModuleArg==0 ){
101334     int j;
101335     for(j=0; j<i; j++){
101336       sqlcipher3DbFree(db, pTable->azModuleArg[j]);
101337     }
101338     sqlcipher3DbFree(db, zArg);
101339     sqlcipher3DbFree(db, pTable->azModuleArg);
101340     pTable->nModuleArg = 0;
101341   }else{
101342     azModuleArg[i] = zArg;
101343     azModuleArg[i+1] = 0;
101344   }
101345   pTable->azModuleArg = azModuleArg;
101346 }
101347
101348 /*
101349 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
101350 ** statement.  The module name has been parsed, but the optional list
101351 ** of parameters that follow the module name are still pending.
101352 */
101353 SQLCIPHER_PRIVATE void sqlcipher3VtabBeginParse(
101354   Parse *pParse,        /* Parsing context */
101355   Token *pName1,        /* Name of new table, or database name */
101356   Token *pName2,        /* Name of new table or NULL */
101357   Token *pModuleName    /* Name of the module for the virtual table */
101358 ){
101359   int iDb;              /* The database the table is being created in */
101360   Table *pTable;        /* The new virtual table */
101361   sqlcipher3 *db;          /* Database connection */
101362
101363   sqlcipher3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
101364   pTable = pParse->pNewTable;
101365   if( pTable==0 ) return;
101366   assert( 0==pTable->pIndex );
101367
101368   db = pParse->db;
101369   iDb = sqlcipher3SchemaToIndex(db, pTable->pSchema);
101370   assert( iDb>=0 );
101371
101372   pTable->tabFlags |= TF_Virtual;
101373   pTable->nModuleArg = 0;
101374   addModuleArgument(db, pTable, sqlcipher3NameFromToken(db, pModuleName));
101375   addModuleArgument(db, pTable, sqlcipher3DbStrDup(db, db->aDb[iDb].zName));
101376   addModuleArgument(db, pTable, sqlcipher3DbStrDup(db, pTable->zName));
101377   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
101378
101379 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
101380   /* Creating a virtual table invokes the authorization callback twice.
101381   ** The first invocation, to obtain permission to INSERT a row into the
101382   ** sqlcipher_master table, has already been made by sqlcipher3StartTable().
101383   ** The second call, to obtain permission to create the table, is made now.
101384   */
101385   if( pTable->azModuleArg ){
101386     sqlcipher3AuthCheck(pParse, SQLCIPHER_CREATE_VTABLE, pTable->zName, 
101387             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
101388   }
101389 #endif
101390 }
101391
101392 /*
101393 ** This routine takes the module argument that has been accumulating
101394 ** in pParse->zArg[] and appends it to the list of arguments on the
101395 ** virtual table currently under construction in pParse->pTable.
101396 */
101397 static void addArgumentToVtab(Parse *pParse){
101398   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
101399     const char *z = (const char*)pParse->sArg.z;
101400     int n = pParse->sArg.n;
101401     sqlcipher3 *db = pParse->db;
101402     addModuleArgument(db, pParse->pNewTable, sqlcipher3DbStrNDup(db, z, n));
101403   }
101404 }
101405
101406 /*
101407 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
101408 ** has been completely parsed.
101409 */
101410 SQLCIPHER_PRIVATE void sqlcipher3VtabFinishParse(Parse *pParse, Token *pEnd){
101411   Table *pTab = pParse->pNewTable;  /* The table being constructed */
101412   sqlcipher3 *db = pParse->db;         /* The database connection */
101413
101414   if( pTab==0 ) return;
101415   addArgumentToVtab(pParse);
101416   pParse->sArg.z = 0;
101417   if( pTab->nModuleArg<1 ) return;
101418   
101419   /* If the CREATE VIRTUAL TABLE statement is being entered for the
101420   ** first time (in other words if the virtual table is actually being
101421   ** created now instead of just being read out of sqlcipher_master) then
101422   ** do additional initialization work and store the statement text
101423   ** in the sqlcipher_master table.
101424   */
101425   if( !db->init.busy ){
101426     char *zStmt;
101427     char *zWhere;
101428     int iDb;
101429     Vdbe *v;
101430
101431     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
101432     if( pEnd ){
101433       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
101434     }
101435     zStmt = sqlcipher3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
101436
101437     /* A slot for the record has already been allocated in the 
101438     ** SQLCIPHER_MASTER table.  We just need to update that slot with all
101439     ** the information we've collected.  
101440     **
101441     ** The VM register number pParse->regRowid holds the rowid of an
101442     ** entry in the sqlcipher_master table tht was created for this vtab
101443     ** by sqlcipher3StartTable().
101444     */
101445     iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
101446     sqlcipher3NestedParse(pParse,
101447       "UPDATE %Q.%s "
101448          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
101449        "WHERE rowid=#%d",
101450       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
101451       pTab->zName,
101452       pTab->zName,
101453       zStmt,
101454       pParse->regRowid
101455     );
101456     sqlcipher3DbFree(db, zStmt);
101457     v = sqlcipher3GetVdbe(pParse);
101458     sqlcipher3ChangeCookie(pParse, iDb);
101459
101460     sqlcipher3VdbeAddOp2(v, OP_Expire, 0, 0);
101461     zWhere = sqlcipher3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
101462     sqlcipher3VdbeAddParseSchemaOp(v, iDb, zWhere);
101463     sqlcipher3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
101464                          pTab->zName, sqlcipher3Strlen30(pTab->zName) + 1);
101465   }
101466
101467   /* If we are rereading the sqlcipher_master table create the in-memory
101468   ** record of the table. The xConnect() method is not called until
101469   ** the first time the virtual table is used in an SQL statement. This
101470   ** allows a schema that contains virtual tables to be loaded before
101471   ** the required virtual table implementations are registered.  */
101472   else {
101473     Table *pOld;
101474     Schema *pSchema = pTab->pSchema;
101475     const char *zName = pTab->zName;
101476     int nName = sqlcipher3Strlen30(zName);
101477     assert( sqlcipher3SchemaMutexHeld(db, 0, pSchema) );
101478     pOld = sqlcipher3HashInsert(&pSchema->tblHash, zName, nName, pTab);
101479     if( pOld ){
101480       db->mallocFailed = 1;
101481       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
101482       return;
101483     }
101484     pParse->pNewTable = 0;
101485   }
101486 }
101487
101488 /*
101489 ** The parser calls this routine when it sees the first token
101490 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
101491 */
101492 SQLCIPHER_PRIVATE void sqlcipher3VtabArgInit(Parse *pParse){
101493   addArgumentToVtab(pParse);
101494   pParse->sArg.z = 0;
101495   pParse->sArg.n = 0;
101496 }
101497
101498 /*
101499 ** The parser calls this routine for each token after the first token
101500 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
101501 */
101502 SQLCIPHER_PRIVATE void sqlcipher3VtabArgExtend(Parse *pParse, Token *p){
101503   Token *pArg = &pParse->sArg;
101504   if( pArg->z==0 ){
101505     pArg->z = p->z;
101506     pArg->n = p->n;
101507   }else{
101508     assert(pArg->z < p->z);
101509     pArg->n = (int)(&p->z[p->n] - pArg->z);
101510   }
101511 }
101512
101513 /*
101514 ** Invoke a virtual table constructor (either xCreate or xConnect). The
101515 ** pointer to the function to invoke is passed as the fourth parameter
101516 ** to this procedure.
101517 */
101518 static int vtabCallConstructor(
101519   sqlcipher3 *db, 
101520   Table *pTab,
101521   Module *pMod,
101522   int (*xConstruct)(sqlcipher3*,void*,int,const char*const*,sqlcipher3_vtab**,char**),
101523   char **pzErr
101524 ){
101525   VtabCtx sCtx;
101526   VTable *pVTable;
101527   int rc;
101528   const char *const*azArg = (const char *const*)pTab->azModuleArg;
101529   int nArg = pTab->nModuleArg;
101530   char *zErr = 0;
101531   char *zModuleName = sqlcipher3MPrintf(db, "%s", pTab->zName);
101532
101533   if( !zModuleName ){
101534     return SQLCIPHER_NOMEM;
101535   }
101536
101537   pVTable = sqlcipher3DbMallocZero(db, sizeof(VTable));
101538   if( !pVTable ){
101539     sqlcipher3DbFree(db, zModuleName);
101540     return SQLCIPHER_NOMEM;
101541   }
101542   pVTable->db = db;
101543   pVTable->pMod = pMod;
101544
101545   /* Invoke the virtual table constructor */
101546   assert( &db->pVtabCtx );
101547   assert( xConstruct );
101548   sCtx.pTab = pTab;
101549   sCtx.pVTable = pVTable;
101550   db->pVtabCtx = &sCtx;
101551   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
101552   db->pVtabCtx = 0;
101553   if( rc==SQLCIPHER_NOMEM ) db->mallocFailed = 1;
101554
101555   if( SQLCIPHER_OK!=rc ){
101556     if( zErr==0 ){
101557       *pzErr = sqlcipher3MPrintf(db, "vtable constructor failed: %s", zModuleName);
101558     }else {
101559       *pzErr = sqlcipher3MPrintf(db, "%s", zErr);
101560       sqlcipher3_free(zErr);
101561     }
101562     sqlcipher3DbFree(db, pVTable);
101563   }else if( ALWAYS(pVTable->pVtab) ){
101564     /* Justification of ALWAYS():  A correct vtab constructor must allocate
101565     ** the sqlcipher3_vtab object if successful.  */
101566     pVTable->pVtab->pModule = pMod->pModule;
101567     pVTable->nRef = 1;
101568     if( sCtx.pTab ){
101569       const char *zFormat = "vtable constructor did not declare schema: %s";
101570       *pzErr = sqlcipher3MPrintf(db, zFormat, pTab->zName);
101571       sqlcipher3VtabUnlock(pVTable);
101572       rc = SQLCIPHER_ERROR;
101573     }else{
101574       int iCol;
101575       /* If everything went according to plan, link the new VTable structure
101576       ** into the linked list headed by pTab->pVTable. Then loop through the 
101577       ** columns of the table to see if any of them contain the token "hidden".
101578       ** If so, set the Column.isHidden flag and remove the token from
101579       ** the type string.  */
101580       pVTable->pNext = pTab->pVTable;
101581       pTab->pVTable = pVTable;
101582
101583       for(iCol=0; iCol<pTab->nCol; iCol++){
101584         char *zType = pTab->aCol[iCol].zType;
101585         int nType;
101586         int i = 0;
101587         if( !zType ) continue;
101588         nType = sqlcipher3Strlen30(zType);
101589         if( sqlcipher3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
101590           for(i=0; i<nType; i++){
101591             if( (0==sqlcipher3StrNICmp(" hidden", &zType[i], 7))
101592              && (zType[i+7]=='\0' || zType[i+7]==' ')
101593             ){
101594               i++;
101595               break;
101596             }
101597           }
101598         }
101599         if( i<nType ){
101600           int j;
101601           int nDel = 6 + (zType[i+6] ? 1 : 0);
101602           for(j=i; (j+nDel)<=nType; j++){
101603             zType[j] = zType[j+nDel];
101604           }
101605           if( zType[i]=='\0' && i>0 ){
101606             assert(zType[i-1]==' ');
101607             zType[i-1] = '\0';
101608           }
101609           pTab->aCol[iCol].isHidden = 1;
101610         }
101611       }
101612     }
101613   }
101614
101615   sqlcipher3DbFree(db, zModuleName);
101616   return rc;
101617 }
101618
101619 /*
101620 ** This function is invoked by the parser to call the xConnect() method
101621 ** of the virtual table pTab. If an error occurs, an error code is returned 
101622 ** and an error left in pParse.
101623 **
101624 ** This call is a no-op if table pTab is not a virtual table.
101625 */
101626 SQLCIPHER_PRIVATE int sqlcipher3VtabCallConnect(Parse *pParse, Table *pTab){
101627   sqlcipher3 *db = pParse->db;
101628   const char *zMod;
101629   Module *pMod;
101630   int rc;
101631
101632   assert( pTab );
101633   if( (pTab->tabFlags & TF_Virtual)==0 || sqlcipher3GetVTable(db, pTab) ){
101634     return SQLCIPHER_OK;
101635   }
101636
101637   /* Locate the required virtual table module */
101638   zMod = pTab->azModuleArg[0];
101639   pMod = (Module*)sqlcipher3HashFind(&db->aModule, zMod, sqlcipher3Strlen30(zMod));
101640
101641   if( !pMod ){
101642     const char *zModule = pTab->azModuleArg[0];
101643     sqlcipher3ErrorMsg(pParse, "no such module: %s", zModule);
101644     rc = SQLCIPHER_ERROR;
101645   }else{
101646     char *zErr = 0;
101647     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
101648     if( rc!=SQLCIPHER_OK ){
101649       sqlcipher3ErrorMsg(pParse, "%s", zErr);
101650     }
101651     sqlcipher3DbFree(db, zErr);
101652   }
101653
101654   return rc;
101655 }
101656 /*
101657 ** Grow the db->aVTrans[] array so that there is room for at least one
101658 ** more v-table. Return SQLCIPHER_NOMEM if a malloc fails, or SQLCIPHER_OK otherwise.
101659 */
101660 static int growVTrans(sqlcipher3 *db){
101661   const int ARRAY_INCR = 5;
101662
101663   /* Grow the sqlcipher3.aVTrans array if required */
101664   if( (db->nVTrans%ARRAY_INCR)==0 ){
101665     VTable **aVTrans;
101666     int nBytes = sizeof(sqlcipher3_vtab *) * (db->nVTrans + ARRAY_INCR);
101667     aVTrans = sqlcipher3DbRealloc(db, (void *)db->aVTrans, nBytes);
101668     if( !aVTrans ){
101669       return SQLCIPHER_NOMEM;
101670     }
101671     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlcipher3_vtab *)*ARRAY_INCR);
101672     db->aVTrans = aVTrans;
101673   }
101674
101675   return SQLCIPHER_OK;
101676 }
101677
101678 /*
101679 ** Add the virtual table pVTab to the array sqlcipher3.aVTrans[]. Space should
101680 ** have already been reserved using growVTrans().
101681 */
101682 static void addToVTrans(sqlcipher3 *db, VTable *pVTab){
101683   /* Add pVtab to the end of sqlcipher3.aVTrans */
101684   db->aVTrans[db->nVTrans++] = pVTab;
101685   sqlcipher3VtabLock(pVTab);
101686 }
101687
101688 /*
101689 ** This function is invoked by the vdbe to call the xCreate method
101690 ** of the virtual table named zTab in database iDb. 
101691 **
101692 ** If an error occurs, *pzErr is set to point an an English language
101693 ** description of the error and an SQLCIPHER_XXX error code is returned.
101694 ** In this case the caller must call sqlcipher3DbFree(db, ) on *pzErr.
101695 */
101696 SQLCIPHER_PRIVATE int sqlcipher3VtabCallCreate(sqlcipher3 *db, int iDb, const char *zTab, char **pzErr){
101697   int rc = SQLCIPHER_OK;
101698   Table *pTab;
101699   Module *pMod;
101700   const char *zMod;
101701
101702   pTab = sqlcipher3FindTable(db, zTab, db->aDb[iDb].zName);
101703   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
101704
101705   /* Locate the required virtual table module */
101706   zMod = pTab->azModuleArg[0];
101707   pMod = (Module*)sqlcipher3HashFind(&db->aModule, zMod, sqlcipher3Strlen30(zMod));
101708
101709   /* If the module has been registered and includes a Create method, 
101710   ** invoke it now. If the module has not been registered, return an 
101711   ** error. Otherwise, do nothing.
101712   */
101713   if( !pMod ){
101714     *pzErr = sqlcipher3MPrintf(db, "no such module: %s", zMod);
101715     rc = SQLCIPHER_ERROR;
101716   }else{
101717     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
101718   }
101719
101720   /* Justification of ALWAYS():  The xConstructor method is required to
101721   ** create a valid sqlcipher3_vtab if it returns SQLCIPHER_OK. */
101722   if( rc==SQLCIPHER_OK && ALWAYS(sqlcipher3GetVTable(db, pTab)) ){
101723     rc = growVTrans(db);
101724     if( rc==SQLCIPHER_OK ){
101725       addToVTrans(db, sqlcipher3GetVTable(db, pTab));
101726     }
101727   }
101728
101729   return rc;
101730 }
101731
101732 /*
101733 ** This function is used to set the schema of a virtual table.  It is only
101734 ** valid to call this function from within the xCreate() or xConnect() of a
101735 ** virtual table module.
101736 */
101737 SQLCIPHER_API int sqlcipher3_declare_vtab(sqlcipher3 *db, const char *zCreateTable){
101738   Parse *pParse;
101739
101740   int rc = SQLCIPHER_OK;
101741   Table *pTab;
101742   char *zErr = 0;
101743
101744   sqlcipher3_mutex_enter(db->mutex);
101745   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
101746     sqlcipher3Error(db, SQLCIPHER_MISUSE, 0);
101747     sqlcipher3_mutex_leave(db->mutex);
101748     return SQLCIPHER_MISUSE_BKPT;
101749   }
101750   assert( (pTab->tabFlags & TF_Virtual)!=0 );
101751
101752   pParse = sqlcipher3StackAllocZero(db, sizeof(*pParse));
101753   if( pParse==0 ){
101754     rc = SQLCIPHER_NOMEM;
101755   }else{
101756     pParse->declareVtab = 1;
101757     pParse->db = db;
101758     pParse->nQueryLoop = 1;
101759   
101760     if( SQLCIPHER_OK==sqlcipher3RunParser(pParse, zCreateTable, &zErr) 
101761      && pParse->pNewTable
101762      && !db->mallocFailed
101763      && !pParse->pNewTable->pSelect
101764      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
101765     ){
101766       if( !pTab->aCol ){
101767         pTab->aCol = pParse->pNewTable->aCol;
101768         pTab->nCol = pParse->pNewTable->nCol;
101769         pParse->pNewTable->nCol = 0;
101770         pParse->pNewTable->aCol = 0;
101771       }
101772       db->pVtabCtx->pTab = 0;
101773     }else{
101774       sqlcipher3Error(db, SQLCIPHER_ERROR, (zErr ? "%s" : 0), zErr);
101775       sqlcipher3DbFree(db, zErr);
101776       rc = SQLCIPHER_ERROR;
101777     }
101778     pParse->declareVtab = 0;
101779   
101780     if( pParse->pVdbe ){
101781       sqlcipher3VdbeFinalize(pParse->pVdbe);
101782     }
101783     sqlcipher3DeleteTable(db, pParse->pNewTable);
101784     sqlcipher3StackFree(db, pParse);
101785   }
101786
101787   assert( (rc&0xff)==rc );
101788   rc = sqlcipher3ApiExit(db, rc);
101789   sqlcipher3_mutex_leave(db->mutex);
101790   return rc;
101791 }
101792
101793 /*
101794 ** This function is invoked by the vdbe to call the xDestroy method
101795 ** of the virtual table named zTab in database iDb. This occurs
101796 ** when a DROP TABLE is mentioned.
101797 **
101798 ** This call is a no-op if zTab is not a virtual table.
101799 */
101800 SQLCIPHER_PRIVATE int sqlcipher3VtabCallDestroy(sqlcipher3 *db, int iDb, const char *zTab){
101801   int rc = SQLCIPHER_OK;
101802   Table *pTab;
101803
101804   pTab = sqlcipher3FindTable(db, zTab, db->aDb[iDb].zName);
101805   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
101806     VTable *p = vtabDisconnectAll(db, pTab);
101807
101808     assert( rc==SQLCIPHER_OK );
101809     rc = p->pMod->pModule->xDestroy(p->pVtab);
101810
101811     /* Remove the sqlcipher3_vtab* from the aVTrans[] array, if applicable */
101812     if( rc==SQLCIPHER_OK ){
101813       assert( pTab->pVTable==p && p->pNext==0 );
101814       p->pVtab = 0;
101815       pTab->pVTable = 0;
101816       sqlcipher3VtabUnlock(p);
101817     }
101818   }
101819
101820   return rc;
101821 }
101822
101823 /*
101824 ** This function invokes either the xRollback or xCommit method
101825 ** of each of the virtual tables in the sqlcipher3.aVTrans array. The method
101826 ** called is identified by the second argument, "offset", which is
101827 ** the offset of the method to call in the sqlcipher3_module structure.
101828 **
101829 ** The array is cleared after invoking the callbacks. 
101830 */
101831 static void callFinaliser(sqlcipher3 *db, int offset){
101832   int i;
101833   if( db->aVTrans ){
101834     for(i=0; i<db->nVTrans; i++){
101835       VTable *pVTab = db->aVTrans[i];
101836       sqlcipher3_vtab *p = pVTab->pVtab;
101837       if( p ){
101838         int (*x)(sqlcipher3_vtab *);
101839         x = *(int (**)(sqlcipher3_vtab *))((char *)p->pModule + offset);
101840         if( x ) x(p);
101841       }
101842       pVTab->iSavepoint = 0;
101843       sqlcipher3VtabUnlock(pVTab);
101844     }
101845     sqlcipher3DbFree(db, db->aVTrans);
101846     db->nVTrans = 0;
101847     db->aVTrans = 0;
101848   }
101849 }
101850
101851 /*
101852 ** Invoke the xSync method of all virtual tables in the sqlcipher3.aVTrans
101853 ** array. Return the error code for the first error that occurs, or
101854 ** SQLCIPHER_OK if all xSync operations are successful.
101855 **
101856 ** Set *pzErrmsg to point to a buffer that should be released using 
101857 ** sqlcipher3DbFree() containing an error message, if one is available.
101858 */
101859 SQLCIPHER_PRIVATE int sqlcipher3VtabSync(sqlcipher3 *db, char **pzErrmsg){
101860   int i;
101861   int rc = SQLCIPHER_OK;
101862   VTable **aVTrans = db->aVTrans;
101863
101864   db->aVTrans = 0;
101865   for(i=0; rc==SQLCIPHER_OK && i<db->nVTrans; i++){
101866     int (*x)(sqlcipher3_vtab *);
101867     sqlcipher3_vtab *pVtab = aVTrans[i]->pVtab;
101868     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
101869       rc = x(pVtab);
101870       sqlcipher3DbFree(db, *pzErrmsg);
101871       *pzErrmsg = sqlcipher3DbStrDup(db, pVtab->zErrMsg);
101872       sqlcipher3_free(pVtab->zErrMsg);
101873     }
101874   }
101875   db->aVTrans = aVTrans;
101876   return rc;
101877 }
101878
101879 /*
101880 ** Invoke the xRollback method of all virtual tables in the 
101881 ** sqlcipher3.aVTrans array. Then clear the array itself.
101882 */
101883 SQLCIPHER_PRIVATE int sqlcipher3VtabRollback(sqlcipher3 *db){
101884   callFinaliser(db, offsetof(sqlcipher3_module,xRollback));
101885   return SQLCIPHER_OK;
101886 }
101887
101888 /*
101889 ** Invoke the xCommit method of all virtual tables in the 
101890 ** sqlcipher3.aVTrans array. Then clear the array itself.
101891 */
101892 SQLCIPHER_PRIVATE int sqlcipher3VtabCommit(sqlcipher3 *db){
101893   callFinaliser(db, offsetof(sqlcipher3_module,xCommit));
101894   return SQLCIPHER_OK;
101895 }
101896
101897 /*
101898 ** If the virtual table pVtab supports the transaction interface
101899 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
101900 ** not currently open, invoke the xBegin method now.
101901 **
101902 ** If the xBegin call is successful, place the sqlcipher3_vtab pointer
101903 ** in the sqlcipher3.aVTrans array.
101904 */
101905 SQLCIPHER_PRIVATE int sqlcipher3VtabBegin(sqlcipher3 *db, VTable *pVTab){
101906   int rc = SQLCIPHER_OK;
101907   const sqlcipher3_module *pModule;
101908
101909   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
101910   ** than zero, then this function is being called from within a
101911   ** virtual module xSync() callback. It is illegal to write to 
101912   ** virtual module tables in this case, so return SQLCIPHER_LOCKED.
101913   */
101914   if( sqlcipher3VtabInSync(db) ){
101915     return SQLCIPHER_LOCKED;
101916   }
101917   if( !pVTab ){
101918     return SQLCIPHER_OK;
101919   } 
101920   pModule = pVTab->pVtab->pModule;
101921
101922   if( pModule->xBegin ){
101923     int i;
101924
101925     /* If pVtab is already in the aVTrans array, return early */
101926     for(i=0; i<db->nVTrans; i++){
101927       if( db->aVTrans[i]==pVTab ){
101928         return SQLCIPHER_OK;
101929       }
101930     }
101931
101932     /* Invoke the xBegin method. If successful, add the vtab to the 
101933     ** sqlcipher3.aVTrans[] array. */
101934     rc = growVTrans(db);
101935     if( rc==SQLCIPHER_OK ){
101936       rc = pModule->xBegin(pVTab->pVtab);
101937       if( rc==SQLCIPHER_OK ){
101938         addToVTrans(db, pVTab);
101939       }
101940     }
101941   }
101942   return rc;
101943 }
101944
101945 /*
101946 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
101947 ** virtual tables that currently have an open transaction. Pass iSavepoint
101948 ** as the second argument to the virtual table method invoked.
101949 **
101950 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
101951 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
101952 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
101953 ** an open transaction is invoked.
101954 **
101955 ** If any virtual table method returns an error code other than SQLCIPHER_OK, 
101956 ** processing is abandoned and the error returned to the caller of this
101957 ** function immediately. If all calls to virtual table methods are successful,
101958 ** SQLCIPHER_OK is returned.
101959 */
101960 SQLCIPHER_PRIVATE int sqlcipher3VtabSavepoint(sqlcipher3 *db, int op, int iSavepoint){
101961   int rc = SQLCIPHER_OK;
101962
101963   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
101964   assert( iSavepoint>=0 );
101965   if( db->aVTrans ){
101966     int i;
101967     for(i=0; rc==SQLCIPHER_OK && i<db->nVTrans; i++){
101968       VTable *pVTab = db->aVTrans[i];
101969       const sqlcipher3_module *pMod = pVTab->pMod->pModule;
101970       if( pVTab->pVtab && pMod->iVersion>=2 ){
101971         int (*xMethod)(sqlcipher3_vtab *, int);
101972         switch( op ){
101973           case SAVEPOINT_BEGIN:
101974             xMethod = pMod->xSavepoint;
101975             pVTab->iSavepoint = iSavepoint+1;
101976             break;
101977           case SAVEPOINT_ROLLBACK:
101978             xMethod = pMod->xRollbackTo;
101979             break;
101980           default:
101981             xMethod = pMod->xRelease;
101982             break;
101983         }
101984         if( xMethod && pVTab->iSavepoint>iSavepoint ){
101985           rc = xMethod(pVTab->pVtab, iSavepoint);
101986         }
101987       }
101988     }
101989   }
101990   return rc;
101991 }
101992
101993 /*
101994 ** The first parameter (pDef) is a function implementation.  The
101995 ** second parameter (pExpr) is the first argument to this function.
101996 ** If pExpr is a column in a virtual table, then let the virtual
101997 ** table implementation have an opportunity to overload the function.
101998 **
101999 ** This routine is used to allow virtual table implementations to
102000 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
102001 **
102002 ** Return either the pDef argument (indicating no change) or a 
102003 ** new FuncDef structure that is marked as ephemeral using the
102004 ** SQLCIPHER_FUNC_EPHEM flag.
102005 */
102006 SQLCIPHER_PRIVATE FuncDef *sqlcipher3VtabOverloadFunction(
102007   sqlcipher3 *db,    /* Database connection for reporting malloc problems */
102008   FuncDef *pDef,  /* Function to possibly overload */
102009   int nArg,       /* Number of arguments to the function */
102010   Expr *pExpr     /* First argument to the function */
102011 ){
102012   Table *pTab;
102013   sqlcipher3_vtab *pVtab;
102014   sqlcipher3_module *pMod;
102015   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**) = 0;
102016   void *pArg = 0;
102017   FuncDef *pNew;
102018   int rc = 0;
102019   char *zLowerName;
102020   unsigned char *z;
102021
102022
102023   /* Check to see the left operand is a column in a virtual table */
102024   if( NEVER(pExpr==0) ) return pDef;
102025   if( pExpr->op!=TK_COLUMN ) return pDef;
102026   pTab = pExpr->pTab;
102027   if( NEVER(pTab==0) ) return pDef;
102028   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
102029   pVtab = sqlcipher3GetVTable(db, pTab)->pVtab;
102030   assert( pVtab!=0 );
102031   assert( pVtab->pModule!=0 );
102032   pMod = (sqlcipher3_module *)pVtab->pModule;
102033   if( pMod->xFindFunction==0 ) return pDef;
102034  
102035   /* Call the xFindFunction method on the virtual table implementation
102036   ** to see if the implementation wants to overload this function 
102037   */
102038   zLowerName = sqlcipher3DbStrDup(db, pDef->zName);
102039   if( zLowerName ){
102040     for(z=(unsigned char*)zLowerName; *z; z++){
102041       *z = sqlcipher3UpperToLower[*z];
102042     }
102043     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
102044     sqlcipher3DbFree(db, zLowerName);
102045   }
102046   if( rc==0 ){
102047     return pDef;
102048   }
102049
102050   /* Create a new ephemeral function definition for the overloaded
102051   ** function */
102052   pNew = sqlcipher3DbMallocZero(db, sizeof(*pNew)
102053                              + sqlcipher3Strlen30(pDef->zName) + 1);
102054   if( pNew==0 ){
102055     return pDef;
102056   }
102057   *pNew = *pDef;
102058   pNew->zName = (char *)&pNew[1];
102059   memcpy(pNew->zName, pDef->zName, sqlcipher3Strlen30(pDef->zName)+1);
102060   pNew->xFunc = xFunc;
102061   pNew->pUserData = pArg;
102062   pNew->flags |= SQLCIPHER_FUNC_EPHEM;
102063   return pNew;
102064 }
102065
102066 /*
102067 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
102068 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
102069 ** array if it is missing.  If pTab is already in the array, this routine
102070 ** is a no-op.
102071 */
102072 SQLCIPHER_PRIVATE void sqlcipher3VtabMakeWritable(Parse *pParse, Table *pTab){
102073   Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
102074   int i, n;
102075   Table **apVtabLock;
102076
102077   assert( IsVirtual(pTab) );
102078   for(i=0; i<pToplevel->nVtabLock; i++){
102079     if( pTab==pToplevel->apVtabLock[i] ) return;
102080   }
102081   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
102082   apVtabLock = sqlcipher3_realloc(pToplevel->apVtabLock, n);
102083   if( apVtabLock ){
102084     pToplevel->apVtabLock = apVtabLock;
102085     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
102086   }else{
102087     pToplevel->db->mallocFailed = 1;
102088   }
102089 }
102090
102091 /*
102092 ** Return the ON CONFLICT resolution mode in effect for the virtual
102093 ** table update operation currently in progress.
102094 **
102095 ** The results of this routine are undefined unless it is called from
102096 ** within an xUpdate method.
102097 */
102098 SQLCIPHER_API int sqlcipher3_vtab_on_conflict(sqlcipher3 *db){
102099   static const unsigned char aMap[] = { 
102100     SQLCIPHER_ROLLBACK, SQLCIPHER_ABORT, SQLCIPHER_FAIL, SQLCIPHER_IGNORE, SQLCIPHER_REPLACE 
102101   };
102102   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
102103   assert( OE_Ignore==4 && OE_Replace==5 );
102104   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
102105   return (int)aMap[db->vtabOnConflict-1];
102106 }
102107
102108 /*
102109 ** Call from within the xCreate() or xConnect() methods to provide 
102110 ** the SQLite core with additional information about the behavior
102111 ** of the virtual table being implemented.
102112 */
102113 SQLCIPHER_API int sqlcipher3_vtab_config(sqlcipher3 *db, int op, ...){
102114   va_list ap;
102115   int rc = SQLCIPHER_OK;
102116
102117   sqlcipher3_mutex_enter(db->mutex);
102118
102119   va_start(ap, op);
102120   switch( op ){
102121     case SQLCIPHER_VTAB_CONSTRAINT_SUPPORT: {
102122       VtabCtx *p = db->pVtabCtx;
102123       if( !p ){
102124         rc = SQLCIPHER_MISUSE_BKPT;
102125       }else{
102126         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
102127         p->pVTable->bConstraint = (u8)va_arg(ap, int);
102128       }
102129       break;
102130     }
102131     default:
102132       rc = SQLCIPHER_MISUSE_BKPT;
102133       break;
102134   }
102135   va_end(ap);
102136
102137   if( rc!=SQLCIPHER_OK ) sqlcipher3Error(db, rc, 0);
102138   sqlcipher3_mutex_leave(db->mutex);
102139   return rc;
102140 }
102141
102142 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
102143
102144 /************** End of vtab.c ************************************************/
102145 /************** Begin file where.c *******************************************/
102146 /*
102147 ** 2001 September 15
102148 **
102149 ** The author disclaims copyright to this source code.  In place of
102150 ** a legal notice, here is a blessing:
102151 **
102152 **    May you do good and not evil.
102153 **    May you find forgiveness for yourself and forgive others.
102154 **    May you share freely, never taking more than you give.
102155 **
102156 *************************************************************************
102157 ** This module contains C code that generates VDBE code used to process
102158 ** the WHERE clause of SQL statements.  This module is responsible for
102159 ** generating the code that loops through a table looking for applicable
102160 ** rows.  Indices are selected and used to speed the search when doing
102161 ** so is applicable.  Because this module is responsible for selecting
102162 ** indices, you might also think of this module as the "query optimizer".
102163 */
102164
102165
102166 /*
102167 ** Trace output macros
102168 */
102169 #if defined(SQLCIPHER_TEST) || defined(SQLCIPHER_DEBUG)
102170 SQLCIPHER_PRIVATE int sqlcipher3WhereTrace = 0;
102171 #endif
102172 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
102173 # define WHERETRACE(X)  if(sqlcipher3WhereTrace) sqlcipher3DebugPrintf X
102174 #else
102175 # define WHERETRACE(X)
102176 #endif
102177
102178 /* Forward reference
102179 */
102180 typedef struct WhereClause WhereClause;
102181 typedef struct WhereMaskSet WhereMaskSet;
102182 typedef struct WhereOrInfo WhereOrInfo;
102183 typedef struct WhereAndInfo WhereAndInfo;
102184 typedef struct WhereCost WhereCost;
102185
102186 /*
102187 ** The query generator uses an array of instances of this structure to
102188 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
102189 ** clause subexpression is separated from the others by AND operators,
102190 ** usually, or sometimes subexpressions separated by OR.
102191 **
102192 ** All WhereTerms are collected into a single WhereClause structure.  
102193 ** The following identity holds:
102194 **
102195 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
102196 **
102197 ** When a term is of the form:
102198 **
102199 **              X <op> <expr>
102200 **
102201 ** where X is a column name and <op> is one of certain operators,
102202 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
102203 ** cursor number and column number for X.  WhereTerm.eOperator records
102204 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
102205 ** use of a bitmask encoding for the operator allows us to search
102206 ** quickly for terms that match any of several different operators.
102207 **
102208 ** A WhereTerm might also be two or more subterms connected by OR:
102209 **
102210 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
102211 **
102212 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
102213 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
102214 ** is collected about the
102215 **
102216 ** If a term in the WHERE clause does not match either of the two previous
102217 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
102218 ** to the original subexpression content and wtFlags is set up appropriately
102219 ** but no other fields in the WhereTerm object are meaningful.
102220 **
102221 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
102222 ** but they do so indirectly.  A single WhereMaskSet structure translates
102223 ** cursor number into bits and the translated bit is stored in the prereq
102224 ** fields.  The translation is used in order to maximize the number of
102225 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
102226 ** spread out over the non-negative integers.  For example, the cursor
102227 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
102228 ** translates these sparse cursor numbers into consecutive integers
102229 ** beginning with 0 in order to make the best possible use of the available
102230 ** bits in the Bitmask.  So, in the example above, the cursor numbers
102231 ** would be mapped into integers 0 through 7.
102232 **
102233 ** The number of terms in a join is limited by the number of bits
102234 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
102235 ** is only able to process joins with 64 or fewer tables.
102236 */
102237 typedef struct WhereTerm WhereTerm;
102238 struct WhereTerm {
102239   Expr *pExpr;            /* Pointer to the subexpression that is this term */
102240   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
102241   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
102242   union {
102243     int leftColumn;         /* Column number of X in "X <op> <expr>" */
102244     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
102245     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
102246   } u;
102247   u16 eOperator;          /* A WO_xx value describing <op> */
102248   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
102249   u8 nChild;              /* Number of children that must disable us */
102250   WhereClause *pWC;       /* The clause this term is part of */
102251   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
102252   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
102253 };
102254
102255 /*
102256 ** Allowed values of WhereTerm.wtFlags
102257 */
102258 #define TERM_DYNAMIC    0x01   /* Need to call sqlcipher3ExprDelete(db, pExpr) */
102259 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
102260 #define TERM_CODED      0x04   /* This term is already coded */
102261 #define TERM_COPIED     0x08   /* Has a child */
102262 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
102263 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
102264 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
102265 #ifdef SQLCIPHER_ENABLE_STAT3
102266 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
102267 #else
102268 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
102269 #endif
102270
102271 /*
102272 ** An instance of the following structure holds all information about a
102273 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
102274 **
102275 ** Explanation of pOuter:  For a WHERE clause of the form
102276 **
102277 **           a AND ((b AND c) OR (d AND e)) AND f
102278 **
102279 ** There are separate WhereClause objects for the whole clause and for
102280 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
102281 ** subclauses points to the WhereClause object for the whole clause.
102282 */
102283 struct WhereClause {
102284   Parse *pParse;           /* The parser context */
102285   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
102286   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
102287   WhereClause *pOuter;     /* Outer conjunction */
102288   u8 op;                   /* Split operator.  TK_AND or TK_OR */
102289   u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
102290   int nTerm;               /* Number of terms */
102291   int nSlot;               /* Number of entries in a[] */
102292   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
102293 #if defined(SQLCIPHER_SMALL_STACK)
102294   WhereTerm aStatic[1];    /* Initial static space for a[] */
102295 #else
102296   WhereTerm aStatic[8];    /* Initial static space for a[] */
102297 #endif
102298 };
102299
102300 /*
102301 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
102302 ** a dynamically allocated instance of the following structure.
102303 */
102304 struct WhereOrInfo {
102305   WhereClause wc;          /* Decomposition into subterms */
102306   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
102307 };
102308
102309 /*
102310 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
102311 ** a dynamically allocated instance of the following structure.
102312 */
102313 struct WhereAndInfo {
102314   WhereClause wc;          /* The subexpression broken out */
102315 };
102316
102317 /*
102318 ** An instance of the following structure keeps track of a mapping
102319 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
102320 **
102321 ** The VDBE cursor numbers are small integers contained in 
102322 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
102323 ** clause, the cursor numbers might not begin with 0 and they might
102324 ** contain gaps in the numbering sequence.  But we want to make maximum
102325 ** use of the bits in our bitmasks.  This structure provides a mapping
102326 ** from the sparse cursor numbers into consecutive integers beginning
102327 ** with 0.
102328 **
102329 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
102330 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
102331 **
102332 ** For example, if the WHERE clause expression used these VDBE
102333 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
102334 ** would map those cursor numbers into bits 0 through 5.
102335 **
102336 ** Note that the mapping is not necessarily ordered.  In the example
102337 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
102338 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
102339 ** does not really matter.  What is important is that sparse cursor
102340 ** numbers all get mapped into bit numbers that begin with 0 and contain
102341 ** no gaps.
102342 */
102343 struct WhereMaskSet {
102344   int n;                        /* Number of assigned cursor values */
102345   int ix[BMS];                  /* Cursor assigned to each bit */
102346 };
102347
102348 /*
102349 ** A WhereCost object records a lookup strategy and the estimated
102350 ** cost of pursuing that strategy.
102351 */
102352 struct WhereCost {
102353   WherePlan plan;    /* The lookup strategy */
102354   double rCost;      /* Overall cost of pursuing this search strategy */
102355   Bitmask used;      /* Bitmask of cursors used by this plan */
102356 };
102357
102358 /*
102359 ** Bitmasks for the operators that indices are able to exploit.  An
102360 ** OR-ed combination of these values can be used when searching for
102361 ** terms in the where clause.
102362 */
102363 #define WO_IN     0x001
102364 #define WO_EQ     0x002
102365 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
102366 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
102367 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
102368 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
102369 #define WO_MATCH  0x040
102370 #define WO_ISNULL 0x080
102371 #define WO_OR     0x100       /* Two or more OR-connected terms */
102372 #define WO_AND    0x200       /* Two or more AND-connected terms */
102373 #define WO_NOOP   0x800       /* This term does not restrict search space */
102374
102375 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
102376 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
102377
102378 /*
102379 ** Value for wsFlags returned by bestIndex() and stored in
102380 ** WhereLevel.wsFlags.  These flags determine which search
102381 ** strategies are appropriate.
102382 **
102383 ** The least significant 12 bits is reserved as a mask for WO_ values above.
102384 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
102385 ** But if the table is the right table of a left join, WhereLevel.wsFlags
102386 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
102387 ** the "op" parameter to findTerm when we are resolving equality constraints.
102388 ** ISNULL constraints will then not be used on the right table of a left
102389 ** join.  Tickets #2177 and #2189.
102390 */
102391 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
102392 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
102393 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
102394 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
102395 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
102396 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
102397 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
102398 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
102399 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
102400 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
102401 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
102402 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
102403 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
102404 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
102405 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
102406 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
102407 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
102408 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
102409 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
102410 #define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
102411
102412 /*
102413 ** Initialize a preallocated WhereClause structure.
102414 */
102415 static void whereClauseInit(
102416   WhereClause *pWC,        /* The WhereClause to be initialized */
102417   Parse *pParse,           /* The parsing context */
102418   WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
102419   u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
102420 ){
102421   pWC->pParse = pParse;
102422   pWC->pMaskSet = pMaskSet;
102423   pWC->pOuter = 0;
102424   pWC->nTerm = 0;
102425   pWC->nSlot = ArraySize(pWC->aStatic);
102426   pWC->a = pWC->aStatic;
102427   pWC->vmask = 0;
102428   pWC->wctrlFlags = wctrlFlags;
102429 }
102430
102431 /* Forward reference */
102432 static void whereClauseClear(WhereClause*);
102433
102434 /*
102435 ** Deallocate all memory associated with a WhereOrInfo object.
102436 */
102437 static void whereOrInfoDelete(sqlcipher3 *db, WhereOrInfo *p){
102438   whereClauseClear(&p->wc);
102439   sqlcipher3DbFree(db, p);
102440 }
102441
102442 /*
102443 ** Deallocate all memory associated with a WhereAndInfo object.
102444 */
102445 static void whereAndInfoDelete(sqlcipher3 *db, WhereAndInfo *p){
102446   whereClauseClear(&p->wc);
102447   sqlcipher3DbFree(db, p);
102448 }
102449
102450 /*
102451 ** Deallocate a WhereClause structure.  The WhereClause structure
102452 ** itself is not freed.  This routine is the inverse of whereClauseInit().
102453 */
102454 static void whereClauseClear(WhereClause *pWC){
102455   int i;
102456   WhereTerm *a;
102457   sqlcipher3 *db = pWC->pParse->db;
102458   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
102459     if( a->wtFlags & TERM_DYNAMIC ){
102460       sqlcipher3ExprDelete(db, a->pExpr);
102461     }
102462     if( a->wtFlags & TERM_ORINFO ){
102463       whereOrInfoDelete(db, a->u.pOrInfo);
102464     }else if( a->wtFlags & TERM_ANDINFO ){
102465       whereAndInfoDelete(db, a->u.pAndInfo);
102466     }
102467   }
102468   if( pWC->a!=pWC->aStatic ){
102469     sqlcipher3DbFree(db, pWC->a);
102470   }
102471 }
102472
102473 /*
102474 ** Add a single new WhereTerm entry to the WhereClause object pWC.
102475 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
102476 ** The index in pWC->a[] of the new WhereTerm is returned on success.
102477 ** 0 is returned if the new WhereTerm could not be added due to a memory
102478 ** allocation error.  The memory allocation failure will be recorded in
102479 ** the db->mallocFailed flag so that higher-level functions can detect it.
102480 **
102481 ** This routine will increase the size of the pWC->a[] array as necessary.
102482 **
102483 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
102484 ** for freeing the expression p is assumed by the WhereClause object pWC.
102485 ** This is true even if this routine fails to allocate a new WhereTerm.
102486 **
102487 ** WARNING:  This routine might reallocate the space used to store
102488 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
102489 ** calling this routine.  Such pointers may be reinitialized by referencing
102490 ** the pWC->a[] array.
102491 */
102492 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
102493   WhereTerm *pTerm;
102494   int idx;
102495   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
102496   if( pWC->nTerm>=pWC->nSlot ){
102497     WhereTerm *pOld = pWC->a;
102498     sqlcipher3 *db = pWC->pParse->db;
102499     pWC->a = sqlcipher3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
102500     if( pWC->a==0 ){
102501       if( wtFlags & TERM_DYNAMIC ){
102502         sqlcipher3ExprDelete(db, p);
102503       }
102504       pWC->a = pOld;
102505       return 0;
102506     }
102507     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
102508     if( pOld!=pWC->aStatic ){
102509       sqlcipher3DbFree(db, pOld);
102510     }
102511     pWC->nSlot = sqlcipher3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
102512   }
102513   pTerm = &pWC->a[idx = pWC->nTerm++];
102514   pTerm->pExpr = p;
102515   pTerm->wtFlags = wtFlags;
102516   pTerm->pWC = pWC;
102517   pTerm->iParent = -1;
102518   return idx;
102519 }
102520
102521 /*
102522 ** This routine identifies subexpressions in the WHERE clause where
102523 ** each subexpression is separated by the AND operator or some other
102524 ** operator specified in the op parameter.  The WhereClause structure
102525 ** is filled with pointers to subexpressions.  For example:
102526 **
102527 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
102528 **           \________/     \_______________/     \________________/
102529 **            slot[0]            slot[1]               slot[2]
102530 **
102531 ** The original WHERE clause in pExpr is unaltered.  All this routine
102532 ** does is make slot[] entries point to substructure within pExpr.
102533 **
102534 ** In the previous sentence and in the diagram, "slot[]" refers to
102535 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
102536 ** all terms of the WHERE clause.
102537 */
102538 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
102539   pWC->op = (u8)op;
102540   if( pExpr==0 ) return;
102541   if( pExpr->op!=op ){
102542     whereClauseInsert(pWC, pExpr, 0);
102543   }else{
102544     whereSplit(pWC, pExpr->pLeft, op);
102545     whereSplit(pWC, pExpr->pRight, op);
102546   }
102547 }
102548
102549 /*
102550 ** Initialize an expression mask set (a WhereMaskSet object)
102551 */
102552 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
102553
102554 /*
102555 ** Return the bitmask for the given cursor number.  Return 0 if
102556 ** iCursor is not in the set.
102557 */
102558 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
102559   int i;
102560   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
102561   for(i=0; i<pMaskSet->n; i++){
102562     if( pMaskSet->ix[i]==iCursor ){
102563       return ((Bitmask)1)<<i;
102564     }
102565   }
102566   return 0;
102567 }
102568
102569 /*
102570 ** Create a new mask for cursor iCursor.
102571 **
102572 ** There is one cursor per table in the FROM clause.  The number of
102573 ** tables in the FROM clause is limited by a test early in the
102574 ** sqlcipher3WhereBegin() routine.  So we know that the pMaskSet->ix[]
102575 ** array will never overflow.
102576 */
102577 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
102578   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
102579   pMaskSet->ix[pMaskSet->n++] = iCursor;
102580 }
102581
102582 /*
102583 ** This routine walks (recursively) an expression tree and generates
102584 ** a bitmask indicating which tables are used in that expression
102585 ** tree.
102586 **
102587 ** In order for this routine to work, the calling function must have
102588 ** previously invoked sqlcipher3ResolveExprNames() on the expression.  See
102589 ** the header comment on that routine for additional information.
102590 ** The sqlcipher3ResolveExprNames() routines looks for column names and
102591 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
102592 ** the VDBE cursor number of the table.  This routine just has to
102593 ** translate the cursor numbers into bitmask values and OR all
102594 ** the bitmasks together.
102595 */
102596 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
102597 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
102598 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
102599   Bitmask mask = 0;
102600   if( p==0 ) return 0;
102601   if( p->op==TK_COLUMN ){
102602     mask = getMask(pMaskSet, p->iTable);
102603     return mask;
102604   }
102605   mask = exprTableUsage(pMaskSet, p->pRight);
102606   mask |= exprTableUsage(pMaskSet, p->pLeft);
102607   if( ExprHasProperty(p, EP_xIsSelect) ){
102608     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
102609   }else{
102610     mask |= exprListTableUsage(pMaskSet, p->x.pList);
102611   }
102612   return mask;
102613 }
102614 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
102615   int i;
102616   Bitmask mask = 0;
102617   if( pList ){
102618     for(i=0; i<pList->nExpr; i++){
102619       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
102620     }
102621   }
102622   return mask;
102623 }
102624 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
102625   Bitmask mask = 0;
102626   while( pS ){
102627     SrcList *pSrc = pS->pSrc;
102628     mask |= exprListTableUsage(pMaskSet, pS->pEList);
102629     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
102630     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
102631     mask |= exprTableUsage(pMaskSet, pS->pWhere);
102632     mask |= exprTableUsage(pMaskSet, pS->pHaving);
102633     if( ALWAYS(pSrc!=0) ){
102634       int i;
102635       for(i=0; i<pSrc->nSrc; i++){
102636         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
102637         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
102638       }
102639     }
102640     pS = pS->pPrior;
102641   }
102642   return mask;
102643 }
102644
102645 /*
102646 ** Return TRUE if the given operator is one of the operators that is
102647 ** allowed for an indexable WHERE clause term.  The allowed operators are
102648 ** "=", "<", ">", "<=", ">=", and "IN".
102649 **
102650 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
102651 ** of one of the following forms: column = expression column > expression
102652 ** column >= expression column < expression column <= expression
102653 ** expression = column expression > column expression >= column
102654 ** expression < column expression <= column column IN
102655 ** (expression-list) column IN (subquery) column IS NULL
102656 */
102657 static int allowedOp(int op){
102658   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
102659   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
102660   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
102661   assert( TK_GE==TK_EQ+4 );
102662   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
102663 }
102664
102665 /*
102666 ** Swap two objects of type TYPE.
102667 */
102668 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
102669
102670 /*
102671 ** Commute a comparison operator.  Expressions of the form "X op Y"
102672 ** are converted into "Y op X".
102673 **
102674 ** If a collation sequence is associated with either the left or right
102675 ** side of the comparison, it remains associated with the same side after
102676 ** the commutation. So "Y collate NOCASE op X" becomes 
102677 ** "X collate NOCASE op Y". This is because any collation sequence on
102678 ** the left hand side of a comparison overrides any collation sequence 
102679 ** attached to the right. For the same reason the EP_ExpCollate flag
102680 ** is not commuted.
102681 */
102682 static void exprCommute(Parse *pParse, Expr *pExpr){
102683   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
102684   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
102685   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
102686   pExpr->pRight->pColl = sqlcipher3ExprCollSeq(pParse, pExpr->pRight);
102687   pExpr->pLeft->pColl = sqlcipher3ExprCollSeq(pParse, pExpr->pLeft);
102688   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
102689   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
102690   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
102691   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
102692   if( pExpr->op>=TK_GT ){
102693     assert( TK_LT==TK_GT+2 );
102694     assert( TK_GE==TK_LE+2 );
102695     assert( TK_GT>TK_EQ );
102696     assert( TK_GT<TK_LE );
102697     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
102698     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
102699   }
102700 }
102701
102702 /*
102703 ** Translate from TK_xx operator to WO_xx bitmask.
102704 */
102705 static u16 operatorMask(int op){
102706   u16 c;
102707   assert( allowedOp(op) );
102708   if( op==TK_IN ){
102709     c = WO_IN;
102710   }else if( op==TK_ISNULL ){
102711     c = WO_ISNULL;
102712   }else{
102713     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
102714     c = (u16)(WO_EQ<<(op-TK_EQ));
102715   }
102716   assert( op!=TK_ISNULL || c==WO_ISNULL );
102717   assert( op!=TK_IN || c==WO_IN );
102718   assert( op!=TK_EQ || c==WO_EQ );
102719   assert( op!=TK_LT || c==WO_LT );
102720   assert( op!=TK_LE || c==WO_LE );
102721   assert( op!=TK_GT || c==WO_GT );
102722   assert( op!=TK_GE || c==WO_GE );
102723   return c;
102724 }
102725
102726 /*
102727 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
102728 ** where X is a reference to the iColumn of table iCur and <op> is one of
102729 ** the WO_xx operator codes specified by the op parameter.
102730 ** Return a pointer to the term.  Return 0 if not found.
102731 */
102732 static WhereTerm *findTerm(
102733   WhereClause *pWC,     /* The WHERE clause to be searched */
102734   int iCur,             /* Cursor number of LHS */
102735   int iColumn,          /* Column number of LHS */
102736   Bitmask notReady,     /* RHS must not overlap with this mask */
102737   u32 op,               /* Mask of WO_xx values describing operator */
102738   Index *pIdx           /* Must be compatible with this index, if not NULL */
102739 ){
102740   WhereTerm *pTerm;
102741   int k;
102742   assert( iCur>=0 );
102743   op &= WO_ALL;
102744   for(; pWC; pWC=pWC->pOuter){
102745     for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
102746       if( pTerm->leftCursor==iCur
102747          && (pTerm->prereqRight & notReady)==0
102748          && pTerm->u.leftColumn==iColumn
102749          && (pTerm->eOperator & op)!=0
102750       ){
102751         if( pIdx && pTerm->eOperator!=WO_ISNULL ){
102752           Expr *pX = pTerm->pExpr;
102753           CollSeq *pColl;
102754           char idxaff;
102755           int j;
102756           Parse *pParse = pWC->pParse;
102757   
102758           idxaff = pIdx->pTable->aCol[iColumn].affinity;
102759           if( !sqlcipher3IndexAffinityOk(pX, idxaff) ) continue;
102760   
102761           /* Figure out the collation sequence required from an index for
102762           ** it to be useful for optimising expression pX. Store this
102763           ** value in variable pColl.
102764           */
102765           assert(pX->pLeft);
102766           pColl = sqlcipher3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
102767           assert(pColl || pParse->nErr);
102768   
102769           for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
102770             if( NEVER(j>=pIdx->nColumn) ) return 0;
102771           }
102772           if( pColl && sqlcipher3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
102773         }
102774         return pTerm;
102775       }
102776     }
102777   }
102778   return 0;
102779 }
102780
102781 /* Forward reference */
102782 static void exprAnalyze(SrcList*, WhereClause*, int);
102783
102784 /*
102785 ** Call exprAnalyze on all terms in a WHERE clause.  
102786 **
102787 **
102788 */
102789 static void exprAnalyzeAll(
102790   SrcList *pTabList,       /* the FROM clause */
102791   WhereClause *pWC         /* the WHERE clause to be analyzed */
102792 ){
102793   int i;
102794   for(i=pWC->nTerm-1; i>=0; i--){
102795     exprAnalyze(pTabList, pWC, i);
102796   }
102797 }
102798
102799 #ifndef SQLCIPHER_OMIT_LIKE_OPTIMIZATION
102800 /*
102801 ** Check to see if the given expression is a LIKE or GLOB operator that
102802 ** can be optimized using inequality constraints.  Return TRUE if it is
102803 ** so and false if not.
102804 **
102805 ** In order for the operator to be optimizible, the RHS must be a string
102806 ** literal that does not begin with a wildcard.  
102807 */
102808 static int isLikeOrGlob(
102809   Parse *pParse,    /* Parsing and code generating context */
102810   Expr *pExpr,      /* Test this expression */
102811   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
102812   int *pisComplete, /* True if the only wildcard is % in the last character */
102813   int *pnoCase      /* True if uppercase is equivalent to lowercase */
102814 ){
102815   const char *z = 0;         /* String on RHS of LIKE operator */
102816   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
102817   ExprList *pList;           /* List of operands to the LIKE operator */
102818   int c;                     /* One character in z[] */
102819   int cnt;                   /* Number of non-wildcard prefix characters */
102820   char wc[3];                /* Wildcard characters */
102821   sqlcipher3 *db = pParse->db;  /* Database connection */
102822   sqlcipher3_value *pVal = 0;
102823   int op;                    /* Opcode of pRight */
102824
102825   if( !sqlcipher3IsLikeFunction(db, pExpr, pnoCase, wc) ){
102826     return 0;
102827   }
102828 #ifdef SQLCIPHER_EBCDIC
102829   if( *pnoCase ) return 0;
102830 #endif
102831   pList = pExpr->x.pList;
102832   pLeft = pList->a[1].pExpr;
102833   if( pLeft->op!=TK_COLUMN || sqlcipher3ExprAffinity(pLeft)!=SQLCIPHER_AFF_TEXT ){
102834     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
102835     ** be the name of an indexed column with TEXT affinity. */
102836     return 0;
102837   }
102838   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
102839
102840   pRight = pList->a[0].pExpr;
102841   op = pRight->op;
102842   if( op==TK_REGISTER ){
102843     op = pRight->op2;
102844   }
102845   if( op==TK_VARIABLE ){
102846     Vdbe *pReprepare = pParse->pReprepare;
102847     int iCol = pRight->iColumn;
102848     pVal = sqlcipher3VdbeGetValue(pReprepare, iCol, SQLCIPHER_AFF_NONE);
102849     if( pVal && sqlcipher3_value_type(pVal)==SQLCIPHER_TEXT ){
102850       z = (char *)sqlcipher3_value_text(pVal);
102851     }
102852     sqlcipher3VdbeSetVarmask(pParse->pVdbe, iCol);
102853     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
102854   }else if( op==TK_STRING ){
102855     z = pRight->u.zToken;
102856   }
102857   if( z ){
102858     cnt = 0;
102859     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
102860       cnt++;
102861     }
102862     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
102863       Expr *pPrefix;
102864       *pisComplete = c==wc[0] && z[cnt+1]==0;
102865       pPrefix = sqlcipher3Expr(db, TK_STRING, z);
102866       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
102867       *ppPrefix = pPrefix;
102868       if( op==TK_VARIABLE ){
102869         Vdbe *v = pParse->pVdbe;
102870         sqlcipher3VdbeSetVarmask(v, pRight->iColumn);
102871         if( *pisComplete && pRight->u.zToken[1] ){
102872           /* If the rhs of the LIKE expression is a variable, and the current
102873           ** value of the variable means there is no need to invoke the LIKE
102874           ** function, then no OP_Variable will be added to the program.
102875           ** This causes problems for the sqlcipher3_bind_parameter_name()
102876           ** API. To workaround them, add a dummy OP_Variable here.
102877           */ 
102878           int r1 = sqlcipher3GetTempReg(pParse);
102879           sqlcipher3ExprCodeTarget(pParse, pRight, r1);
102880           sqlcipher3VdbeChangeP3(v, sqlcipher3VdbeCurrentAddr(v)-1, 0);
102881           sqlcipher3ReleaseTempReg(pParse, r1);
102882         }
102883       }
102884     }else{
102885       z = 0;
102886     }
102887   }
102888
102889   sqlcipher3ValueFree(pVal);
102890   return (z!=0);
102891 }
102892 #endif /* SQLCIPHER_OMIT_LIKE_OPTIMIZATION */
102893
102894
102895 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
102896 /*
102897 ** Check to see if the given expression is of the form
102898 **
102899 **         column MATCH expr
102900 **
102901 ** If it is then return TRUE.  If not, return FALSE.
102902 */
102903 static int isMatchOfColumn(
102904   Expr *pExpr      /* Test this expression */
102905 ){
102906   ExprList *pList;
102907
102908   if( pExpr->op!=TK_FUNCTION ){
102909     return 0;
102910   }
102911   if( sqlcipher3StrICmp(pExpr->u.zToken,"match")!=0 ){
102912     return 0;
102913   }
102914   pList = pExpr->x.pList;
102915   if( pList->nExpr!=2 ){
102916     return 0;
102917   }
102918   if( pList->a[1].pExpr->op != TK_COLUMN ){
102919     return 0;
102920   }
102921   return 1;
102922 }
102923 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
102924
102925 /*
102926 ** If the pBase expression originated in the ON or USING clause of
102927 ** a join, then transfer the appropriate markings over to derived.
102928 */
102929 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
102930   pDerived->flags |= pBase->flags & EP_FromJoin;
102931   pDerived->iRightJoinTable = pBase->iRightJoinTable;
102932 }
102933
102934 #if !defined(SQLCIPHER_OMIT_OR_OPTIMIZATION) && !defined(SQLCIPHER_OMIT_SUBQUERY)
102935 /*
102936 ** Analyze a term that consists of two or more OR-connected
102937 ** subterms.  So in:
102938 **
102939 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
102940 **                          ^^^^^^^^^^^^^^^^^^^^
102941 **
102942 ** This routine analyzes terms such as the middle term in the above example.
102943 ** A WhereOrTerm object is computed and attached to the term under
102944 ** analysis, regardless of the outcome of the analysis.  Hence:
102945 **
102946 **     WhereTerm.wtFlags   |=  TERM_ORINFO
102947 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
102948 **
102949 ** The term being analyzed must have two or more of OR-connected subterms.
102950 ** A single subterm might be a set of AND-connected sub-subterms.
102951 ** Examples of terms under analysis:
102952 **
102953 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
102954 **     (B)     x=expr1 OR expr2=x OR x=expr3
102955 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
102956 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
102957 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
102958 **
102959 ** CASE 1:
102960 **
102961 ** If all subterms are of the form T.C=expr for some single column of C
102962 ** a single table T (as shown in example B above) then create a new virtual
102963 ** term that is an equivalent IN expression.  In other words, if the term
102964 ** being analyzed is:
102965 **
102966 **      x = expr1  OR  expr2 = x  OR  x = expr3
102967 **
102968 ** then create a new virtual term like this:
102969 **
102970 **      x IN (expr1,expr2,expr3)
102971 **
102972 ** CASE 2:
102973 **
102974 ** If all subterms are indexable by a single table T, then set
102975 **
102976 **     WhereTerm.eOperator              =  WO_OR
102977 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
102978 **
102979 ** A subterm is "indexable" if it is of the form
102980 ** "T.C <op> <expr>" where C is any column of table T and 
102981 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
102982 ** A subterm is also indexable if it is an AND of two or more
102983 ** subsubterms at least one of which is indexable.  Indexable AND 
102984 ** subterms have their eOperator set to WO_AND and they have
102985 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
102986 **
102987 ** From another point of view, "indexable" means that the subterm could
102988 ** potentially be used with an index if an appropriate index exists.
102989 ** This analysis does not consider whether or not the index exists; that
102990 ** is something the bestIndex() routine will determine.  This analysis
102991 ** only looks at whether subterms appropriate for indexing exist.
102992 **
102993 ** All examples A through E above all satisfy case 2.  But if a term
102994 ** also statisfies case 1 (such as B) we know that the optimizer will
102995 ** always prefer case 1, so in that case we pretend that case 2 is not
102996 ** satisfied.
102997 **
102998 ** It might be the case that multiple tables are indexable.  For example,
102999 ** (E) above is indexable on tables P, Q, and R.
103000 **
103001 ** Terms that satisfy case 2 are candidates for lookup by using
103002 ** separate indices to find rowids for each subterm and composing
103003 ** the union of all rowids using a RowSet object.  This is similar
103004 ** to "bitmap indices" in other database engines.
103005 **
103006 ** OTHERWISE:
103007 **
103008 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
103009 ** zero.  This term is not useful for search.
103010 */
103011 static void exprAnalyzeOrTerm(
103012   SrcList *pSrc,            /* the FROM clause */
103013   WhereClause *pWC,         /* the complete WHERE clause */
103014   int idxTerm               /* Index of the OR-term to be analyzed */
103015 ){
103016   Parse *pParse = pWC->pParse;            /* Parser context */
103017   sqlcipher3 *db = pParse->db;               /* Database connection */
103018   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
103019   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
103020   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
103021   int i;                                  /* Loop counters */
103022   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
103023   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
103024   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
103025   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
103026   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
103027
103028   /*
103029   ** Break the OR clause into its separate subterms.  The subterms are
103030   ** stored in a WhereClause structure containing within the WhereOrInfo
103031   ** object that is attached to the original OR clause term.
103032   */
103033   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
103034   assert( pExpr->op==TK_OR );
103035   pTerm->u.pOrInfo = pOrInfo = sqlcipher3DbMallocZero(db, sizeof(*pOrInfo));
103036   if( pOrInfo==0 ) return;
103037   pTerm->wtFlags |= TERM_ORINFO;
103038   pOrWc = &pOrInfo->wc;
103039   whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103040   whereSplit(pOrWc, pExpr, TK_OR);
103041   exprAnalyzeAll(pSrc, pOrWc);
103042   if( db->mallocFailed ) return;
103043   assert( pOrWc->nTerm>=2 );
103044
103045   /*
103046   ** Compute the set of tables that might satisfy cases 1 or 2.
103047   */
103048   indexable = ~(Bitmask)0;
103049   chngToIN = ~(pWC->vmask);
103050   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
103051     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
103052       WhereAndInfo *pAndInfo;
103053       assert( pOrTerm->eOperator==0 );
103054       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
103055       chngToIN = 0;
103056       pAndInfo = sqlcipher3DbMallocRaw(db, sizeof(*pAndInfo));
103057       if( pAndInfo ){
103058         WhereClause *pAndWC;
103059         WhereTerm *pAndTerm;
103060         int j;
103061         Bitmask b = 0;
103062         pOrTerm->u.pAndInfo = pAndInfo;
103063         pOrTerm->wtFlags |= TERM_ANDINFO;
103064         pOrTerm->eOperator = WO_AND;
103065         pAndWC = &pAndInfo->wc;
103066         whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103067         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
103068         exprAnalyzeAll(pSrc, pAndWC);
103069         pAndWC->pOuter = pWC;
103070         testcase( db->mallocFailed );
103071         if( !db->mallocFailed ){
103072           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
103073             assert( pAndTerm->pExpr );
103074             if( allowedOp(pAndTerm->pExpr->op) ){
103075               b |= getMask(pMaskSet, pAndTerm->leftCursor);
103076             }
103077           }
103078         }
103079         indexable &= b;
103080       }
103081     }else if( pOrTerm->wtFlags & TERM_COPIED ){
103082       /* Skip this term for now.  We revisit it when we process the
103083       ** corresponding TERM_VIRTUAL term */
103084     }else{
103085       Bitmask b;
103086       b = getMask(pMaskSet, pOrTerm->leftCursor);
103087       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
103088         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
103089         b |= getMask(pMaskSet, pOther->leftCursor);
103090       }
103091       indexable &= b;
103092       if( pOrTerm->eOperator!=WO_EQ ){
103093         chngToIN = 0;
103094       }else{
103095         chngToIN &= b;
103096       }
103097     }
103098   }
103099
103100   /*
103101   ** Record the set of tables that satisfy case 2.  The set might be
103102   ** empty.
103103   */
103104   pOrInfo->indexable = indexable;
103105   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
103106
103107   /*
103108   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
103109   ** we have to do some additional checking to see if case 1 really
103110   ** is satisfied.
103111   **
103112   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
103113   ** that there is no possibility of transforming the OR clause into an
103114   ** IN operator because one or more terms in the OR clause contain
103115   ** something other than == on a column in the single table.  The 1-bit
103116   ** case means that every term of the OR clause is of the form
103117   ** "table.column=expr" for some single table.  The one bit that is set
103118   ** will correspond to the common table.  We still need to check to make
103119   ** sure the same column is used on all terms.  The 2-bit case is when
103120   ** the all terms are of the form "table1.column=table2.column".  It
103121   ** might be possible to form an IN operator with either table1.column
103122   ** or table2.column as the LHS if either is common to every term of
103123   ** the OR clause.
103124   **
103125   ** Note that terms of the form "table.column1=table.column2" (the
103126   ** same table on both sizes of the ==) cannot be optimized.
103127   */
103128   if( chngToIN ){
103129     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
103130     int iColumn = -1;         /* Column index on lhs of IN operator */
103131     int iCursor = -1;         /* Table cursor common to all terms */
103132     int j = 0;                /* Loop counter */
103133
103134     /* Search for a table and column that appears on one side or the
103135     ** other of the == operator in every subterm.  That table and column
103136     ** will be recorded in iCursor and iColumn.  There might not be any
103137     ** such table and column.  Set okToChngToIN if an appropriate table
103138     ** and column is found but leave okToChngToIN false if not found.
103139     */
103140     for(j=0; j<2 && !okToChngToIN; j++){
103141       pOrTerm = pOrWc->a;
103142       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
103143         assert( pOrTerm->eOperator==WO_EQ );
103144         pOrTerm->wtFlags &= ~TERM_OR_OK;
103145         if( pOrTerm->leftCursor==iCursor ){
103146           /* This is the 2-bit case and we are on the second iteration and
103147           ** current term is from the first iteration.  So skip this term. */
103148           assert( j==1 );
103149           continue;
103150         }
103151         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
103152           /* This term must be of the form t1.a==t2.b where t2 is in the
103153           ** chngToIN set but t1 is not.  This term will be either preceeded
103154           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
103155           ** and use its inversion. */
103156           testcase( pOrTerm->wtFlags & TERM_COPIED );
103157           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
103158           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
103159           continue;
103160         }
103161         iColumn = pOrTerm->u.leftColumn;
103162         iCursor = pOrTerm->leftCursor;
103163         break;
103164       }
103165       if( i<0 ){
103166         /* No candidate table+column was found.  This can only occur
103167         ** on the second iteration */
103168         assert( j==1 );
103169         assert( (chngToIN&(chngToIN-1))==0 );
103170         assert( chngToIN==getMask(pMaskSet, iCursor) );
103171         break;
103172       }
103173       testcase( j==1 );
103174
103175       /* We have found a candidate table and column.  Check to see if that
103176       ** table and column is common to every term in the OR clause */
103177       okToChngToIN = 1;
103178       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
103179         assert( pOrTerm->eOperator==WO_EQ );
103180         if( pOrTerm->leftCursor!=iCursor ){
103181           pOrTerm->wtFlags &= ~TERM_OR_OK;
103182         }else if( pOrTerm->u.leftColumn!=iColumn ){
103183           okToChngToIN = 0;
103184         }else{
103185           int affLeft, affRight;
103186           /* If the right-hand side is also a column, then the affinities
103187           ** of both right and left sides must be such that no type
103188           ** conversions are required on the right.  (Ticket #2249)
103189           */
103190           affRight = sqlcipher3ExprAffinity(pOrTerm->pExpr->pRight);
103191           affLeft = sqlcipher3ExprAffinity(pOrTerm->pExpr->pLeft);
103192           if( affRight!=0 && affRight!=affLeft ){
103193             okToChngToIN = 0;
103194           }else{
103195             pOrTerm->wtFlags |= TERM_OR_OK;
103196           }
103197         }
103198       }
103199     }
103200
103201     /* At this point, okToChngToIN is true if original pTerm satisfies
103202     ** case 1.  In that case, construct a new virtual term that is 
103203     ** pTerm converted into an IN operator.
103204     **
103205     ** EV: R-00211-15100
103206     */
103207     if( okToChngToIN ){
103208       Expr *pDup;            /* A transient duplicate expression */
103209       ExprList *pList = 0;   /* The RHS of the IN operator */
103210       Expr *pLeft = 0;       /* The LHS of the IN operator */
103211       Expr *pNew;            /* The complete IN operator */
103212
103213       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
103214         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
103215         assert( pOrTerm->eOperator==WO_EQ );
103216         assert( pOrTerm->leftCursor==iCursor );
103217         assert( pOrTerm->u.leftColumn==iColumn );
103218         pDup = sqlcipher3ExprDup(db, pOrTerm->pExpr->pRight, 0);
103219         pList = sqlcipher3ExprListAppend(pWC->pParse, pList, pDup);
103220         pLeft = pOrTerm->pExpr->pLeft;
103221       }
103222       assert( pLeft!=0 );
103223       pDup = sqlcipher3ExprDup(db, pLeft, 0);
103224       pNew = sqlcipher3PExpr(pParse, TK_IN, pDup, 0, 0);
103225       if( pNew ){
103226         int idxNew;
103227         transferJoinMarkings(pNew, pExpr);
103228         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
103229         pNew->x.pList = pList;
103230         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
103231         testcase( idxNew==0 );
103232         exprAnalyze(pSrc, pWC, idxNew);
103233         pTerm = &pWC->a[idxTerm];
103234         pWC->a[idxNew].iParent = idxTerm;
103235         pTerm->nChild = 1;
103236       }else{
103237         sqlcipher3ExprListDelete(db, pList);
103238       }
103239       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
103240     }
103241   }
103242 }
103243 #endif /* !SQLCIPHER_OMIT_OR_OPTIMIZATION && !SQLCIPHER_OMIT_SUBQUERY */
103244
103245
103246 /*
103247 ** The input to this routine is an WhereTerm structure with only the
103248 ** "pExpr" field filled in.  The job of this routine is to analyze the
103249 ** subexpression and populate all the other fields of the WhereTerm
103250 ** structure.
103251 **
103252 ** If the expression is of the form "<expr> <op> X" it gets commuted
103253 ** to the standard form of "X <op> <expr>".
103254 **
103255 ** If the expression is of the form "X <op> Y" where both X and Y are
103256 ** columns, then the original expression is unchanged and a new virtual
103257 ** term of the form "Y <op> X" is added to the WHERE clause and
103258 ** analyzed separately.  The original term is marked with TERM_COPIED
103259 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
103260 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
103261 ** is a commuted copy of a prior term.)  The original term has nChild=1
103262 ** and the copy has idxParent set to the index of the original term.
103263 */
103264 static void exprAnalyze(
103265   SrcList *pSrc,            /* the FROM clause */
103266   WhereClause *pWC,         /* the WHERE clause */
103267   int idxTerm               /* Index of the term to be analyzed */
103268 ){
103269   WhereTerm *pTerm;                /* The term to be analyzed */
103270   WhereMaskSet *pMaskSet;          /* Set of table index masks */
103271   Expr *pExpr;                     /* The expression to be analyzed */
103272   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
103273   Bitmask prereqAll;               /* Prerequesites of pExpr */
103274   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
103275   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
103276   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
103277   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
103278   int op;                          /* Top-level operator.  pExpr->op */
103279   Parse *pParse = pWC->pParse;     /* Parsing context */
103280   sqlcipher3 *db = pParse->db;        /* Database connection */
103281
103282   if( db->mallocFailed ){
103283     return;
103284   }
103285   pTerm = &pWC->a[idxTerm];
103286   pMaskSet = pWC->pMaskSet;
103287   pExpr = pTerm->pExpr;
103288   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
103289   op = pExpr->op;
103290   if( op==TK_IN ){
103291     assert( pExpr->pRight==0 );
103292     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
103293       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
103294     }else{
103295       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
103296     }
103297   }else if( op==TK_ISNULL ){
103298     pTerm->prereqRight = 0;
103299   }else{
103300     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
103301   }
103302   prereqAll = exprTableUsage(pMaskSet, pExpr);
103303   if( ExprHasProperty(pExpr, EP_FromJoin) ){
103304     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
103305     prereqAll |= x;
103306     extraRight = x-1;  /* ON clause terms may not be used with an index
103307                        ** on left table of a LEFT JOIN.  Ticket #3015 */
103308   }
103309   pTerm->prereqAll = prereqAll;
103310   pTerm->leftCursor = -1;
103311   pTerm->iParent = -1;
103312   pTerm->eOperator = 0;
103313   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
103314     Expr *pLeft = pExpr->pLeft;
103315     Expr *pRight = pExpr->pRight;
103316     if( pLeft->op==TK_COLUMN ){
103317       pTerm->leftCursor = pLeft->iTable;
103318       pTerm->u.leftColumn = pLeft->iColumn;
103319       pTerm->eOperator = operatorMask(op);
103320     }
103321     if( pRight && pRight->op==TK_COLUMN ){
103322       WhereTerm *pNew;
103323       Expr *pDup;
103324       if( pTerm->leftCursor>=0 ){
103325         int idxNew;
103326         pDup = sqlcipher3ExprDup(db, pExpr, 0);
103327         if( db->mallocFailed ){
103328           sqlcipher3ExprDelete(db, pDup);
103329           return;
103330         }
103331         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
103332         if( idxNew==0 ) return;
103333         pNew = &pWC->a[idxNew];
103334         pNew->iParent = idxTerm;
103335         pTerm = &pWC->a[idxTerm];
103336         pTerm->nChild = 1;
103337         pTerm->wtFlags |= TERM_COPIED;
103338       }else{
103339         pDup = pExpr;
103340         pNew = pTerm;
103341       }
103342       exprCommute(pParse, pDup);
103343       pLeft = pDup->pLeft;
103344       pNew->leftCursor = pLeft->iTable;
103345       pNew->u.leftColumn = pLeft->iColumn;
103346       testcase( (prereqLeft | extraRight) != prereqLeft );
103347       pNew->prereqRight = prereqLeft | extraRight;
103348       pNew->prereqAll = prereqAll;
103349       pNew->eOperator = operatorMask(pDup->op);
103350     }
103351   }
103352
103353 #ifndef SQLCIPHER_OMIT_BETWEEN_OPTIMIZATION
103354   /* If a term is the BETWEEN operator, create two new virtual terms
103355   ** that define the range that the BETWEEN implements.  For example:
103356   **
103357   **      a BETWEEN b AND c
103358   **
103359   ** is converted into:
103360   **
103361   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
103362   **
103363   ** The two new terms are added onto the end of the WhereClause object.
103364   ** The new terms are "dynamic" and are children of the original BETWEEN
103365   ** term.  That means that if the BETWEEN term is coded, the children are
103366   ** skipped.  Or, if the children are satisfied by an index, the original
103367   ** BETWEEN term is skipped.
103368   */
103369   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
103370     ExprList *pList = pExpr->x.pList;
103371     int i;
103372     static const u8 ops[] = {TK_GE, TK_LE};
103373     assert( pList!=0 );
103374     assert( pList->nExpr==2 );
103375     for(i=0; i<2; i++){
103376       Expr *pNewExpr;
103377       int idxNew;
103378       pNewExpr = sqlcipher3PExpr(pParse, ops[i], 
103379                              sqlcipher3ExprDup(db, pExpr->pLeft, 0),
103380                              sqlcipher3ExprDup(db, pList->a[i].pExpr, 0), 0);
103381       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
103382       testcase( idxNew==0 );
103383       exprAnalyze(pSrc, pWC, idxNew);
103384       pTerm = &pWC->a[idxTerm];
103385       pWC->a[idxNew].iParent = idxTerm;
103386     }
103387     pTerm->nChild = 2;
103388   }
103389 #endif /* SQLCIPHER_OMIT_BETWEEN_OPTIMIZATION */
103390
103391 #if !defined(SQLCIPHER_OMIT_OR_OPTIMIZATION) && !defined(SQLCIPHER_OMIT_SUBQUERY)
103392   /* Analyze a term that is composed of two or more subterms connected by
103393   ** an OR operator.
103394   */
103395   else if( pExpr->op==TK_OR ){
103396     assert( pWC->op==TK_AND );
103397     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
103398     pTerm = &pWC->a[idxTerm];
103399   }
103400 #endif /* SQLCIPHER_OMIT_OR_OPTIMIZATION */
103401
103402 #ifndef SQLCIPHER_OMIT_LIKE_OPTIMIZATION
103403   /* Add constraints to reduce the search space on a LIKE or GLOB
103404   ** operator.
103405   **
103406   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
103407   **
103408   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
103409   **
103410   ** The last character of the prefix "abc" is incremented to form the
103411   ** termination condition "abd".
103412   */
103413   if( pWC->op==TK_AND 
103414    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
103415   ){
103416     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
103417     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
103418     Expr *pNewExpr1;
103419     Expr *pNewExpr2;
103420     int idxNew1;
103421     int idxNew2;
103422     CollSeq *pColl;    /* Collating sequence to use */
103423
103424     pLeft = pExpr->x.pList->a[1].pExpr;
103425     pStr2 = sqlcipher3ExprDup(db, pStr1, 0);
103426     if( !db->mallocFailed ){
103427       u8 c, *pC;       /* Last character before the first wildcard */
103428       pC = (u8*)&pStr2->u.zToken[sqlcipher3Strlen30(pStr2->u.zToken)-1];
103429       c = *pC;
103430       if( noCase ){
103431         /* The point is to increment the last character before the first
103432         ** wildcard.  But if we increment '@', that will push it into the
103433         ** alphabetic range where case conversions will mess up the 
103434         ** inequality.  To avoid this, make sure to also run the full
103435         ** LIKE on all candidate expressions by clearing the isComplete flag
103436         */
103437         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
103438
103439
103440         c = sqlcipher3UpperToLower[c];
103441       }
103442       *pC = c + 1;
103443     }
103444     pColl = sqlcipher3FindCollSeq(db, SQLCIPHER_UTF8, noCase ? "NOCASE" : "BINARY",0);
103445     pNewExpr1 = sqlcipher3PExpr(pParse, TK_GE, 
103446                      sqlcipher3ExprSetColl(sqlcipher3ExprDup(db,pLeft,0), pColl),
103447                      pStr1, 0);
103448     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
103449     testcase( idxNew1==0 );
103450     exprAnalyze(pSrc, pWC, idxNew1);
103451     pNewExpr2 = sqlcipher3PExpr(pParse, TK_LT,
103452                      sqlcipher3ExprSetColl(sqlcipher3ExprDup(db,pLeft,0), pColl),
103453                      pStr2, 0);
103454     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
103455     testcase( idxNew2==0 );
103456     exprAnalyze(pSrc, pWC, idxNew2);
103457     pTerm = &pWC->a[idxTerm];
103458     if( isComplete ){
103459       pWC->a[idxNew1].iParent = idxTerm;
103460       pWC->a[idxNew2].iParent = idxTerm;
103461       pTerm->nChild = 2;
103462     }
103463   }
103464 #endif /* SQLCIPHER_OMIT_LIKE_OPTIMIZATION */
103465
103466 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
103467   /* Add a WO_MATCH auxiliary term to the constraint set if the
103468   ** current expression is of the form:  column MATCH expr.
103469   ** This information is used by the xBestIndex methods of
103470   ** virtual tables.  The native query optimizer does not attempt
103471   ** to do anything with MATCH functions.
103472   */
103473   if( isMatchOfColumn(pExpr) ){
103474     int idxNew;
103475     Expr *pRight, *pLeft;
103476     WhereTerm *pNewTerm;
103477     Bitmask prereqColumn, prereqExpr;
103478
103479     pRight = pExpr->x.pList->a[0].pExpr;
103480     pLeft = pExpr->x.pList->a[1].pExpr;
103481     prereqExpr = exprTableUsage(pMaskSet, pRight);
103482     prereqColumn = exprTableUsage(pMaskSet, pLeft);
103483     if( (prereqExpr & prereqColumn)==0 ){
103484       Expr *pNewExpr;
103485       pNewExpr = sqlcipher3PExpr(pParse, TK_MATCH, 
103486                               0, sqlcipher3ExprDup(db, pRight, 0), 0);
103487       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
103488       testcase( idxNew==0 );
103489       pNewTerm = &pWC->a[idxNew];
103490       pNewTerm->prereqRight = prereqExpr;
103491       pNewTerm->leftCursor = pLeft->iTable;
103492       pNewTerm->u.leftColumn = pLeft->iColumn;
103493       pNewTerm->eOperator = WO_MATCH;
103494       pNewTerm->iParent = idxTerm;
103495       pTerm = &pWC->a[idxTerm];
103496       pTerm->nChild = 1;
103497       pTerm->wtFlags |= TERM_COPIED;
103498       pNewTerm->prereqAll = pTerm->prereqAll;
103499     }
103500   }
103501 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
103502
103503 #ifdef SQLCIPHER_ENABLE_STAT3
103504   /* When sqlcipher_stat3 histogram data is available an operator of the
103505   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
103506   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
103507   ** virtual term of that form.
103508   **
103509   ** Note that the virtual term must be tagged with TERM_VNULL.  This
103510   ** TERM_VNULL tag will suppress the not-null check at the beginning
103511   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
103512   ** the start of the loop will prevent any results from being returned.
103513   */
103514   if( pExpr->op==TK_NOTNULL
103515    && pExpr->pLeft->op==TK_COLUMN
103516    && pExpr->pLeft->iColumn>=0
103517   ){
103518     Expr *pNewExpr;
103519     Expr *pLeft = pExpr->pLeft;
103520     int idxNew;
103521     WhereTerm *pNewTerm;
103522
103523     pNewExpr = sqlcipher3PExpr(pParse, TK_GT,
103524                             sqlcipher3ExprDup(db, pLeft, 0),
103525                             sqlcipher3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
103526
103527     idxNew = whereClauseInsert(pWC, pNewExpr,
103528                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
103529     if( idxNew ){
103530       pNewTerm = &pWC->a[idxNew];
103531       pNewTerm->prereqRight = 0;
103532       pNewTerm->leftCursor = pLeft->iTable;
103533       pNewTerm->u.leftColumn = pLeft->iColumn;
103534       pNewTerm->eOperator = WO_GT;
103535       pNewTerm->iParent = idxTerm;
103536       pTerm = &pWC->a[idxTerm];
103537       pTerm->nChild = 1;
103538       pTerm->wtFlags |= TERM_COPIED;
103539       pNewTerm->prereqAll = pTerm->prereqAll;
103540     }
103541   }
103542 #endif /* SQLCIPHER_ENABLE_STAT */
103543
103544   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
103545   ** an index for tables to the left of the join.
103546   */
103547   pTerm->prereqRight |= extraRight;
103548 }
103549
103550 /*
103551 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
103552 ** a reference to any table other than the iBase table.
103553 */
103554 static int referencesOtherTables(
103555   ExprList *pList,          /* Search expressions in ths list */
103556   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
103557   int iFirst,               /* Be searching with the iFirst-th expression */
103558   int iBase                 /* Ignore references to this table */
103559 ){
103560   Bitmask allowed = ~getMask(pMaskSet, iBase);
103561   while( iFirst<pList->nExpr ){
103562     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
103563       return 1;
103564     }
103565   }
103566   return 0;
103567 }
103568
103569 /*
103570 ** This function searches the expression list passed as the second argument
103571 ** for an expression of type TK_COLUMN that refers to the same column and
103572 ** uses the same collation sequence as the iCol'th column of index pIdx.
103573 ** Argument iBase is the cursor number used for the table that pIdx refers
103574 ** to.
103575 **
103576 ** If such an expression is found, its index in pList->a[] is returned. If
103577 ** no expression is found, -1 is returned.
103578 */
103579 static int findIndexCol(
103580   Parse *pParse,                  /* Parse context */
103581   ExprList *pList,                /* Expression list to search */
103582   int iBase,                      /* Cursor for table associated with pIdx */
103583   Index *pIdx,                    /* Index to match column of */
103584   int iCol                        /* Column of index to match */
103585 ){
103586   int i;
103587   const char *zColl = pIdx->azColl[iCol];
103588
103589   for(i=0; i<pList->nExpr; i++){
103590     Expr *p = pList->a[i].pExpr;
103591     if( p->op==TK_COLUMN
103592      && p->iColumn==pIdx->aiColumn[iCol]
103593      && p->iTable==iBase
103594     ){
103595       CollSeq *pColl = sqlcipher3ExprCollSeq(pParse, p);
103596       if( ALWAYS(pColl) && 0==sqlcipher3StrICmp(pColl->zName, zColl) ){
103597         return i;
103598       }
103599     }
103600   }
103601
103602   return -1;
103603 }
103604
103605 /*
103606 ** This routine determines if pIdx can be used to assist in processing a
103607 ** DISTINCT qualifier. In other words, it tests whether or not using this
103608 ** index for the outer loop guarantees that rows with equal values for
103609 ** all expressions in the pDistinct list are delivered grouped together.
103610 **
103611 ** For example, the query 
103612 **
103613 **   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
103614 **
103615 ** can benefit from any index on columns "b" and "c".
103616 */
103617 static int isDistinctIndex(
103618   Parse *pParse,                  /* Parsing context */
103619   WhereClause *pWC,               /* The WHERE clause */
103620   Index *pIdx,                    /* The index being considered */
103621   int base,                       /* Cursor number for the table pIdx is on */
103622   ExprList *pDistinct,            /* The DISTINCT expressions */
103623   int nEqCol                      /* Number of index columns with == */
103624 ){
103625   Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
103626   int i;                          /* Iterator variable */
103627
103628   if( pIdx->zName==0 || pDistinct==0 || pDistinct->nExpr>=BMS ) return 0;
103629   testcase( pDistinct->nExpr==BMS-1 );
103630
103631   /* Loop through all the expressions in the distinct list. If any of them
103632   ** are not simple column references, return early. Otherwise, test if the
103633   ** WHERE clause contains a "col=X" clause. If it does, the expression
103634   ** can be ignored. If it does not, and the column does not belong to the
103635   ** same table as index pIdx, return early. Finally, if there is no
103636   ** matching "col=X" expression and the column is on the same table as pIdx,
103637   ** set the corresponding bit in variable mask.
103638   */
103639   for(i=0; i<pDistinct->nExpr; i++){
103640     WhereTerm *pTerm;
103641     Expr *p = pDistinct->a[i].pExpr;
103642     if( p->op!=TK_COLUMN ) return 0;
103643     pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
103644     if( pTerm ){
103645       Expr *pX = pTerm->pExpr;
103646       CollSeq *p1 = sqlcipher3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
103647       CollSeq *p2 = sqlcipher3ExprCollSeq(pParse, p);
103648       if( p1==p2 ) continue;
103649     }
103650     if( p->iTable!=base ) return 0;
103651     mask |= (((Bitmask)1) << i);
103652   }
103653
103654   for(i=nEqCol; mask && i<pIdx->nColumn; i++){
103655     int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
103656     if( iExpr<0 ) break;
103657     mask &= ~(((Bitmask)1) << iExpr);
103658   }
103659
103660   return (mask==0);
103661 }
103662
103663
103664 /*
103665 ** Return true if the DISTINCT expression-list passed as the third argument
103666 ** is redundant. A DISTINCT list is redundant if the database contains a
103667 ** UNIQUE index that guarantees that the result of the query will be distinct
103668 ** anyway.
103669 */
103670 static int isDistinctRedundant(
103671   Parse *pParse,
103672   SrcList *pTabList,
103673   WhereClause *pWC,
103674   ExprList *pDistinct
103675 ){
103676   Table *pTab;
103677   Index *pIdx;
103678   int i;                          
103679   int iBase;
103680
103681   /* If there is more than one table or sub-select in the FROM clause of
103682   ** this query, then it will not be possible to show that the DISTINCT 
103683   ** clause is redundant. */
103684   if( pTabList->nSrc!=1 ) return 0;
103685   iBase = pTabList->a[0].iCursor;
103686   pTab = pTabList->a[0].pTab;
103687
103688   /* If any of the expressions is an IPK column on table iBase, then return 
103689   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
103690   ** current SELECT is a correlated sub-query.
103691   */
103692   for(i=0; i<pDistinct->nExpr; i++){
103693     Expr *p = pDistinct->a[i].pExpr;
103694     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
103695   }
103696
103697   /* Loop through all indices on the table, checking each to see if it makes
103698   ** the DISTINCT qualifier redundant. It does so if:
103699   **
103700   **   1. The index is itself UNIQUE, and
103701   **
103702   **   2. All of the columns in the index are either part of the pDistinct
103703   **      list, or else the WHERE clause contains a term of the form "col=X",
103704   **      where X is a constant value. The collation sequences of the
103705   **      comparison and select-list expressions must match those of the index.
103706   */
103707   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
103708     if( pIdx->onError==OE_None ) continue;
103709     for(i=0; i<pIdx->nColumn; i++){
103710       int iCol = pIdx->aiColumn[i];
103711       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) 
103712        && 0>findIndexCol(pParse, pDistinct, iBase, pIdx, i)
103713       ){
103714         break;
103715       }
103716     }
103717     if( i==pIdx->nColumn ){
103718       /* This index implies that the DISTINCT qualifier is redundant. */
103719       return 1;
103720     }
103721   }
103722
103723   return 0;
103724 }
103725
103726 /*
103727 ** This routine decides if pIdx can be used to satisfy the ORDER BY
103728 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
103729 ** ORDER BY clause, this routine returns 0.
103730 **
103731 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
103732 ** left-most table in the FROM clause of that same SELECT statement and
103733 ** the table has a cursor number of "base".  pIdx is an index on pTab.
103734 **
103735 ** nEqCol is the number of columns of pIdx that are used as equality
103736 ** constraints.  Any of these columns may be missing from the ORDER BY
103737 ** clause and the match can still be a success.
103738 **
103739 ** All terms of the ORDER BY that match against the index must be either
103740 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
103741 ** index do not need to satisfy this constraint.)  The *pbRev value is
103742 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
103743 ** the ORDER BY clause is all ASC.
103744 */
103745 static int isSortingIndex(
103746   Parse *pParse,          /* Parsing context */
103747   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
103748   Index *pIdx,            /* The index we are testing */
103749   int base,               /* Cursor number for the table to be sorted */
103750   ExprList *pOrderBy,     /* The ORDER BY clause */
103751   int nEqCol,             /* Number of index columns with == constraints */
103752   int wsFlags,            /* Index usages flags */
103753   int *pbRev              /* Set to 1 if ORDER BY is DESC */
103754 ){
103755   int i, j;                       /* Loop counters */
103756   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
103757   int nTerm;                      /* Number of ORDER BY terms */
103758   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
103759   sqlcipher3 *db = pParse->db;
103760
103761   if( !pOrderBy ) return 0;
103762   if( wsFlags & WHERE_COLUMN_IN ) return 0;
103763   if( pIdx->bUnordered ) return 0;
103764
103765   nTerm = pOrderBy->nExpr;
103766   assert( nTerm>0 );
103767
103768   /* Argument pIdx must either point to a 'real' named index structure, 
103769   ** or an index structure allocated on the stack by bestBtreeIndex() to
103770   ** represent the rowid index that is part of every table.  */
103771   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
103772
103773   /* Match terms of the ORDER BY clause against columns of
103774   ** the index.
103775   **
103776   ** Note that indices have pIdx->nColumn regular columns plus
103777   ** one additional column containing the rowid.  The rowid column
103778   ** of the index is also allowed to match against the ORDER BY
103779   ** clause.
103780   */
103781   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
103782     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
103783     CollSeq *pColl;    /* The collating sequence of pExpr */
103784     int termSortOrder; /* Sort order for this term */
103785     int iColumn;       /* The i-th column of the index.  -1 for rowid */
103786     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
103787     const char *zColl; /* Name of the collating sequence for i-th index term */
103788
103789     pExpr = pTerm->pExpr;
103790     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
103791       /* Can not use an index sort on anything that is not a column in the
103792       ** left-most table of the FROM clause */
103793       break;
103794     }
103795     pColl = sqlcipher3ExprCollSeq(pParse, pExpr);
103796     if( !pColl ){
103797       pColl = db->pDfltColl;
103798     }
103799     if( pIdx->zName && i<pIdx->nColumn ){
103800       iColumn = pIdx->aiColumn[i];
103801       if( iColumn==pIdx->pTable->iPKey ){
103802         iColumn = -1;
103803       }
103804       iSortOrder = pIdx->aSortOrder[i];
103805       zColl = pIdx->azColl[i];
103806     }else{
103807       iColumn = -1;
103808       iSortOrder = 0;
103809       zColl = pColl->zName;
103810     }
103811     if( pExpr->iColumn!=iColumn || sqlcipher3StrICmp(pColl->zName, zColl) ){
103812       /* Term j of the ORDER BY clause does not match column i of the index */
103813       if( i<nEqCol ){
103814         /* If an index column that is constrained by == fails to match an
103815         ** ORDER BY term, that is OK.  Just ignore that column of the index
103816         */
103817         continue;
103818       }else if( i==pIdx->nColumn ){
103819         /* Index column i is the rowid.  All other terms match. */
103820         break;
103821       }else{
103822         /* If an index column fails to match and is not constrained by ==
103823         ** then the index cannot satisfy the ORDER BY constraint.
103824         */
103825         return 0;
103826       }
103827     }
103828     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
103829     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
103830     assert( iSortOrder==0 || iSortOrder==1 );
103831     termSortOrder = iSortOrder ^ pTerm->sortOrder;
103832     if( i>nEqCol ){
103833       if( termSortOrder!=sortOrder ){
103834         /* Indices can only be used if all ORDER BY terms past the
103835         ** equality constraints are all either DESC or ASC. */
103836         return 0;
103837       }
103838     }else{
103839       sortOrder = termSortOrder;
103840     }
103841     j++;
103842     pTerm++;
103843     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
103844       /* If the indexed column is the primary key and everything matches
103845       ** so far and none of the ORDER BY terms to the right reference other
103846       ** tables in the join, then we are assured that the index can be used 
103847       ** to sort because the primary key is unique and so none of the other
103848       ** columns will make any difference
103849       */
103850       j = nTerm;
103851     }
103852   }
103853
103854   *pbRev = sortOrder!=0;
103855   if( j>=nTerm ){
103856     /* All terms of the ORDER BY clause are covered by this index so
103857     ** this index can be used for sorting. */
103858     return 1;
103859   }
103860   if( pIdx->onError!=OE_None && i==pIdx->nColumn
103861       && (wsFlags & WHERE_COLUMN_NULL)==0
103862       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
103863     /* All terms of this index match some prefix of the ORDER BY clause
103864     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
103865     ** clause reference other tables in a join.  If this is all true then
103866     ** the order by clause is superfluous.  Not that if the matching
103867     ** condition is IS NULL then the result is not necessarily unique
103868     ** even on a UNIQUE index, so disallow those cases. */
103869     return 1;
103870   }
103871   return 0;
103872 }
103873
103874 /*
103875 ** Prepare a crude estimate of the logarithm of the input value.
103876 ** The results need not be exact.  This is only used for estimating
103877 ** the total cost of performing operations with O(logN) or O(NlogN)
103878 ** complexity.  Because N is just a guess, it is no great tragedy if
103879 ** logN is a little off.
103880 */
103881 static double estLog(double N){
103882   double logN = 1;
103883   double x = 10;
103884   while( N>x ){
103885     logN += 1;
103886     x *= 10;
103887   }
103888   return logN;
103889 }
103890
103891 /*
103892 ** Two routines for printing the content of an sqlcipher3_index_info
103893 ** structure.  Used for testing and debugging only.  If neither
103894 ** SQLCIPHER_TEST or SQLCIPHER_DEBUG are defined, then these routines
103895 ** are no-ops.
103896 */
103897 #if !defined(SQLCIPHER_OMIT_VIRTUALTABLE) && defined(SQLCIPHER_DEBUG)
103898 static void TRACE_IDX_INPUTS(sqlcipher3_index_info *p){
103899   int i;
103900   if( !sqlcipher3WhereTrace ) return;
103901   for(i=0; i<p->nConstraint; i++){
103902     sqlcipher3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
103903        i,
103904        p->aConstraint[i].iColumn,
103905        p->aConstraint[i].iTermOffset,
103906        p->aConstraint[i].op,
103907        p->aConstraint[i].usable);
103908   }
103909   for(i=0; i<p->nOrderBy; i++){
103910     sqlcipher3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
103911        i,
103912        p->aOrderBy[i].iColumn,
103913        p->aOrderBy[i].desc);
103914   }
103915 }
103916 static void TRACE_IDX_OUTPUTS(sqlcipher3_index_info *p){
103917   int i;
103918   if( !sqlcipher3WhereTrace ) return;
103919   for(i=0; i<p->nConstraint; i++){
103920     sqlcipher3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
103921        i,
103922        p->aConstraintUsage[i].argvIndex,
103923        p->aConstraintUsage[i].omit);
103924   }
103925   sqlcipher3DebugPrintf("  idxNum=%d\n", p->idxNum);
103926   sqlcipher3DebugPrintf("  idxStr=%s\n", p->idxStr);
103927   sqlcipher3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
103928   sqlcipher3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
103929 }
103930 #else
103931 #define TRACE_IDX_INPUTS(A)
103932 #define TRACE_IDX_OUTPUTS(A)
103933 #endif
103934
103935 /* 
103936 ** Required because bestIndex() is called by bestOrClauseIndex() 
103937 */
103938 static void bestIndex(
103939     Parse*, WhereClause*, struct SrcList_item*,
103940     Bitmask, Bitmask, ExprList*, WhereCost*);
103941
103942 /*
103943 ** This routine attempts to find an scanning strategy that can be used 
103944 ** to optimize an 'OR' expression that is part of a WHERE clause. 
103945 **
103946 ** The table associated with FROM clause term pSrc may be either a
103947 ** regular B-Tree table or a virtual table.
103948 */
103949 static void bestOrClauseIndex(
103950   Parse *pParse,              /* The parsing context */
103951   WhereClause *pWC,           /* The WHERE clause */
103952   struct SrcList_item *pSrc,  /* The FROM clause term to search */
103953   Bitmask notReady,           /* Mask of cursors not available for indexing */
103954   Bitmask notValid,           /* Cursors not available for any purpose */
103955   ExprList *pOrderBy,         /* The ORDER BY clause */
103956   WhereCost *pCost            /* Lowest cost query plan */
103957 ){
103958 #ifndef SQLCIPHER_OMIT_OR_OPTIMIZATION
103959   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
103960   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
103961   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
103962   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
103963
103964   /* The OR-clause optimization is disallowed if the INDEXED BY or
103965   ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
103966   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
103967     return;
103968   }
103969   if( pWC->wctrlFlags & WHERE_AND_ONLY ){
103970     return;
103971   }
103972
103973   /* Search the WHERE clause terms for a usable WO_OR term. */
103974   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
103975     if( pTerm->eOperator==WO_OR 
103976      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
103977      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
103978     ){
103979       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
103980       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
103981       WhereTerm *pOrTerm;
103982       int flags = WHERE_MULTI_OR;
103983       double rTotal = 0;
103984       double nRow = 0;
103985       Bitmask used = 0;
103986
103987       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
103988         WhereCost sTermCost;
103989         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
103990           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
103991         ));
103992         if( pOrTerm->eOperator==WO_AND ){
103993           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
103994           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
103995         }else if( pOrTerm->leftCursor==iCur ){
103996           WhereClause tempWC;
103997           tempWC.pParse = pWC->pParse;
103998           tempWC.pMaskSet = pWC->pMaskSet;
103999           tempWC.pOuter = pWC;
104000           tempWC.op = TK_AND;
104001           tempWC.a = pOrTerm;
104002           tempWC.wctrlFlags = 0;
104003           tempWC.nTerm = 1;
104004           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
104005         }else{
104006           continue;
104007         }
104008         rTotal += sTermCost.rCost;
104009         nRow += sTermCost.plan.nRow;
104010         used |= sTermCost.used;
104011         if( rTotal>=pCost->rCost ) break;
104012       }
104013
104014       /* If there is an ORDER BY clause, increase the scan cost to account 
104015       ** for the cost of the sort. */
104016       if( pOrderBy!=0 ){
104017         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
104018                     rTotal, rTotal+nRow*estLog(nRow)));
104019         rTotal += nRow*estLog(nRow);
104020       }
104021
104022       /* If the cost of scanning using this OR term for optimization is
104023       ** less than the current cost stored in pCost, replace the contents
104024       ** of pCost. */
104025       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
104026       if( rTotal<pCost->rCost ){
104027         pCost->rCost = rTotal;
104028         pCost->used = used;
104029         pCost->plan.nRow = nRow;
104030         pCost->plan.wsFlags = flags;
104031         pCost->plan.u.pTerm = pTerm;
104032       }
104033     }
104034   }
104035 #endif /* SQLCIPHER_OMIT_OR_OPTIMIZATION */
104036 }
104037
104038 #ifndef SQLCIPHER_OMIT_AUTOMATIC_INDEX
104039 /*
104040 ** Return TRUE if the WHERE clause term pTerm is of a form where it
104041 ** could be used with an index to access pSrc, assuming an appropriate
104042 ** index existed.
104043 */
104044 static int termCanDriveIndex(
104045   WhereTerm *pTerm,              /* WHERE clause term to check */
104046   struct SrcList_item *pSrc,     /* Table we are trying to access */
104047   Bitmask notReady               /* Tables in outer loops of the join */
104048 ){
104049   char aff;
104050   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
104051   if( pTerm->eOperator!=WO_EQ ) return 0;
104052   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
104053   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
104054   if( !sqlcipher3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
104055   return 1;
104056 }
104057 #endif
104058
104059 #ifndef SQLCIPHER_OMIT_AUTOMATIC_INDEX
104060 /*
104061 ** If the query plan for pSrc specified in pCost is a full table scan
104062 ** and indexing is allows (if there is no NOT INDEXED clause) and it
104063 ** possible to construct a transient index that would perform better
104064 ** than a full table scan even when the cost of constructing the index
104065 ** is taken into account, then alter the query plan to use the
104066 ** transient index.
104067 */
104068 static void bestAutomaticIndex(
104069   Parse *pParse,              /* The parsing context */
104070   WhereClause *pWC,           /* The WHERE clause */
104071   struct SrcList_item *pSrc,  /* The FROM clause term to search */
104072   Bitmask notReady,           /* Mask of cursors that are not available */
104073   WhereCost *pCost            /* Lowest cost query plan */
104074 ){
104075   double nTableRow;           /* Rows in the input table */
104076   double logN;                /* log(nTableRow) */
104077   double costTempIdx;         /* per-query cost of the transient index */
104078   WhereTerm *pTerm;           /* A single term of the WHERE clause */
104079   WhereTerm *pWCEnd;          /* End of pWC->a[] */
104080   Table *pTable;              /* Table tht might be indexed */
104081
104082   if( pParse->nQueryLoop<=(double)1 ){
104083     /* There is no point in building an automatic index for a single scan */
104084     return;
104085   }
104086   if( (pParse->db->flags & SQLCIPHER_AutoIndex)==0 ){
104087     /* Automatic indices are disabled at run-time */
104088     return;
104089   }
104090   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
104091     /* We already have some kind of index in use for this query. */
104092     return;
104093   }
104094   if( pSrc->notIndexed ){
104095     /* The NOT INDEXED clause appears in the SQL. */
104096     return;
104097   }
104098   if( pSrc->isCorrelated ){
104099     /* The source is a correlated sub-query. No point in indexing it. */
104100     return;
104101   }
104102
104103   assert( pParse->nQueryLoop >= (double)1 );
104104   pTable = pSrc->pTab;
104105   nTableRow = pTable->nRowEst;
104106   logN = estLog(nTableRow);
104107   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
104108   if( costTempIdx>=pCost->rCost ){
104109     /* The cost of creating the transient table would be greater than
104110     ** doing the full table scan */
104111     return;
104112   }
104113
104114   /* Search for any equality comparison term */
104115   pWCEnd = &pWC->a[pWC->nTerm];
104116   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104117     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104118       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
104119                     pCost->rCost, costTempIdx));
104120       pCost->rCost = costTempIdx;
104121       pCost->plan.nRow = logN + 1;
104122       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
104123       pCost->used = pTerm->prereqRight;
104124       break;
104125     }
104126   }
104127 }
104128 #else
104129 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
104130 #endif /* SQLCIPHER_OMIT_AUTOMATIC_INDEX */
104131
104132
104133 #ifndef SQLCIPHER_OMIT_AUTOMATIC_INDEX
104134 /*
104135 ** Generate code to construct the Index object for an automatic index
104136 ** and to set up the WhereLevel object pLevel so that the code generator
104137 ** makes use of the automatic index.
104138 */
104139 static void constructAutomaticIndex(
104140   Parse *pParse,              /* The parsing context */
104141   WhereClause *pWC,           /* The WHERE clause */
104142   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
104143   Bitmask notReady,           /* Mask of cursors that are not available */
104144   WhereLevel *pLevel          /* Write new index here */
104145 ){
104146   int nColumn;                /* Number of columns in the constructed index */
104147   WhereTerm *pTerm;           /* A single term of the WHERE clause */
104148   WhereTerm *pWCEnd;          /* End of pWC->a[] */
104149   int nByte;                  /* Byte of memory needed for pIdx */
104150   Index *pIdx;                /* Object describing the transient index */
104151   Vdbe *v;                    /* Prepared statement under construction */
104152   int regIsInit;              /* Register set by initialization */
104153   int addrInit;               /* Address of the initialization bypass jump */
104154   Table *pTable;              /* The table being indexed */
104155   KeyInfo *pKeyinfo;          /* Key information for the index */   
104156   int addrTop;                /* Top of the index fill loop */
104157   int regRecord;              /* Register holding an index record */
104158   int n;                      /* Column counter */
104159   int i;                      /* Loop counter */
104160   int mxBitCol;               /* Maximum column in pSrc->colUsed */
104161   CollSeq *pColl;             /* Collating sequence to on a column */
104162   Bitmask idxCols;            /* Bitmap of columns used for indexing */
104163   Bitmask extraCols;          /* Bitmap of additional columns */
104164
104165   /* Generate code to skip over the creation and initialization of the
104166   ** transient index on 2nd and subsequent iterations of the loop. */
104167   v = pParse->pVdbe;
104168   assert( v!=0 );
104169   regIsInit = ++pParse->nMem;
104170   addrInit = sqlcipher3VdbeAddOp1(v, OP_Once, regIsInit);
104171
104172   /* Count the number of columns that will be added to the index
104173   ** and used to match WHERE clause constraints */
104174   nColumn = 0;
104175   pTable = pSrc->pTab;
104176   pWCEnd = &pWC->a[pWC->nTerm];
104177   idxCols = 0;
104178   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104179     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104180       int iCol = pTerm->u.leftColumn;
104181       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104182       testcase( iCol==BMS );
104183       testcase( iCol==BMS-1 );
104184       if( (idxCols & cMask)==0 ){
104185         nColumn++;
104186         idxCols |= cMask;
104187       }
104188     }
104189   }
104190   assert( nColumn>0 );
104191   pLevel->plan.nEq = nColumn;
104192
104193   /* Count the number of additional columns needed to create a
104194   ** covering index.  A "covering index" is an index that contains all
104195   ** columns that are needed by the query.  With a covering index, the
104196   ** original table never needs to be accessed.  Automatic indices must
104197   ** be a covering index because the index will not be updated if the
104198   ** original table changes and the index and table cannot both be used
104199   ** if they go out of sync.
104200   */
104201   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
104202   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
104203   testcase( pTable->nCol==BMS-1 );
104204   testcase( pTable->nCol==BMS-2 );
104205   for(i=0; i<mxBitCol; i++){
104206     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
104207   }
104208   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
104209     nColumn += pTable->nCol - BMS + 1;
104210   }
104211   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
104212
104213   /* Construct the Index object to describe this index */
104214   nByte = sizeof(Index);
104215   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
104216   nByte += nColumn*sizeof(char*);   /* Index.azColl */
104217   nByte += nColumn;                 /* Index.aSortOrder */
104218   pIdx = sqlcipher3DbMallocZero(pParse->db, nByte);
104219   if( pIdx==0 ) return;
104220   pLevel->plan.u.pIdx = pIdx;
104221   pIdx->azColl = (char**)&pIdx[1];
104222   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
104223   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
104224   pIdx->zName = "auto-index";
104225   pIdx->nColumn = nColumn;
104226   pIdx->pTable = pTable;
104227   n = 0;
104228   idxCols = 0;
104229   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104230     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104231       int iCol = pTerm->u.leftColumn;
104232       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104233       if( (idxCols & cMask)==0 ){
104234         Expr *pX = pTerm->pExpr;
104235         idxCols |= cMask;
104236         pIdx->aiColumn[n] = pTerm->u.leftColumn;
104237         pColl = sqlcipher3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
104238         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
104239         n++;
104240       }
104241     }
104242   }
104243   assert( (u32)n==pLevel->plan.nEq );
104244
104245   /* Add additional columns needed to make the automatic index into
104246   ** a covering index */
104247   for(i=0; i<mxBitCol; i++){
104248     if( extraCols & (((Bitmask)1)<<i) ){
104249       pIdx->aiColumn[n] = i;
104250       pIdx->azColl[n] = "BINARY";
104251       n++;
104252     }
104253   }
104254   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
104255     for(i=BMS-1; i<pTable->nCol; i++){
104256       pIdx->aiColumn[n] = i;
104257       pIdx->azColl[n] = "BINARY";
104258       n++;
104259     }
104260   }
104261   assert( n==nColumn );
104262
104263   /* Create the automatic index */
104264   pKeyinfo = sqlcipher3IndexKeyinfo(pParse, pIdx);
104265   assert( pLevel->iIdxCur>=0 );
104266   sqlcipher3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
104267                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
104268   VdbeComment((v, "for %s", pTable->zName));
104269
104270   /* Fill the automatic index with content */
104271   addrTop = sqlcipher3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
104272   regRecord = sqlcipher3GetTempReg(pParse);
104273   sqlcipher3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
104274   sqlcipher3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
104275   sqlcipher3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
104276   sqlcipher3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
104277   sqlcipher3VdbeChangeP5(v, SQLCIPHER_STMTSTATUS_AUTOINDEX);
104278   sqlcipher3VdbeJumpHere(v, addrTop);
104279   sqlcipher3ReleaseTempReg(pParse, regRecord);
104280   
104281   /* Jump here when skipping the initialization */
104282   sqlcipher3VdbeJumpHere(v, addrInit);
104283 }
104284 #endif /* SQLCIPHER_OMIT_AUTOMATIC_INDEX */
104285
104286 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
104287 /*
104288 ** Allocate and populate an sqlcipher3_index_info structure. It is the 
104289 ** responsibility of the caller to eventually release the structure
104290 ** by passing the pointer returned by this function to sqlcipher3_free().
104291 */
104292 static sqlcipher3_index_info *allocateIndexInfo(
104293   Parse *pParse, 
104294   WhereClause *pWC,
104295   struct SrcList_item *pSrc,
104296   ExprList *pOrderBy
104297 ){
104298   int i, j;
104299   int nTerm;
104300   struct sqlcipher3_index_constraint *pIdxCons;
104301   struct sqlcipher3_index_orderby *pIdxOrderBy;
104302   struct sqlcipher3_index_constraint_usage *pUsage;
104303   WhereTerm *pTerm;
104304   int nOrderBy;
104305   sqlcipher3_index_info *pIdxInfo;
104306
104307   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
104308
104309   /* Count the number of possible WHERE clause constraints referring
104310   ** to this virtual table */
104311   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
104312     if( pTerm->leftCursor != pSrc->iCursor ) continue;
104313     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
104314     testcase( pTerm->eOperator==WO_IN );
104315     testcase( pTerm->eOperator==WO_ISNULL );
104316     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
104317     if( pTerm->wtFlags & TERM_VNULL ) continue;
104318     nTerm++;
104319   }
104320
104321   /* If the ORDER BY clause contains only columns in the current 
104322   ** virtual table then allocate space for the aOrderBy part of
104323   ** the sqlcipher3_index_info structure.
104324   */
104325   nOrderBy = 0;
104326   if( pOrderBy ){
104327     for(i=0; i<pOrderBy->nExpr; i++){
104328       Expr *pExpr = pOrderBy->a[i].pExpr;
104329       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
104330     }
104331     if( i==pOrderBy->nExpr ){
104332       nOrderBy = pOrderBy->nExpr;
104333     }
104334   }
104335
104336   /* Allocate the sqlcipher3_index_info structure
104337   */
104338   pIdxInfo = sqlcipher3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
104339                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
104340                            + sizeof(*pIdxOrderBy)*nOrderBy );
104341   if( pIdxInfo==0 ){
104342     sqlcipher3ErrorMsg(pParse, "out of memory");
104343     /* (double)0 In case of SQLCIPHER_OMIT_FLOATING_POINT... */
104344     return 0;
104345   }
104346
104347   /* Initialize the structure.  The sqlcipher3_index_info structure contains
104348   ** many fields that are declared "const" to prevent xBestIndex from
104349   ** changing them.  We have to do some funky casting in order to
104350   ** initialize those fields.
104351   */
104352   pIdxCons = (struct sqlcipher3_index_constraint*)&pIdxInfo[1];
104353   pIdxOrderBy = (struct sqlcipher3_index_orderby*)&pIdxCons[nTerm];
104354   pUsage = (struct sqlcipher3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
104355   *(int*)&pIdxInfo->nConstraint = nTerm;
104356   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
104357   *(struct sqlcipher3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
104358   *(struct sqlcipher3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
104359   *(struct sqlcipher3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
104360                                                                    pUsage;
104361
104362   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
104363     if( pTerm->leftCursor != pSrc->iCursor ) continue;
104364     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
104365     testcase( pTerm->eOperator==WO_IN );
104366     testcase( pTerm->eOperator==WO_ISNULL );
104367     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
104368     if( pTerm->wtFlags & TERM_VNULL ) continue;
104369     pIdxCons[j].iColumn = pTerm->u.leftColumn;
104370     pIdxCons[j].iTermOffset = i;
104371     pIdxCons[j].op = (u8)pTerm->eOperator;
104372     /* The direct assignment in the previous line is possible only because
104373     ** the WO_ and SQLCIPHER_INDEX_CONSTRAINT_ codes are identical.  The
104374     ** following asserts verify this fact. */
104375     assert( WO_EQ==SQLCIPHER_INDEX_CONSTRAINT_EQ );
104376     assert( WO_LT==SQLCIPHER_INDEX_CONSTRAINT_LT );
104377     assert( WO_LE==SQLCIPHER_INDEX_CONSTRAINT_LE );
104378     assert( WO_GT==SQLCIPHER_INDEX_CONSTRAINT_GT );
104379     assert( WO_GE==SQLCIPHER_INDEX_CONSTRAINT_GE );
104380     assert( WO_MATCH==SQLCIPHER_INDEX_CONSTRAINT_MATCH );
104381     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
104382     j++;
104383   }
104384   for(i=0; i<nOrderBy; i++){
104385     Expr *pExpr = pOrderBy->a[i].pExpr;
104386     pIdxOrderBy[i].iColumn = pExpr->iColumn;
104387     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
104388   }
104389
104390   return pIdxInfo;
104391 }
104392
104393 /*
104394 ** The table object reference passed as the second argument to this function
104395 ** must represent a virtual table. This function invokes the xBestIndex()
104396 ** method of the virtual table with the sqlcipher3_index_info pointer passed
104397 ** as the argument.
104398 **
104399 ** If an error occurs, pParse is populated with an error message and a
104400 ** non-zero value is returned. Otherwise, 0 is returned and the output
104401 ** part of the sqlcipher3_index_info structure is left populated.
104402 **
104403 ** Whether or not an error is returned, it is the responsibility of the
104404 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
104405 ** that this is required.
104406 */
104407 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlcipher3_index_info *p){
104408   sqlcipher3_vtab *pVtab = sqlcipher3GetVTable(pParse->db, pTab)->pVtab;
104409   int i;
104410   int rc;
104411
104412   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
104413   TRACE_IDX_INPUTS(p);
104414   rc = pVtab->pModule->xBestIndex(pVtab, p);
104415   TRACE_IDX_OUTPUTS(p);
104416
104417   if( rc!=SQLCIPHER_OK ){
104418     if( rc==SQLCIPHER_NOMEM ){
104419       pParse->db->mallocFailed = 1;
104420     }else if( !pVtab->zErrMsg ){
104421       sqlcipher3ErrorMsg(pParse, "%s", sqlcipher3ErrStr(rc));
104422     }else{
104423       sqlcipher3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
104424     }
104425   }
104426   sqlcipher3_free(pVtab->zErrMsg);
104427   pVtab->zErrMsg = 0;
104428
104429   for(i=0; i<p->nConstraint; i++){
104430     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
104431       sqlcipher3ErrorMsg(pParse, 
104432           "table %s: xBestIndex returned an invalid plan", pTab->zName);
104433     }
104434   }
104435
104436   return pParse->nErr;
104437 }
104438
104439
104440 /*
104441 ** Compute the best index for a virtual table.
104442 **
104443 ** The best index is computed by the xBestIndex method of the virtual
104444 ** table module.  This routine is really just a wrapper that sets up
104445 ** the sqlcipher3_index_info structure that is used to communicate with
104446 ** xBestIndex.
104447 **
104448 ** In a join, this routine might be called multiple times for the
104449 ** same virtual table.  The sqlcipher3_index_info structure is created
104450 ** and initialized on the first invocation and reused on all subsequent
104451 ** invocations.  The sqlcipher3_index_info structure is also used when
104452 ** code is generated to access the virtual table.  The whereInfoDelete() 
104453 ** routine takes care of freeing the sqlcipher3_index_info structure after
104454 ** everybody has finished with it.
104455 */
104456 static void bestVirtualIndex(
104457   Parse *pParse,                  /* The parsing context */
104458   WhereClause *pWC,               /* The WHERE clause */
104459   struct SrcList_item *pSrc,      /* The FROM clause term to search */
104460   Bitmask notReady,               /* Mask of cursors not available for index */
104461   Bitmask notValid,               /* Cursors not valid for any purpose */
104462   ExprList *pOrderBy,             /* The order by clause */
104463   WhereCost *pCost,               /* Lowest cost query plan */
104464   sqlcipher3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
104465 ){
104466   Table *pTab = pSrc->pTab;
104467   sqlcipher3_index_info *pIdxInfo;
104468   struct sqlcipher3_index_constraint *pIdxCons;
104469   struct sqlcipher3_index_constraint_usage *pUsage;
104470   WhereTerm *pTerm;
104471   int i, j;
104472   int nOrderBy;
104473   double rCost;
104474
104475   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
104476   ** malloc in allocateIndexInfo() fails and this function returns leaving
104477   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
104478   */
104479   memset(pCost, 0, sizeof(*pCost));
104480   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
104481
104482   /* If the sqlcipher3_index_info structure has not been previously
104483   ** allocated and initialized, then allocate and initialize it now.
104484   */
104485   pIdxInfo = *ppIdxInfo;
104486   if( pIdxInfo==0 ){
104487     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
104488   }
104489   if( pIdxInfo==0 ){
104490     return;
104491   }
104492
104493   /* At this point, the sqlcipher3_index_info structure that pIdxInfo points
104494   ** to will have been initialized, either during the current invocation or
104495   ** during some prior invocation.  Now we just have to customize the
104496   ** details of pIdxInfo for the current invocation and pass it to
104497   ** xBestIndex.
104498   */
104499
104500   /* The module name must be defined. Also, by this point there must
104501   ** be a pointer to an sqlcipher3_vtab structure. Otherwise
104502   ** sqlcipher3ViewGetColumnNames() would have picked up the error. 
104503   */
104504   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
104505   assert( sqlcipher3GetVTable(pParse->db, pTab) );
104506
104507   /* Set the aConstraint[].usable fields and initialize all 
104508   ** output variables to zero.
104509   **
104510   ** aConstraint[].usable is true for constraints where the right-hand
104511   ** side contains only references to tables to the left of the current
104512   ** table.  In other words, if the constraint is of the form:
104513   **
104514   **           column = expr
104515   **
104516   ** and we are evaluating a join, then the constraint on column is 
104517   ** only valid if all tables referenced in expr occur to the left
104518   ** of the table containing column.
104519   **
104520   ** The aConstraints[] array contains entries for all constraints
104521   ** on the current table.  That way we only have to compute it once
104522   ** even though we might try to pick the best index multiple times.
104523   ** For each attempt at picking an index, the order of tables in the
104524   ** join might be different so we have to recompute the usable flag
104525   ** each time.
104526   */
104527   pIdxCons = *(struct sqlcipher3_index_constraint**)&pIdxInfo->aConstraint;
104528   pUsage = pIdxInfo->aConstraintUsage;
104529   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
104530     j = pIdxCons->iTermOffset;
104531     pTerm = &pWC->a[j];
104532     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
104533   }
104534   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
104535   if( pIdxInfo->needToFreeIdxStr ){
104536     sqlcipher3_free(pIdxInfo->idxStr);
104537   }
104538   pIdxInfo->idxStr = 0;
104539   pIdxInfo->idxNum = 0;
104540   pIdxInfo->needToFreeIdxStr = 0;
104541   pIdxInfo->orderByConsumed = 0;
104542   /* ((double)2) In case of SQLCIPHER_OMIT_FLOATING_POINT... */
104543   pIdxInfo->estimatedCost = SQLCIPHER_BIG_DBL / ((double)2);
104544   nOrderBy = pIdxInfo->nOrderBy;
104545   if( !pOrderBy ){
104546     pIdxInfo->nOrderBy = 0;
104547   }
104548
104549   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
104550     return;
104551   }
104552
104553   pIdxCons = *(struct sqlcipher3_index_constraint**)&pIdxInfo->aConstraint;
104554   for(i=0; i<pIdxInfo->nConstraint; i++){
104555     if( pUsage[i].argvIndex>0 ){
104556       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
104557     }
104558   }
104559
104560   /* If there is an ORDER BY clause, and the selected virtual table index
104561   ** does not satisfy it, increase the cost of the scan accordingly. This
104562   ** matches the processing for non-virtual tables in bestBtreeIndex().
104563   */
104564   rCost = pIdxInfo->estimatedCost;
104565   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
104566     rCost += estLog(rCost)*rCost;
104567   }
104568
104569   /* The cost is not allowed to be larger than SQLCIPHER_BIG_DBL (the
104570   ** inital value of lowestCost in this loop. If it is, then the
104571   ** (cost<lowestCost) test below will never be true.
104572   ** 
104573   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
104574   ** is defined.
104575   */
104576   if( (SQLCIPHER_BIG_DBL/((double)2))<rCost ){
104577     pCost->rCost = (SQLCIPHER_BIG_DBL/((double)2));
104578   }else{
104579     pCost->rCost = rCost;
104580   }
104581   pCost->plan.u.pVtabIdx = pIdxInfo;
104582   if( pIdxInfo->orderByConsumed ){
104583     pCost->plan.wsFlags |= WHERE_ORDERBY;
104584   }
104585   pCost->plan.nEq = 0;
104586   pIdxInfo->nOrderBy = nOrderBy;
104587
104588   /* Try to find a more efficient access pattern by using multiple indexes
104589   ** to optimize an OR expression within the WHERE clause. 
104590   */
104591   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
104592 }
104593 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
104594
104595 #ifdef SQLCIPHER_ENABLE_STAT3
104596 /*
104597 ** Estimate the location of a particular key among all keys in an
104598 ** index.  Store the results in aStat as follows:
104599 **
104600 **    aStat[0]      Est. number of rows less than pVal
104601 **    aStat[1]      Est. number of rows equal to pVal
104602 **
104603 ** Return SQLCIPHER_OK on success.
104604 */
104605 static int whereKeyStats(
104606   Parse *pParse,              /* Database connection */
104607   Index *pIdx,                /* Index to consider domain of */
104608   sqlcipher3_value *pVal,        /* Value to consider */
104609   int roundUp,                /* Round up if true.  Round down if false */
104610   tRowcnt *aStat              /* OUT: stats written here */
104611 ){
104612   tRowcnt n;
104613   IndexSample *aSample;
104614   int i, eType;
104615   int isEq = 0;
104616   i64 v;
104617   double r, rS;
104618
104619   assert( roundUp==0 || roundUp==1 );
104620   assert( pIdx->nSample>0 );
104621   if( pVal==0 ) return SQLCIPHER_ERROR;
104622   n = pIdx->aiRowEst[0];
104623   aSample = pIdx->aSample;
104624   eType = sqlcipher3_value_type(pVal);
104625
104626   if( eType==SQLCIPHER_INTEGER ){
104627     v = sqlcipher3_value_int64(pVal);
104628     r = (i64)v;
104629     for(i=0; i<pIdx->nSample; i++){
104630       if( aSample[i].eType==SQLCIPHER_NULL ) continue;
104631       if( aSample[i].eType>=SQLCIPHER_TEXT ) break;
104632       if( aSample[i].eType==SQLCIPHER_INTEGER ){
104633         if( aSample[i].u.i>=v ){
104634           isEq = aSample[i].u.i==v;
104635           break;
104636         }
104637       }else{
104638         assert( aSample[i].eType==SQLCIPHER_FLOAT );
104639         if( aSample[i].u.r>=r ){
104640           isEq = aSample[i].u.r==r;
104641           break;
104642         }
104643       }
104644     }
104645   }else if( eType==SQLCIPHER_FLOAT ){
104646     r = sqlcipher3_value_double(pVal);
104647     for(i=0; i<pIdx->nSample; i++){
104648       if( aSample[i].eType==SQLCIPHER_NULL ) continue;
104649       if( aSample[i].eType>=SQLCIPHER_TEXT ) break;
104650       if( aSample[i].eType==SQLCIPHER_FLOAT ){
104651         rS = aSample[i].u.r;
104652       }else{
104653         rS = aSample[i].u.i;
104654       }
104655       if( rS>=r ){
104656         isEq = rS==r;
104657         break;
104658       }
104659     }
104660   }else if( eType==SQLCIPHER_NULL ){
104661     i = 0;
104662     if( aSample[0].eType==SQLCIPHER_NULL ) isEq = 1;
104663   }else{
104664     assert( eType==SQLCIPHER_TEXT || eType==SQLCIPHER_BLOB );
104665     for(i=0; i<pIdx->nSample; i++){
104666       if( aSample[i].eType==SQLCIPHER_TEXT || aSample[i].eType==SQLCIPHER_BLOB ){
104667         break;
104668       }
104669     }
104670     if( i<pIdx->nSample ){      
104671       sqlcipher3 *db = pParse->db;
104672       CollSeq *pColl;
104673       const u8 *z;
104674       if( eType==SQLCIPHER_BLOB ){
104675         z = (const u8 *)sqlcipher3_value_blob(pVal);
104676         pColl = db->pDfltColl;
104677         assert( pColl->enc==SQLCIPHER_UTF8 );
104678       }else{
104679         pColl = sqlcipher3GetCollSeq(db, SQLCIPHER_UTF8, 0, *pIdx->azColl);
104680         if( pColl==0 ){
104681           sqlcipher3ErrorMsg(pParse, "no such collation sequence: %s",
104682                           *pIdx->azColl);
104683           return SQLCIPHER_ERROR;
104684         }
104685         z = (const u8 *)sqlcipher3ValueText(pVal, pColl->enc);
104686         if( !z ){
104687           return SQLCIPHER_NOMEM;
104688         }
104689         assert( z && pColl && pColl->xCmp );
104690       }
104691       n = sqlcipher3ValueBytes(pVal, pColl->enc);
104692   
104693       for(; i<pIdx->nSample; i++){
104694         int c;
104695         int eSampletype = aSample[i].eType;
104696         if( eSampletype<eType ) continue;
104697         if( eSampletype!=eType ) break;
104698 #ifndef SQLCIPHER_OMIT_UTF16
104699         if( pColl->enc!=SQLCIPHER_UTF8 ){
104700           int nSample;
104701           char *zSample = sqlcipher3Utf8to16(
104702               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
104703           );
104704           if( !zSample ){
104705             assert( db->mallocFailed );
104706             return SQLCIPHER_NOMEM;
104707           }
104708           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
104709           sqlcipher3DbFree(db, zSample);
104710         }else
104711 #endif
104712         {
104713           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
104714         }
104715         if( c>=0 ){
104716           if( c==0 ) isEq = 1;
104717           break;
104718         }
104719       }
104720     }
104721   }
104722
104723   /* At this point, aSample[i] is the first sample that is greater than
104724   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
104725   ** than pVal.  If aSample[i]==pVal, then isEq==1.
104726   */
104727   if( isEq ){
104728     assert( i<pIdx->nSample );
104729     aStat[0] = aSample[i].nLt;
104730     aStat[1] = aSample[i].nEq;
104731   }else{
104732     tRowcnt iLower, iUpper, iGap;
104733     if( i==0 ){
104734       iLower = 0;
104735       iUpper = aSample[0].nLt;
104736     }else{
104737       iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
104738       iLower = aSample[i-1].nEq + aSample[i-1].nLt;
104739     }
104740     aStat[1] = pIdx->avgEq;
104741     if( iLower>=iUpper ){
104742       iGap = 0;
104743     }else{
104744       iGap = iUpper - iLower;
104745     }
104746     if( roundUp ){
104747       iGap = (iGap*2)/3;
104748     }else{
104749       iGap = iGap/3;
104750     }
104751     aStat[0] = iLower + iGap;
104752   }
104753   return SQLCIPHER_OK;
104754 }
104755 #endif /* SQLCIPHER_ENABLE_STAT3 */
104756
104757 /*
104758 ** If expression pExpr represents a literal value, set *pp to point to
104759 ** an sqlcipher3_value structure containing the same value, with affinity
104760 ** aff applied to it, before returning. It is the responsibility of the 
104761 ** caller to eventually release this structure by passing it to 
104762 ** sqlcipher3ValueFree().
104763 **
104764 ** If the current parse is a recompile (sqlcipher3Reprepare()) and pExpr
104765 ** is an SQL variable that currently has a non-NULL value bound to it,
104766 ** create an sqlcipher3_value structure containing this value, again with
104767 ** affinity aff applied to it, instead.
104768 **
104769 ** If neither of the above apply, set *pp to NULL.
104770 **
104771 ** If an error occurs, return an error code. Otherwise, SQLCIPHER_OK.
104772 */
104773 #ifdef SQLCIPHER_ENABLE_STAT3
104774 static int valueFromExpr(
104775   Parse *pParse, 
104776   Expr *pExpr, 
104777   u8 aff, 
104778   sqlcipher3_value **pp
104779 ){
104780   if( pExpr->op==TK_VARIABLE
104781    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
104782   ){
104783     int iVar = pExpr->iColumn;
104784     sqlcipher3VdbeSetVarmask(pParse->pVdbe, iVar);
104785     *pp = sqlcipher3VdbeGetValue(pParse->pReprepare, iVar, aff);
104786     return SQLCIPHER_OK;
104787   }
104788   return sqlcipher3ValueFromExpr(pParse->db, pExpr, SQLCIPHER_UTF8, aff, pp);
104789 }
104790 #endif
104791
104792 /*
104793 ** This function is used to estimate the number of rows that will be visited
104794 ** by scanning an index for a range of values. The range may have an upper
104795 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
104796 ** and lower bounds are represented by pLower and pUpper respectively. For
104797 ** example, assuming that index p is on t1(a):
104798 **
104799 **   ... FROM t1 WHERE a > ? AND a < ? ...
104800 **                    |_____|   |_____|
104801 **                       |         |
104802 **                     pLower    pUpper
104803 **
104804 ** If either of the upper or lower bound is not present, then NULL is passed in
104805 ** place of the corresponding WhereTerm.
104806 **
104807 ** The nEq parameter is passed the index of the index column subject to the
104808 ** range constraint. Or, equivalently, the number of equality constraints
104809 ** optimized by the proposed index scan. For example, assuming index p is
104810 ** on t1(a, b), and the SQL query is:
104811 **
104812 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
104813 **
104814 ** then nEq should be passed the value 1 (as the range restricted column,
104815 ** b, is the second left-most column of the index). Or, if the query is:
104816 **
104817 **   ... FROM t1 WHERE a > ? AND a < ? ...
104818 **
104819 ** then nEq should be passed 0.
104820 **
104821 ** The returned value is an integer divisor to reduce the estimated
104822 ** search space.  A return value of 1 means that range constraints are
104823 ** no help at all.  A return value of 2 means range constraints are
104824 ** expected to reduce the search space by half.  And so forth...
104825 **
104826 ** In the absence of sqlcipher_stat3 ANALYZE data, each range inequality
104827 ** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
104828 ** results in a return of 4 and a range constraint (x>? AND x<?) results
104829 ** in a return of 16.
104830 */
104831 static int whereRangeScanEst(
104832   Parse *pParse,       /* Parsing & code generating context */
104833   Index *p,            /* The index containing the range-compared column; "x" */
104834   int nEq,             /* index into p->aCol[] of the range-compared column */
104835   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
104836   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
104837   double *pRangeDiv   /* OUT: Reduce search space by this divisor */
104838 ){
104839   int rc = SQLCIPHER_OK;
104840
104841 #ifdef SQLCIPHER_ENABLE_STAT3
104842
104843   if( nEq==0 && p->nSample ){
104844     sqlcipher3_value *pRangeVal;
104845     tRowcnt iLower = 0;
104846     tRowcnt iUpper = p->aiRowEst[0];
104847     tRowcnt a[2];
104848     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
104849
104850     if( pLower ){
104851       Expr *pExpr = pLower->pExpr->pRight;
104852       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
104853       assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
104854       if( rc==SQLCIPHER_OK
104855        && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLCIPHER_OK
104856       ){
104857         iLower = a[0];
104858         if( pLower->eOperator==WO_GT ) iLower += a[1];
104859       }
104860       sqlcipher3ValueFree(pRangeVal);
104861     }
104862     if( rc==SQLCIPHER_OK && pUpper ){
104863       Expr *pExpr = pUpper->pExpr->pRight;
104864       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
104865       assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
104866       if( rc==SQLCIPHER_OK
104867        && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLCIPHER_OK
104868       ){
104869         iUpper = a[0];
104870         if( pUpper->eOperator==WO_LE ) iUpper += a[1];
104871       }
104872       sqlcipher3ValueFree(pRangeVal);
104873     }
104874     if( rc==SQLCIPHER_OK ){
104875       if( iUpper<=iLower ){
104876         *pRangeDiv = (double)p->aiRowEst[0];
104877       }else{
104878         *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
104879       }
104880       WHERETRACE(("range scan regions: %u..%u  div=%g\n",
104881                   (u32)iLower, (u32)iUpper, *pRangeDiv));
104882       return SQLCIPHER_OK;
104883     }
104884   }
104885 #else
104886   UNUSED_PARAMETER(pParse);
104887   UNUSED_PARAMETER(p);
104888   UNUSED_PARAMETER(nEq);
104889 #endif
104890   assert( pLower || pUpper );
104891   *pRangeDiv = (double)1;
104892   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
104893   if( pUpper ) *pRangeDiv *= (double)4;
104894   return rc;
104895 }
104896
104897 #ifdef SQLCIPHER_ENABLE_STAT3
104898 /*
104899 ** Estimate the number of rows that will be returned based on
104900 ** an equality constraint x=VALUE and where that VALUE occurs in
104901 ** the histogram data.  This only works when x is the left-most
104902 ** column of an index and sqlcipher_stat3 histogram data is available
104903 ** for that index.  When pExpr==NULL that means the constraint is
104904 ** "x IS NULL" instead of "x=VALUE".
104905 **
104906 ** Write the estimated row count into *pnRow and return SQLCIPHER_OK. 
104907 ** If unable to make an estimate, leave *pnRow unchanged and return
104908 ** non-zero.
104909 **
104910 ** This routine can fail if it is unable to load a collating sequence
104911 ** required for string comparison, or if unable to allocate memory
104912 ** for a UTF conversion required for comparison.  The error is stored
104913 ** in the pParse structure.
104914 */
104915 static int whereEqualScanEst(
104916   Parse *pParse,       /* Parsing & code generating context */
104917   Index *p,            /* The index whose left-most column is pTerm */
104918   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
104919   double *pnRow        /* Write the revised row estimate here */
104920 ){
104921   sqlcipher3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
104922   u8 aff;                   /* Column affinity */
104923   int rc;                   /* Subfunction return code */
104924   tRowcnt a[2];             /* Statistics */
104925
104926   assert( p->aSample!=0 );
104927   assert( p->nSample>0 );
104928   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
104929   if( pExpr ){
104930     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
104931     if( rc ) goto whereEqualScanEst_cancel;
104932   }else{
104933     pRhs = sqlcipher3ValueNew(pParse->db);
104934   }
104935   if( pRhs==0 ) return SQLCIPHER_NOTFOUND;
104936   rc = whereKeyStats(pParse, p, pRhs, 0, a);
104937   if( rc==SQLCIPHER_OK ){
104938     WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
104939     *pnRow = a[1];
104940   }
104941 whereEqualScanEst_cancel:
104942   sqlcipher3ValueFree(pRhs);
104943   return rc;
104944 }
104945 #endif /* defined(SQLCIPHER_ENABLE_STAT3) */
104946
104947 #ifdef SQLCIPHER_ENABLE_STAT3
104948 /*
104949 ** Estimate the number of rows that will be returned based on
104950 ** an IN constraint where the right-hand side of the IN operator
104951 ** is a list of values.  Example:
104952 **
104953 **        WHERE x IN (1,2,3,4)
104954 **
104955 ** Write the estimated row count into *pnRow and return SQLCIPHER_OK. 
104956 ** If unable to make an estimate, leave *pnRow unchanged and return
104957 ** non-zero.
104958 **
104959 ** This routine can fail if it is unable to load a collating sequence
104960 ** required for string comparison, or if unable to allocate memory
104961 ** for a UTF conversion required for comparison.  The error is stored
104962 ** in the pParse structure.
104963 */
104964 static int whereInScanEst(
104965   Parse *pParse,       /* Parsing & code generating context */
104966   Index *p,            /* The index whose left-most column is pTerm */
104967   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
104968   double *pnRow        /* Write the revised row estimate here */
104969 ){
104970   int rc = SQLCIPHER_OK;         /* Subfunction return code */
104971   double nEst;                /* Number of rows for a single term */
104972   double nRowEst = (double)0; /* New estimate of the number of rows */
104973   int i;                      /* Loop counter */
104974
104975   assert( p->aSample!=0 );
104976   for(i=0; rc==SQLCIPHER_OK && i<pList->nExpr; i++){
104977     nEst = p->aiRowEst[0];
104978     rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
104979     nRowEst += nEst;
104980   }
104981   if( rc==SQLCIPHER_OK ){
104982     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
104983     *pnRow = nRowEst;
104984     WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
104985   }
104986   return rc;
104987 }
104988 #endif /* defined(SQLCIPHER_ENABLE_STAT3) */
104989
104990
104991 /*
104992 ** Find the best query plan for accessing a particular table.  Write the
104993 ** best query plan and its cost into the WhereCost object supplied as the
104994 ** last parameter.
104995 **
104996 ** The lowest cost plan wins.  The cost is an estimate of the amount of
104997 ** CPU and disk I/O needed to process the requested result.
104998 ** Factors that influence cost include:
104999 **
105000 **    *  The estimated number of rows that will be retrieved.  (The
105001 **       fewer the better.)
105002 **
105003 **    *  Whether or not sorting must occur.
105004 **
105005 **    *  Whether or not there must be separate lookups in the
105006 **       index and in the main table.
105007 **
105008 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
105009 ** the SQL statement, then this function only considers plans using the 
105010 ** named index. If no such plan is found, then the returned cost is
105011 ** SQLCIPHER_BIG_DBL. If a plan is found that uses the named index, 
105012 ** then the cost is calculated in the usual way.
105013 **
105014 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
105015 ** in the SELECT statement, then no indexes are considered. However, the 
105016 ** selected plan may still take advantage of the built-in rowid primary key
105017 ** index.
105018 */
105019 static void bestBtreeIndex(
105020   Parse *pParse,              /* The parsing context */
105021   WhereClause *pWC,           /* The WHERE clause */
105022   struct SrcList_item *pSrc,  /* The FROM clause term to search */
105023   Bitmask notReady,           /* Mask of cursors not available for indexing */
105024   Bitmask notValid,           /* Cursors not available for any purpose */
105025   ExprList *pOrderBy,         /* The ORDER BY clause */
105026   ExprList *pDistinct,        /* The select-list if query is DISTINCT */
105027   WhereCost *pCost            /* Lowest cost query plan */
105028 ){
105029   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
105030   Index *pProbe;              /* An index we are evaluating */
105031   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
105032   int eqTermMask;             /* Current mask of valid equality operators */
105033   int idxEqTermMask;          /* Index mask of valid equality operators */
105034   Index sPk;                  /* A fake index object for the primary key */
105035   tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
105036   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
105037   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
105038
105039   /* Initialize the cost to a worst-case value */
105040   memset(pCost, 0, sizeof(*pCost));
105041   pCost->rCost = SQLCIPHER_BIG_DBL;
105042
105043   /* If the pSrc table is the right table of a LEFT JOIN then we may not
105044   ** use an index to satisfy IS NULL constraints on that table.  This is
105045   ** because columns might end up being NULL if the table does not match -
105046   ** a circumstance which the index cannot help us discover.  Ticket #2177.
105047   */
105048   if( pSrc->jointype & JT_LEFT ){
105049     idxEqTermMask = WO_EQ|WO_IN;
105050   }else{
105051     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
105052   }
105053
105054   if( pSrc->pIndex ){
105055     /* An INDEXED BY clause specifies a particular index to use */
105056     pIdx = pProbe = pSrc->pIndex;
105057     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
105058     eqTermMask = idxEqTermMask;
105059   }else{
105060     /* There is no INDEXED BY clause.  Create a fake Index object in local
105061     ** variable sPk to represent the rowid primary key index.  Make this
105062     ** fake index the first in a chain of Index objects with all of the real
105063     ** indices to follow */
105064     Index *pFirst;                  /* First of real indices on the table */
105065     memset(&sPk, 0, sizeof(Index));
105066     sPk.nColumn = 1;
105067     sPk.aiColumn = &aiColumnPk;
105068     sPk.aiRowEst = aiRowEstPk;
105069     sPk.onError = OE_Replace;
105070     sPk.pTable = pSrc->pTab;
105071     aiRowEstPk[0] = pSrc->pTab->nRowEst;
105072     aiRowEstPk[1] = 1;
105073     pFirst = pSrc->pTab->pIndex;
105074     if( pSrc->notIndexed==0 ){
105075       /* The real indices of the table are only considered if the
105076       ** NOT INDEXED qualifier is omitted from the FROM clause */
105077       sPk.pNext = pFirst;
105078     }
105079     pProbe = &sPk;
105080     wsFlagMask = ~(
105081         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
105082     );
105083     eqTermMask = WO_EQ|WO_IN;
105084     pIdx = 0;
105085   }
105086
105087   /* Loop over all indices looking for the best one to use
105088   */
105089   for(; pProbe; pIdx=pProbe=pProbe->pNext){
105090     const tRowcnt * const aiRowEst = pProbe->aiRowEst;
105091     double cost;                /* Cost of using pProbe */
105092     double nRow;                /* Estimated number of rows in result set */
105093     double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
105094     int rev;                    /* True to scan in reverse order */
105095     int wsFlags = 0;
105096     Bitmask used = 0;
105097
105098     /* The following variables are populated based on the properties of
105099     ** index being evaluated. They are then used to determine the expected
105100     ** cost and number of rows returned.
105101     **
105102     **  nEq: 
105103     **    Number of equality terms that can be implemented using the index.
105104     **    In other words, the number of initial fields in the index that
105105     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
105106     **
105107     **  nInMul:  
105108     **    The "in-multiplier". This is an estimate of how many seek operations 
105109     **    SQLite must perform on the index in question. For example, if the 
105110     **    WHERE clause is:
105111     **
105112     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
105113     **
105114     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
105115     **    set to 9. Given the same schema and either of the following WHERE 
105116     **    clauses:
105117     **
105118     **      WHERE a =  1
105119     **      WHERE a >= 2
105120     **
105121     **    nInMul is set to 1.
105122     **
105123     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
105124     **    the sub-select is assumed to return 25 rows for the purposes of 
105125     **    determining nInMul.
105126     **
105127     **  bInEst:  
105128     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
105129     **    in determining the value of nInMul.  Note that the RHS of the
105130     **    IN operator must be a SELECT, not a value list, for this variable
105131     **    to be true.
105132     **
105133     **  rangeDiv:
105134     **    An estimate of a divisor by which to reduce the search space due
105135     **    to inequality constraints.  In the absence of sqlcipher_stat3 ANALYZE
105136     **    data, a single inequality reduces the search space to 1/4rd its
105137     **    original size (rangeDiv==4).  Two inequalities reduce the search
105138     **    space to 1/16th of its original size (rangeDiv==16).
105139     **
105140     **  bSort:   
105141     **    Boolean. True if there is an ORDER BY clause that will require an 
105142     **    external sort (i.e. scanning the index being evaluated will not 
105143     **    correctly order records).
105144     **
105145     **  bLookup: 
105146     **    Boolean. True if a table lookup is required for each index entry
105147     **    visited.  In other words, true if this is not a covering index.
105148     **    This is always false for the rowid primary key index of a table.
105149     **    For other indexes, it is true unless all the columns of the table
105150     **    used by the SELECT statement are present in the index (such an
105151     **    index is sometimes described as a covering index).
105152     **    For example, given the index on (a, b), the second of the following 
105153     **    two queries requires table b-tree lookups in order to find the value
105154     **    of column c, but the first does not because columns a and b are
105155     **    both available in the index.
105156     **
105157     **             SELECT a, b    FROM tbl WHERE a = 1;
105158     **             SELECT a, b, c FROM tbl WHERE a = 1;
105159     */
105160     int nEq;                      /* Number of == or IN terms matching index */
105161     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
105162     int nInMul = 1;               /* Number of distinct equalities to lookup */
105163     double rangeDiv = (double)1;  /* Estimated reduction in search space */
105164     int nBound = 0;               /* Number of range constraints seen */
105165     int bSort = !!pOrderBy;       /* True if external sort required */
105166     int bDist = !!pDistinct;      /* True if index cannot help with DISTINCT */
105167     int bLookup = 0;              /* True if not a covering index */
105168     WhereTerm *pTerm;             /* A single term of the WHERE clause */
105169 #ifdef SQLCIPHER_ENABLE_STAT3
105170     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
105171 #endif
105172
105173     /* Determine the values of nEq and nInMul */
105174     for(nEq=0; nEq<pProbe->nColumn; nEq++){
105175       int j = pProbe->aiColumn[nEq];
105176       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
105177       if( pTerm==0 ) break;
105178       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
105179       testcase( pTerm->pWC!=pWC );
105180       if( pTerm->eOperator & WO_IN ){
105181         Expr *pExpr = pTerm->pExpr;
105182         wsFlags |= WHERE_COLUMN_IN;
105183         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
105184           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
105185           nInMul *= 25;
105186           bInEst = 1;
105187         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
105188           /* "x IN (value, value, ...)" */
105189           nInMul *= pExpr->x.pList->nExpr;
105190         }
105191       }else if( pTerm->eOperator & WO_ISNULL ){
105192         wsFlags |= WHERE_COLUMN_NULL;
105193       }
105194 #ifdef SQLCIPHER_ENABLE_STAT3
105195       if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
105196 #endif
105197       used |= pTerm->prereqRight;
105198     }
105199
105200     /* Determine the value of rangeDiv */
105201     if( nEq<pProbe->nColumn && pProbe->bUnordered==0 ){
105202       int j = pProbe->aiColumn[nEq];
105203       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
105204         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
105205         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
105206         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &rangeDiv);
105207         if( pTop ){
105208           nBound = 1;
105209           wsFlags |= WHERE_TOP_LIMIT;
105210           used |= pTop->prereqRight;
105211           testcase( pTop->pWC!=pWC );
105212         }
105213         if( pBtm ){
105214           nBound++;
105215           wsFlags |= WHERE_BTM_LIMIT;
105216           used |= pBtm->prereqRight;
105217           testcase( pBtm->pWC!=pWC );
105218         }
105219         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
105220       }
105221     }else if( pProbe->onError!=OE_None ){
105222       testcase( wsFlags & WHERE_COLUMN_IN );
105223       testcase( wsFlags & WHERE_COLUMN_NULL );
105224       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
105225         wsFlags |= WHERE_UNIQUE;
105226       }
105227     }
105228
105229     /* If there is an ORDER BY clause and the index being considered will
105230     ** naturally scan rows in the required order, set the appropriate flags
105231     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
105232     ** will scan rows in a different order, set the bSort variable.  */
105233     if( isSortingIndex(
105234           pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy, nEq, wsFlags, &rev)
105235     ){
105236       bSort = 0;
105237       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
105238       wsFlags |= (rev ? WHERE_REVERSE : 0);
105239     }
105240
105241     /* If there is a DISTINCT qualifier and this index will scan rows in
105242     ** order of the DISTINCT expressions, clear bDist and set the appropriate
105243     ** flags in wsFlags. */
105244     if( isDistinctIndex(pParse, pWC, pProbe, iCur, pDistinct, nEq) ){
105245       bDist = 0;
105246       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
105247     }
105248
105249     /* If currently calculating the cost of using an index (not the IPK
105250     ** index), determine if all required column data may be obtained without 
105251     ** using the main table (i.e. if the index is a covering
105252     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
105253     ** wsFlags. Otherwise, set the bLookup variable to true.  */
105254     if( pIdx && wsFlags ){
105255       Bitmask m = pSrc->colUsed;
105256       int j;
105257       for(j=0; j<pIdx->nColumn; j++){
105258         int x = pIdx->aiColumn[j];
105259         if( x<BMS-1 ){
105260           m &= ~(((Bitmask)1)<<x);
105261         }
105262       }
105263       if( m==0 ){
105264         wsFlags |= WHERE_IDX_ONLY;
105265       }else{
105266         bLookup = 1;
105267       }
105268     }
105269
105270     /*
105271     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
105272     ** constraint, do not let the estimate exceed half the rows in the table.
105273     */
105274     nRow = (double)(aiRowEst[nEq] * nInMul);
105275     if( bInEst && nRow*2>aiRowEst[0] ){
105276       nRow = aiRowEst[0]/2;
105277       nInMul = (int)(nRow / aiRowEst[nEq]);
105278     }
105279
105280 #ifdef SQLCIPHER_ENABLE_STAT3
105281     /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
105282     ** and we do not think that values of x are unique and if histogram
105283     ** data is available for column x, then it might be possible
105284     ** to get a better estimate on the number of rows based on
105285     ** VALUE and how common that value is according to the histogram.
105286     */
105287     if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 && aiRowEst[1]>1 ){
105288       assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
105289       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
105290         testcase( pFirstTerm->eOperator==WO_EQ );
105291         testcase( pFirstTerm->eOperator==WO_ISNULL );
105292         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
105293       }else if( bInEst==0 ){
105294         assert( pFirstTerm->eOperator==WO_IN );
105295         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
105296       }
105297     }
105298 #endif /* SQLCIPHER_ENABLE_STAT3 */
105299
105300     /* Adjust the number of output rows and downward to reflect rows
105301     ** that are excluded by range constraints.
105302     */
105303     nRow = nRow/rangeDiv;
105304     if( nRow<1 ) nRow = 1;
105305
105306     /* Experiments run on real SQLite databases show that the time needed
105307     ** to do a binary search to locate a row in a table or index is roughly
105308     ** log10(N) times the time to move from one row to the next row within
105309     ** a table or index.  The actual times can vary, with the size of
105310     ** records being an important factor.  Both moves and searches are
105311     ** slower with larger records, presumably because fewer records fit
105312     ** on one page and hence more pages have to be fetched.
105313     **
105314     ** The ANALYZE command and the sqlcipher_stat1 and sqlcipher_stat3 tables do
105315     ** not give us data on the relative sizes of table and index records.
105316     ** So this computation assumes table records are about twice as big
105317     ** as index records
105318     */
105319     if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
105320       /* The cost of a full table scan is a number of move operations equal
105321       ** to the number of rows in the table.
105322       **
105323       ** We add an additional 4x penalty to full table scans.  This causes
105324       ** the cost function to err on the side of choosing an index over
105325       ** choosing a full scan.  This 4x full-scan penalty is an arguable
105326       ** decision and one which we expect to revisit in the future.  But
105327       ** it seems to be working well enough at the moment.
105328       */
105329       cost = aiRowEst[0]*4;
105330     }else{
105331       log10N = estLog(aiRowEst[0]);
105332       cost = nRow;
105333       if( pIdx ){
105334         if( bLookup ){
105335           /* For an index lookup followed by a table lookup:
105336           **    nInMul index searches to find the start of each index range
105337           **  + nRow steps through the index
105338           **  + nRow table searches to lookup the table entry using the rowid
105339           */
105340           cost += (nInMul + nRow)*log10N;
105341         }else{
105342           /* For a covering index:
105343           **     nInMul index searches to find the initial entry 
105344           **   + nRow steps through the index
105345           */
105346           cost += nInMul*log10N;
105347         }
105348       }else{
105349         /* For a rowid primary key lookup:
105350         **    nInMult table searches to find the initial entry for each range
105351         **  + nRow steps through the table
105352         */
105353         cost += nInMul*log10N;
105354       }
105355     }
105356
105357     /* Add in the estimated cost of sorting the result.  Actual experimental
105358     ** measurements of sorting performance in SQLite show that sorting time
105359     ** adds C*N*log10(N) to the cost, where N is the number of rows to be 
105360     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
105361     ** difference and select C of 3.0.
105362     */
105363     if( bSort ){
105364       cost += nRow*estLog(nRow)*3;
105365     }
105366     if( bDist ){
105367       cost += nRow*estLog(nRow)*3;
105368     }
105369
105370     /**** Cost of using this index has now been computed ****/
105371
105372     /* If there are additional constraints on this table that cannot
105373     ** be used with the current index, but which might lower the number
105374     ** of output rows, adjust the nRow value accordingly.  This only 
105375     ** matters if the current index is the least costly, so do not bother
105376     ** with this step if we already know this index will not be chosen.
105377     ** Also, never reduce the output row count below 2 using this step.
105378     **
105379     ** It is critical that the notValid mask be used here instead of
105380     ** the notReady mask.  When computing an "optimal" index, the notReady
105381     ** mask will only have one bit set - the bit for the current table.
105382     ** The notValid mask, on the other hand, always has all bits set for
105383     ** tables that are not in outer loops.  If notReady is used here instead
105384     ** of notValid, then a optimal index that depends on inner joins loops
105385     ** might be selected even when there exists an optimal index that has
105386     ** no such dependency.
105387     */
105388     if( nRow>2 && cost<=pCost->rCost ){
105389       int k;                       /* Loop counter */
105390       int nSkipEq = nEq;           /* Number of == constraints to skip */
105391       int nSkipRange = nBound;     /* Number of < constraints to skip */
105392       Bitmask thisTab;             /* Bitmap for pSrc */
105393
105394       thisTab = getMask(pWC->pMaskSet, iCur);
105395       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
105396         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
105397         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
105398         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
105399           if( nSkipEq ){
105400             /* Ignore the first nEq equality matches since the index
105401             ** has already accounted for these */
105402             nSkipEq--;
105403           }else{
105404             /* Assume each additional equality match reduces the result
105405             ** set size by a factor of 10 */
105406             nRow /= 10;
105407           }
105408         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
105409           if( nSkipRange ){
105410             /* Ignore the first nSkipRange range constraints since the index
105411             ** has already accounted for these */
105412             nSkipRange--;
105413           }else{
105414             /* Assume each additional range constraint reduces the result
105415             ** set size by a factor of 3.  Indexed range constraints reduce
105416             ** the search space by a larger factor: 4.  We make indexed range
105417             ** more selective intentionally because of the subjective 
105418             ** observation that indexed range constraints really are more
105419             ** selective in practice, on average. */
105420             nRow /= 3;
105421           }
105422         }else if( pTerm->eOperator!=WO_NOOP ){
105423           /* Any other expression lowers the output row count by half */
105424           nRow /= 2;
105425         }
105426       }
105427       if( nRow<2 ) nRow = 2;
105428     }
105429
105430
105431     WHERETRACE((
105432       "%s(%s): nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
105433       "         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
105434       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
105435       nEq, nInMul, (int)rangeDiv, bSort, bLookup, wsFlags,
105436       notReady, log10N, nRow, cost, used
105437     ));
105438
105439     /* If this index is the best we have seen so far, then record this
105440     ** index and its cost in the pCost structure.
105441     */
105442     if( (!pIdx || wsFlags)
105443      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
105444     ){
105445       pCost->rCost = cost;
105446       pCost->used = used;
105447       pCost->plan.nRow = nRow;
105448       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
105449       pCost->plan.nEq = nEq;
105450       pCost->plan.u.pIdx = pIdx;
105451     }
105452
105453     /* If there was an INDEXED BY clause, then only that one index is
105454     ** considered. */
105455     if( pSrc->pIndex ) break;
105456
105457     /* Reset masks for the next index in the loop */
105458     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
105459     eqTermMask = idxEqTermMask;
105460   }
105461
105462   /* If there is no ORDER BY clause and the SQLCIPHER_ReverseOrder flag
105463   ** is set, then reverse the order that the index will be scanned
105464   ** in. This is used for application testing, to help find cases
105465   ** where application behaviour depends on the (undefined) order that
105466   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
105467   if( !pOrderBy && pParse->db->flags & SQLCIPHER_ReverseOrder ){
105468     pCost->plan.wsFlags |= WHERE_REVERSE;
105469   }
105470
105471   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
105472   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
105473   assert( pSrc->pIndex==0 
105474        || pCost->plan.u.pIdx==0 
105475        || pCost->plan.u.pIdx==pSrc->pIndex 
105476   );
105477
105478   WHERETRACE(("best index is: %s\n", 
105479     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 
105480          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
105481   ));
105482   
105483   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
105484   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
105485   pCost->plan.wsFlags |= eqTermMask;
105486 }
105487
105488 /*
105489 ** Find the query plan for accessing table pSrc->pTab. Write the
105490 ** best query plan and its cost into the WhereCost object supplied 
105491 ** as the last parameter. This function may calculate the cost of
105492 ** both real and virtual table scans.
105493 */
105494 static void bestIndex(
105495   Parse *pParse,              /* The parsing context */
105496   WhereClause *pWC,           /* The WHERE clause */
105497   struct SrcList_item *pSrc,  /* The FROM clause term to search */
105498   Bitmask notReady,           /* Mask of cursors not available for indexing */
105499   Bitmask notValid,           /* Cursors not available for any purpose */
105500   ExprList *pOrderBy,         /* The ORDER BY clause */
105501   WhereCost *pCost            /* Lowest cost query plan */
105502 ){
105503 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
105504   if( IsVirtual(pSrc->pTab) ){
105505     sqlcipher3_index_info *p = 0;
105506     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
105507     if( p->needToFreeIdxStr ){
105508       sqlcipher3_free(p->idxStr);
105509     }
105510     sqlcipher3DbFree(pParse->db, p);
105511   }else
105512 #endif
105513   {
105514     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, 0, pCost);
105515   }
105516 }
105517
105518 /*
105519 ** Disable a term in the WHERE clause.  Except, do not disable the term
105520 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
105521 ** or USING clause of that join.
105522 **
105523 ** Consider the term t2.z='ok' in the following queries:
105524 **
105525 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
105526 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
105527 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
105528 **
105529 ** The t2.z='ok' is disabled in the in (2) because it originates
105530 ** in the ON clause.  The term is disabled in (3) because it is not part
105531 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
105532 **
105533 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
105534 ** completely satisfied by indices.
105535 **
105536 ** Disabling a term causes that term to not be tested in the inner loop
105537 ** of the join.  Disabling is an optimization.  When terms are satisfied
105538 ** by indices, we disable them to prevent redundant tests in the inner
105539 ** loop.  We would get the correct results if nothing were ever disabled,
105540 ** but joins might run a little slower.  The trick is to disable as much
105541 ** as we can without disabling too much.  If we disabled in (1), we'd get
105542 ** the wrong answer.  See ticket #813.
105543 */
105544 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
105545   if( pTerm
105546       && (pTerm->wtFlags & TERM_CODED)==0
105547       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
105548   ){
105549     pTerm->wtFlags |= TERM_CODED;
105550     if( pTerm->iParent>=0 ){
105551       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
105552       if( (--pOther->nChild)==0 ){
105553         disableTerm(pLevel, pOther);
105554       }
105555     }
105556   }
105557 }
105558
105559 /*
105560 ** Code an OP_Affinity opcode to apply the column affinity string zAff
105561 ** to the n registers starting at base. 
105562 **
105563 ** As an optimization, SQLCIPHER_AFF_NONE entries (which are no-ops) at the
105564 ** beginning and end of zAff are ignored.  If all entries in zAff are
105565 ** SQLCIPHER_AFF_NONE, then no code gets generated.
105566 **
105567 ** This routine makes its own copy of zAff so that the caller is free
105568 ** to modify zAff after this routine returns.
105569 */
105570 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
105571   Vdbe *v = pParse->pVdbe;
105572   if( zAff==0 ){
105573     assert( pParse->db->mallocFailed );
105574     return;
105575   }
105576   assert( v!=0 );
105577
105578   /* Adjust base and n to skip over SQLCIPHER_AFF_NONE entries at the beginning
105579   ** and end of the affinity string.
105580   */
105581   while( n>0 && zAff[0]==SQLCIPHER_AFF_NONE ){
105582     n--;
105583     base++;
105584     zAff++;
105585   }
105586   while( n>1 && zAff[n-1]==SQLCIPHER_AFF_NONE ){
105587     n--;
105588   }
105589
105590   /* Code the OP_Affinity opcode if there is anything left to do. */
105591   if( n>0 ){
105592     sqlcipher3VdbeAddOp2(v, OP_Affinity, base, n);
105593     sqlcipher3VdbeChangeP4(v, -1, zAff, n);
105594     sqlcipher3ExprCacheAffinityChange(pParse, base, n);
105595   }
105596 }
105597
105598
105599 /*
105600 ** Generate code for a single equality term of the WHERE clause.  An equality
105601 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
105602 ** coded.
105603 **
105604 ** The current value for the constraint is left in register iReg.
105605 **
105606 ** For a constraint of the form X=expr, the expression is evaluated and its
105607 ** result is left on the stack.  For constraints of the form X IN (...)
105608 ** this routine sets up a loop that will iterate over all values of X.
105609 */
105610 static int codeEqualityTerm(
105611   Parse *pParse,      /* The parsing context */
105612   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
105613   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
105614   int iTarget         /* Attempt to leave results in this register */
105615 ){
105616   Expr *pX = pTerm->pExpr;
105617   Vdbe *v = pParse->pVdbe;
105618   int iReg;                  /* Register holding results */
105619
105620   assert( iTarget>0 );
105621   if( pX->op==TK_EQ ){
105622     iReg = sqlcipher3ExprCodeTarget(pParse, pX->pRight, iTarget);
105623   }else if( pX->op==TK_ISNULL ){
105624     iReg = iTarget;
105625     sqlcipher3VdbeAddOp2(v, OP_Null, 0, iReg);
105626 #ifndef SQLCIPHER_OMIT_SUBQUERY
105627   }else{
105628     int eType;
105629     int iTab;
105630     struct InLoop *pIn;
105631
105632     assert( pX->op==TK_IN );
105633     iReg = iTarget;
105634     eType = sqlcipher3FindInIndex(pParse, pX, 0);
105635     iTab = pX->iTable;
105636     sqlcipher3VdbeAddOp2(v, OP_Rewind, iTab, 0);
105637     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
105638     if( pLevel->u.in.nIn==0 ){
105639       pLevel->addrNxt = sqlcipher3VdbeMakeLabel(v);
105640     }
105641     pLevel->u.in.nIn++;
105642     pLevel->u.in.aInLoop =
105643        sqlcipher3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
105644                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
105645     pIn = pLevel->u.in.aInLoop;
105646     if( pIn ){
105647       pIn += pLevel->u.in.nIn - 1;
105648       pIn->iCur = iTab;
105649       if( eType==IN_INDEX_ROWID ){
105650         pIn->addrInTop = sqlcipher3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
105651       }else{
105652         pIn->addrInTop = sqlcipher3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
105653       }
105654       sqlcipher3VdbeAddOp1(v, OP_IsNull, iReg);
105655     }else{
105656       pLevel->u.in.nIn = 0;
105657     }
105658 #endif
105659   }
105660   disableTerm(pLevel, pTerm);
105661   return iReg;
105662 }
105663
105664 /*
105665 ** Generate code that will evaluate all == and IN constraints for an
105666 ** index.
105667 **
105668 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
105669 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
105670 ** The index has as many as three equality constraints, but in this
105671 ** example, the third "c" value is an inequality.  So only two 
105672 ** constraints are coded.  This routine will generate code to evaluate
105673 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
105674 ** in consecutive registers and the index of the first register is returned.
105675 **
105676 ** In the example above nEq==2.  But this subroutine works for any value
105677 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
105678 ** The only thing it does is allocate the pLevel->iMem memory cell and
105679 ** compute the affinity string.
105680 **
105681 ** This routine always allocates at least one memory cell and returns
105682 ** the index of that memory cell. The code that
105683 ** calls this routine will use that memory cell to store the termination
105684 ** key value of the loop.  If one or more IN operators appear, then
105685 ** this routine allocates an additional nEq memory cells for internal
105686 ** use.
105687 **
105688 ** Before returning, *pzAff is set to point to a buffer containing a
105689 ** copy of the column affinity string of the index allocated using
105690 ** sqlcipher3DbMalloc(). Except, entries in the copy of the string associated
105691 ** with equality constraints that use NONE affinity are set to
105692 ** SQLCIPHER_AFF_NONE. This is to deal with SQL such as the following:
105693 **
105694 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
105695 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
105696 **
105697 ** In the example above, the index on t1(a) has TEXT affinity. But since
105698 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
105699 ** no conversion should be attempted before using a t2.b value as part of
105700 ** a key to search the index. Hence the first byte in the returned affinity
105701 ** string in this example would be set to SQLCIPHER_AFF_NONE.
105702 */
105703 static int codeAllEqualityTerms(
105704   Parse *pParse,        /* Parsing context */
105705   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
105706   WhereClause *pWC,     /* The WHERE clause */
105707   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
105708   int nExtraReg,        /* Number of extra registers to allocate */
105709   char **pzAff          /* OUT: Set to point to affinity string */
105710 ){
105711   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
105712   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
105713   Index *pIdx;                  /* The index being used for this loop */
105714   int iCur = pLevel->iTabCur;   /* The cursor of the table */
105715   WhereTerm *pTerm;             /* A single constraint term */
105716   int j;                        /* Loop counter */
105717   int regBase;                  /* Base register */
105718   int nReg;                     /* Number of registers to allocate */
105719   char *zAff;                   /* Affinity string to return */
105720
105721   /* This module is only called on query plans that use an index. */
105722   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
105723   pIdx = pLevel->plan.u.pIdx;
105724
105725   /* Figure out how many memory cells we will need then allocate them.
105726   */
105727   regBase = pParse->nMem + 1;
105728   nReg = pLevel->plan.nEq + nExtraReg;
105729   pParse->nMem += nReg;
105730
105731   zAff = sqlcipher3DbStrDup(pParse->db, sqlcipher3IndexAffinityStr(v, pIdx));
105732   if( !zAff ){
105733     pParse->db->mallocFailed = 1;
105734   }
105735
105736   /* Evaluate the equality constraints
105737   */
105738   assert( pIdx->nColumn>=nEq );
105739   for(j=0; j<nEq; j++){
105740     int r1;
105741     int k = pIdx->aiColumn[j];
105742     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
105743     if( NEVER(pTerm==0) ) break;
105744     /* The following true for indices with redundant columns. 
105745     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
105746     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
105747     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
105748     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
105749     if( r1!=regBase+j ){
105750       if( nReg==1 ){
105751         sqlcipher3ReleaseTempReg(pParse, regBase);
105752         regBase = r1;
105753       }else{
105754         sqlcipher3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
105755       }
105756     }
105757     testcase( pTerm->eOperator & WO_ISNULL );
105758     testcase( pTerm->eOperator & WO_IN );
105759     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
105760       Expr *pRight = pTerm->pExpr->pRight;
105761       sqlcipher3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
105762       if( zAff ){
105763         if( sqlcipher3CompareAffinity(pRight, zAff[j])==SQLCIPHER_AFF_NONE ){
105764           zAff[j] = SQLCIPHER_AFF_NONE;
105765         }
105766         if( sqlcipher3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
105767           zAff[j] = SQLCIPHER_AFF_NONE;
105768         }
105769       }
105770     }
105771   }
105772   *pzAff = zAff;
105773   return regBase;
105774 }
105775
105776 #ifndef SQLCIPHER_OMIT_EXPLAIN
105777 /*
105778 ** This routine is a helper for explainIndexRange() below
105779 **
105780 ** pStr holds the text of an expression that we are building up one term
105781 ** at a time.  This routine adds a new term to the end of the expression.
105782 ** Terms are separated by AND so add the "AND" text for second and subsequent
105783 ** terms only.
105784 */
105785 static void explainAppendTerm(
105786   StrAccum *pStr,             /* The text expression being built */
105787   int iTerm,                  /* Index of this term.  First is zero */
105788   const char *zColumn,        /* Name of the column */
105789   const char *zOp             /* Name of the operator */
105790 ){
105791   if( iTerm ) sqlcipher3StrAccumAppend(pStr, " AND ", 5);
105792   sqlcipher3StrAccumAppend(pStr, zColumn, -1);
105793   sqlcipher3StrAccumAppend(pStr, zOp, 1);
105794   sqlcipher3StrAccumAppend(pStr, "?", 1);
105795 }
105796
105797 /*
105798 ** Argument pLevel describes a strategy for scanning table pTab. This 
105799 ** function returns a pointer to a string buffer containing a description
105800 ** of the subset of table rows scanned by the strategy in the form of an
105801 ** SQL expression. Or, if all rows are scanned, NULL is returned.
105802 **
105803 ** For example, if the query:
105804 **
105805 **   SELECT * FROM t1 WHERE a=1 AND b>2;
105806 **
105807 ** is run and there is an index on (a, b), then this function returns a
105808 ** string similar to:
105809 **
105810 **   "a=? AND b>?"
105811 **
105812 ** The returned pointer points to memory obtained from sqlcipher3DbMalloc().
105813 ** It is the responsibility of the caller to free the buffer when it is
105814 ** no longer required.
105815 */
105816 static char *explainIndexRange(sqlcipher3 *db, WhereLevel *pLevel, Table *pTab){
105817   WherePlan *pPlan = &pLevel->plan;
105818   Index *pIndex = pPlan->u.pIdx;
105819   int nEq = pPlan->nEq;
105820   int i, j;
105821   Column *aCol = pTab->aCol;
105822   int *aiColumn = pIndex->aiColumn;
105823   StrAccum txt;
105824
105825   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
105826     return 0;
105827   }
105828   sqlcipher3StrAccumInit(&txt, 0, 0, SQLCIPHER_MAX_LENGTH);
105829   txt.db = db;
105830   sqlcipher3StrAccumAppend(&txt, " (", 2);
105831   for(i=0; i<nEq; i++){
105832     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
105833   }
105834
105835   j = i;
105836   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
105837     explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
105838   }
105839   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
105840     explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
105841   }
105842   sqlcipher3StrAccumAppend(&txt, ")", 1);
105843   return sqlcipher3StrAccumFinish(&txt);
105844 }
105845
105846 /*
105847 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
105848 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
105849 ** record is added to the output to describe the table scan strategy in 
105850 ** pLevel.
105851 */
105852 static void explainOneScan(
105853   Parse *pParse,                  /* Parse context */
105854   SrcList *pTabList,              /* Table list this loop refers to */
105855   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
105856   int iLevel,                     /* Value for "level" column of output */
105857   int iFrom,                      /* Value for "from" column of output */
105858   u16 wctrlFlags                  /* Flags passed to sqlcipher3WhereBegin() */
105859 ){
105860   if( pParse->explain==2 ){
105861     u32 flags = pLevel->plan.wsFlags;
105862     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
105863     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
105864     sqlcipher3 *db = pParse->db;     /* Database handle */
105865     char *zMsg;                   /* Text to add to EQP output */
105866     sqlcipher3_int64 nRow;           /* Expected number of rows visited by scan */
105867     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
105868     int isSearch;                 /* True for a SEARCH. False for SCAN. */
105869
105870     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
105871
105872     isSearch = (pLevel->plan.nEq>0)
105873              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
105874              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
105875
105876     zMsg = sqlcipher3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
105877     if( pItem->pSelect ){
105878       zMsg = sqlcipher3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
105879     }else{
105880       zMsg = sqlcipher3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
105881     }
105882
105883     if( pItem->zAlias ){
105884       zMsg = sqlcipher3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
105885     }
105886     if( (flags & WHERE_INDEXED)!=0 ){
105887       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
105888       zMsg = sqlcipher3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg, 
105889           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
105890           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
105891           ((flags & WHERE_TEMP_INDEX)?"":" "),
105892           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
105893           zWhere
105894       );
105895       sqlcipher3DbFree(db, zWhere);
105896     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
105897       zMsg = sqlcipher3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
105898
105899       if( flags&WHERE_ROWID_EQ ){
105900         zMsg = sqlcipher3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
105901       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
105902         zMsg = sqlcipher3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
105903       }else if( flags&WHERE_BTM_LIMIT ){
105904         zMsg = sqlcipher3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
105905       }else if( flags&WHERE_TOP_LIMIT ){
105906         zMsg = sqlcipher3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
105907       }
105908     }
105909 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
105910     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
105911       sqlcipher3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
105912       zMsg = sqlcipher3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
105913                   pVtabIdx->idxNum, pVtabIdx->idxStr);
105914     }
105915 #endif
105916     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
105917       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
105918       nRow = 1;
105919     }else{
105920       nRow = (sqlcipher3_int64)pLevel->plan.nRow;
105921     }
105922     zMsg = sqlcipher3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
105923     sqlcipher3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
105924   }
105925 }
105926 #else
105927 # define explainOneScan(u,v,w,x,y,z)
105928 #endif /* SQLCIPHER_OMIT_EXPLAIN */
105929
105930
105931 /*
105932 ** Generate code for the start of the iLevel-th loop in the WHERE clause
105933 ** implementation described by pWInfo.
105934 */
105935 static Bitmask codeOneLoopStart(
105936   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
105937   int iLevel,          /* Which level of pWInfo->a[] should be coded */
105938   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqlcipherInt.h */
105939   Bitmask notReady,    /* Which tables are currently available */
105940   Expr *pWhere         /* Complete WHERE clause */
105941 ){
105942   int j, k;            /* Loop counters */
105943   int iCur;            /* The VDBE cursor for the table */
105944   int addrNxt;         /* Where to jump to continue with the next IN case */
105945   int omitTable;       /* True if we use the index only */
105946   int bRev;            /* True if we need to scan in reverse order */
105947   WhereLevel *pLevel;  /* The where level to be coded */
105948   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
105949   WhereTerm *pTerm;               /* A WHERE clause term */
105950   Parse *pParse;                  /* Parsing context */
105951   Vdbe *v;                        /* The prepared stmt under constructions */
105952   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
105953   int addrBrk;                    /* Jump here to break out of the loop */
105954   int addrCont;                   /* Jump here to continue with next cycle */
105955   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
105956   int iReleaseReg = 0;      /* Temp register to free before returning */
105957
105958   pParse = pWInfo->pParse;
105959   v = pParse->pVdbe;
105960   pWC = pWInfo->pWC;
105961   pLevel = &pWInfo->a[iLevel];
105962   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
105963   iCur = pTabItem->iCursor;
105964   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
105965   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
105966            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
105967
105968   /* Create labels for the "break" and "continue" instructions
105969   ** for the current loop.  Jump to addrBrk to break out of a loop.
105970   ** Jump to cont to go immediately to the next iteration of the
105971   ** loop.
105972   **
105973   ** When there is an IN operator, we also have a "addrNxt" label that
105974   ** means to continue with the next IN value combination.  When
105975   ** there are no IN operators in the constraints, the "addrNxt" label
105976   ** is the same as "addrBrk".
105977   */
105978   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlcipher3VdbeMakeLabel(v);
105979   addrCont = pLevel->addrCont = sqlcipher3VdbeMakeLabel(v);
105980
105981   /* If this is the right table of a LEFT OUTER JOIN, allocate and
105982   ** initialize a memory cell that records if this table matches any
105983   ** row of the left table of the join.
105984   */
105985   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
105986     pLevel->iLeftJoin = ++pParse->nMem;
105987     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
105988     VdbeComment((v, "init LEFT JOIN no-match flag"));
105989   }
105990
105991 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
105992   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
105993     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
105994     **          to access the data.
105995     */
105996     int iReg;   /* P3 Value for OP_VFilter */
105997     sqlcipher3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
105998     int nConstraint = pVtabIdx->nConstraint;
105999     struct sqlcipher3_index_constraint_usage *aUsage =
106000                                                 pVtabIdx->aConstraintUsage;
106001     const struct sqlcipher3_index_constraint *aConstraint =
106002                                                 pVtabIdx->aConstraint;
106003
106004     sqlcipher3ExprCachePush(pParse);
106005     iReg = sqlcipher3GetTempRange(pParse, nConstraint+2);
106006     for(j=1; j<=nConstraint; j++){
106007       for(k=0; k<nConstraint; k++){
106008         if( aUsage[k].argvIndex==j ){
106009           int iTerm = aConstraint[k].iTermOffset;
106010           sqlcipher3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
106011           break;
106012         }
106013       }
106014       if( k==nConstraint ) break;
106015     }
106016     sqlcipher3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
106017     sqlcipher3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
106018     sqlcipher3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
106019                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
106020     pVtabIdx->needToFreeIdxStr = 0;
106021     for(j=0; j<nConstraint; j++){
106022       if( aUsage[j].omit ){
106023         int iTerm = aConstraint[j].iTermOffset;
106024         disableTerm(pLevel, &pWC->a[iTerm]);
106025       }
106026     }
106027     pLevel->op = OP_VNext;
106028     pLevel->p1 = iCur;
106029     pLevel->p2 = sqlcipher3VdbeCurrentAddr(v);
106030     sqlcipher3ReleaseTempRange(pParse, iReg, nConstraint+2);
106031     sqlcipher3ExprCachePop(pParse, 1);
106032   }else
106033 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
106034
106035   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
106036     /* Case 1:  We can directly reference a single row using an
106037     **          equality comparison against the ROWID field.  Or
106038     **          we reference multiple rows using a "rowid IN (...)"
106039     **          construct.
106040     */
106041     iReleaseReg = sqlcipher3GetTempReg(pParse);
106042     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
106043     assert( pTerm!=0 );
106044     assert( pTerm->pExpr!=0 );
106045     assert( pTerm->leftCursor==iCur );
106046     assert( omitTable==0 );
106047     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106048     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
106049     addrNxt = pLevel->addrNxt;
106050     sqlcipher3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
106051     sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
106052     sqlcipher3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106053     VdbeComment((v, "pk"));
106054     pLevel->op = OP_Noop;
106055   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
106056     /* Case 2:  We have an inequality comparison against the ROWID field.
106057     */
106058     int testOp = OP_Noop;
106059     int start;
106060     int memEndValue = 0;
106061     WhereTerm *pStart, *pEnd;
106062
106063     assert( omitTable==0 );
106064     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
106065     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
106066     if( bRev ){
106067       pTerm = pStart;
106068       pStart = pEnd;
106069       pEnd = pTerm;
106070     }
106071     if( pStart ){
106072       Expr *pX;             /* The expression that defines the start bound */
106073       int r1, rTemp;        /* Registers for holding the start boundary */
106074
106075       /* The following constant maps TK_xx codes into corresponding 
106076       ** seek opcodes.  It depends on a particular ordering of TK_xx
106077       */
106078       const u8 aMoveOp[] = {
106079            /* TK_GT */  OP_SeekGt,
106080            /* TK_LE */  OP_SeekLe,
106081            /* TK_LT */  OP_SeekLt,
106082            /* TK_GE */  OP_SeekGe
106083       };
106084       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
106085       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
106086       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
106087
106088       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106089       pX = pStart->pExpr;
106090       assert( pX!=0 );
106091       assert( pStart->leftCursor==iCur );
106092       r1 = sqlcipher3ExprCodeTemp(pParse, pX->pRight, &rTemp);
106093       sqlcipher3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
106094       VdbeComment((v, "pk"));
106095       sqlcipher3ExprCacheAffinityChange(pParse, r1, 1);
106096       sqlcipher3ReleaseTempReg(pParse, rTemp);
106097       disableTerm(pLevel, pStart);
106098     }else{
106099       sqlcipher3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
106100     }
106101     if( pEnd ){
106102       Expr *pX;
106103       pX = pEnd->pExpr;
106104       assert( pX!=0 );
106105       assert( pEnd->leftCursor==iCur );
106106       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106107       memEndValue = ++pParse->nMem;
106108       sqlcipher3ExprCode(pParse, pX->pRight, memEndValue);
106109       if( pX->op==TK_LT || pX->op==TK_GT ){
106110         testOp = bRev ? OP_Le : OP_Ge;
106111       }else{
106112         testOp = bRev ? OP_Lt : OP_Gt;
106113       }
106114       disableTerm(pLevel, pEnd);
106115     }
106116     start = sqlcipher3VdbeCurrentAddr(v);
106117     pLevel->op = bRev ? OP_Prev : OP_Next;
106118     pLevel->p1 = iCur;
106119     pLevel->p2 = start;
106120     if( pStart==0 && pEnd==0 ){
106121       pLevel->p5 = SQLCIPHER_STMTSTATUS_FULLSCAN_STEP;
106122     }else{
106123       assert( pLevel->p5==0 );
106124     }
106125     if( testOp!=OP_Noop ){
106126       iRowidReg = iReleaseReg = sqlcipher3GetTempReg(pParse);
106127       sqlcipher3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
106128       sqlcipher3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106129       sqlcipher3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
106130       sqlcipher3VdbeChangeP5(v, SQLCIPHER_AFF_NUMERIC | SQLCIPHER_JUMPIFNULL);
106131     }
106132   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
106133     /* Case 3: A scan using an index.
106134     **
106135     **         The WHERE clause may contain zero or more equality 
106136     **         terms ("==" or "IN" operators) that refer to the N
106137     **         left-most columns of the index. It may also contain
106138     **         inequality constraints (>, <, >= or <=) on the indexed
106139     **         column that immediately follows the N equalities. Only 
106140     **         the right-most column can be an inequality - the rest must
106141     **         use the "==" and "IN" operators. For example, if the 
106142     **         index is on (x,y,z), then the following clauses are all 
106143     **         optimized:
106144     **
106145     **            x=5
106146     **            x=5 AND y=10
106147     **            x=5 AND y<10
106148     **            x=5 AND y>5 AND y<10
106149     **            x=5 AND y=5 AND z<=10
106150     **
106151     **         The z<10 term of the following cannot be used, only
106152     **         the x=5 term:
106153     **
106154     **            x=5 AND z<10
106155     **
106156     **         N may be zero if there are inequality constraints.
106157     **         If there are no inequality constraints, then N is at
106158     **         least one.
106159     **
106160     **         This case is also used when there are no WHERE clause
106161     **         constraints but an index is selected anyway, in order
106162     **         to force the output order to conform to an ORDER BY.
106163     */  
106164     static const u8 aStartOp[] = {
106165       0,
106166       0,
106167       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
106168       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
106169       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
106170       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
106171       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
106172       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
106173     };
106174     static const u8 aEndOp[] = {
106175       OP_Noop,             /* 0: (!end_constraints) */
106176       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
106177       OP_IdxLT             /* 2: (end_constraints && bRev) */
106178     };
106179     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
106180     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
106181     int regBase;                 /* Base register holding constraint values */
106182     int r1;                      /* Temp register */
106183     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
106184     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
106185     int startEq;                 /* True if range start uses ==, >= or <= */
106186     int endEq;                   /* True if range end uses ==, >= or <= */
106187     int start_constraints;       /* Start of range is constrained */
106188     int nConstraint;             /* Number of constraint terms */
106189     Index *pIdx;                 /* The index we will be using */
106190     int iIdxCur;                 /* The VDBE cursor for the index */
106191     int nExtraReg = 0;           /* Number of extra registers needed */
106192     int op;                      /* Instruction opcode */
106193     char *zStartAff;             /* Affinity for start of range constraint */
106194     char *zEndAff;               /* Affinity for end of range constraint */
106195
106196     pIdx = pLevel->plan.u.pIdx;
106197     iIdxCur = pLevel->iIdxCur;
106198     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
106199
106200     /* If this loop satisfies a sort order (pOrderBy) request that 
106201     ** was passed to this function to implement a "SELECT min(x) ..." 
106202     ** query, then the caller will only allow the loop to run for
106203     ** a single iteration. This means that the first row returned
106204     ** should not have a NULL value stored in 'x'. If column 'x' is
106205     ** the first one after the nEq equality constraints in the index,
106206     ** this requires some special handling.
106207     */
106208     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
106209      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
106210      && (pIdx->nColumn>nEq)
106211     ){
106212       /* assert( pOrderBy->nExpr==1 ); */
106213       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
106214       isMinQuery = 1;
106215       nExtraReg = 1;
106216     }
106217
106218     /* Find any inequality constraint terms for the start and end 
106219     ** of the range. 
106220     */
106221     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
106222       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
106223       nExtraReg = 1;
106224     }
106225     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
106226       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
106227       nExtraReg = 1;
106228     }
106229
106230     /* Generate code to evaluate all constraint terms using == or IN
106231     ** and store the values of those terms in an array of registers
106232     ** starting at regBase.
106233     */
106234     regBase = codeAllEqualityTerms(
106235         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
106236     );
106237     zEndAff = sqlcipher3DbStrDup(pParse->db, zStartAff);
106238     addrNxt = pLevel->addrNxt;
106239
106240     /* If we are doing a reverse order scan on an ascending index, or
106241     ** a forward order scan on a descending index, interchange the 
106242     ** start and end terms (pRangeStart and pRangeEnd).
106243     */
106244     if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLCIPHER_SO_ASC) ){
106245       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
106246     }
106247
106248     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
106249     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
106250     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
106251     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
106252     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
106253     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
106254     start_constraints = pRangeStart || nEq>0;
106255
106256     /* Seek the index cursor to the start of the range. */
106257     nConstraint = nEq;
106258     if( pRangeStart ){
106259       Expr *pRight = pRangeStart->pExpr->pRight;
106260       sqlcipher3ExprCode(pParse, pRight, regBase+nEq);
106261       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
106262         sqlcipher3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
106263       }
106264       if( zStartAff ){
106265         if( sqlcipher3CompareAffinity(pRight, zStartAff[nEq])==SQLCIPHER_AFF_NONE){
106266           /* Since the comparison is to be performed with no conversions
106267           ** applied to the operands, set the affinity to apply to pRight to 
106268           ** SQLCIPHER_AFF_NONE.  */
106269           zStartAff[nEq] = SQLCIPHER_AFF_NONE;
106270         }
106271         if( sqlcipher3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
106272           zStartAff[nEq] = SQLCIPHER_AFF_NONE;
106273         }
106274       }  
106275       nConstraint++;
106276       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106277     }else if( isMinQuery ){
106278       sqlcipher3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
106279       nConstraint++;
106280       startEq = 0;
106281       start_constraints = 1;
106282     }
106283     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
106284     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
106285     assert( op!=0 );
106286     testcase( op==OP_Rewind );
106287     testcase( op==OP_Last );
106288     testcase( op==OP_SeekGt );
106289     testcase( op==OP_SeekGe );
106290     testcase( op==OP_SeekLe );
106291     testcase( op==OP_SeekLt );
106292     sqlcipher3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
106293
106294     /* Load the value for the inequality constraint at the end of the
106295     ** range (if any).
106296     */
106297     nConstraint = nEq;
106298     if( pRangeEnd ){
106299       Expr *pRight = pRangeEnd->pExpr->pRight;
106300       sqlcipher3ExprCacheRemove(pParse, regBase+nEq, 1);
106301       sqlcipher3ExprCode(pParse, pRight, regBase+nEq);
106302       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
106303         sqlcipher3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
106304       }
106305       if( zEndAff ){
106306         if( sqlcipher3CompareAffinity(pRight, zEndAff[nEq])==SQLCIPHER_AFF_NONE){
106307           /* Since the comparison is to be performed with no conversions
106308           ** applied to the operands, set the affinity to apply to pRight to 
106309           ** SQLCIPHER_AFF_NONE.  */
106310           zEndAff[nEq] = SQLCIPHER_AFF_NONE;
106311         }
106312         if( sqlcipher3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
106313           zEndAff[nEq] = SQLCIPHER_AFF_NONE;
106314         }
106315       }  
106316       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
106317       nConstraint++;
106318       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106319     }
106320     sqlcipher3DbFree(pParse->db, zStartAff);
106321     sqlcipher3DbFree(pParse->db, zEndAff);
106322
106323     /* Top of the loop body */
106324     pLevel->p2 = sqlcipher3VdbeCurrentAddr(v);
106325
106326     /* Check if the index cursor is past the end of the range. */
106327     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
106328     testcase( op==OP_Noop );
106329     testcase( op==OP_IdxGE );
106330     testcase( op==OP_IdxLT );
106331     if( op!=OP_Noop ){
106332       sqlcipher3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
106333       sqlcipher3VdbeChangeP5(v, endEq!=bRev ?1:0);
106334     }
106335
106336     /* If there are inequality constraints, check that the value
106337     ** of the table column that the inequality contrains is not NULL.
106338     ** If it is, jump to the next iteration of the loop.
106339     */
106340     r1 = sqlcipher3GetTempReg(pParse);
106341     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
106342     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
106343     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
106344       sqlcipher3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
106345       sqlcipher3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
106346     }
106347     sqlcipher3ReleaseTempReg(pParse, r1);
106348
106349     /* Seek the table cursor, if required */
106350     disableTerm(pLevel, pRangeStart);
106351     disableTerm(pLevel, pRangeEnd);
106352     if( !omitTable ){
106353       iRowidReg = iReleaseReg = sqlcipher3GetTempReg(pParse);
106354       sqlcipher3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
106355       sqlcipher3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106356       sqlcipher3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
106357     }
106358
106359     /* Record the instruction used to terminate the loop. Disable 
106360     ** WHERE clause terms made redundant by the index range scan.
106361     */
106362     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
106363       pLevel->op = OP_Noop;
106364     }else if( bRev ){
106365       pLevel->op = OP_Prev;
106366     }else{
106367       pLevel->op = OP_Next;
106368     }
106369     pLevel->p1 = iIdxCur;
106370   }else
106371
106372 #ifndef SQLCIPHER_OMIT_OR_OPTIMIZATION
106373   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
106374     /* Case 4:  Two or more separately indexed terms connected by OR
106375     **
106376     ** Example:
106377     **
106378     **   CREATE TABLE t1(a,b,c,d);
106379     **   CREATE INDEX i1 ON t1(a);
106380     **   CREATE INDEX i2 ON t1(b);
106381     **   CREATE INDEX i3 ON t1(c);
106382     **
106383     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
106384     **
106385     ** In the example, there are three indexed terms connected by OR.
106386     ** The top of the loop looks like this:
106387     **
106388     **          Null       1                # Zero the rowset in reg 1
106389     **
106390     ** Then, for each indexed term, the following. The arguments to
106391     ** RowSetTest are such that the rowid of the current row is inserted
106392     ** into the RowSet. If it is already present, control skips the
106393     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
106394     **
106395     **        sqlcipher3WhereBegin(<term>)
106396     **          RowSetTest                  # Insert rowid into rowset
106397     **          Gosub      2 A
106398     **        sqlcipher3WhereEnd()
106399     **
106400     ** Following the above, code to terminate the loop. Label A, the target
106401     ** of the Gosub above, jumps to the instruction right after the Goto.
106402     **
106403     **          Null       1                # Zero the rowset in reg 1
106404     **          Goto       B                # The loop is finished.
106405     **
106406     **       A: <loop body>                 # Return data, whatever.
106407     **
106408     **          Return     2                # Jump back to the Gosub
106409     **
106410     **       B: <after the loop>
106411     **
106412     */
106413     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
106414     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
106415
106416     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
106417     int regRowset = 0;                        /* Register for RowSet object */
106418     int regRowid = 0;                         /* Register holding rowid */
106419     int iLoopBody = sqlcipher3VdbeMakeLabel(v);  /* Start of loop body */
106420     int iRetInit;                             /* Address of regReturn init */
106421     int untestedTerms = 0;             /* Some terms not completely tested */
106422     int ii;                            /* Loop counter */
106423     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
106424    
106425     pTerm = pLevel->plan.u.pTerm;
106426     assert( pTerm!=0 );
106427     assert( pTerm->eOperator==WO_OR );
106428     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
106429     pOrWc = &pTerm->u.pOrInfo->wc;
106430     pLevel->op = OP_Return;
106431     pLevel->p1 = regReturn;
106432
106433     /* Set up a new SrcList ni pOrTab containing the table being scanned
106434     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
106435     ** This becomes the SrcList in the recursive call to sqlcipher3WhereBegin().
106436     */
106437     if( pWInfo->nLevel>1 ){
106438       int nNotReady;                 /* The number of notReady tables */
106439       struct SrcList_item *origSrc;     /* Original list of tables */
106440       nNotReady = pWInfo->nLevel - iLevel - 1;
106441       pOrTab = sqlcipher3StackAllocRaw(pParse->db,
106442                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
106443       if( pOrTab==0 ) return notReady;
106444       pOrTab->nAlloc = (i16)(nNotReady + 1);
106445       pOrTab->nSrc = pOrTab->nAlloc;
106446       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
106447       origSrc = pWInfo->pTabList->a;
106448       for(k=1; k<=nNotReady; k++){
106449         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
106450       }
106451     }else{
106452       pOrTab = pWInfo->pTabList;
106453     }
106454
106455     /* Initialize the rowset register to contain NULL. An SQL NULL is 
106456     ** equivalent to an empty rowset.
106457     **
106458     ** Also initialize regReturn to contain the address of the instruction 
106459     ** immediately following the OP_Return at the bottom of the loop. This
106460     ** is required in a few obscure LEFT JOIN cases where control jumps
106461     ** over the top of the loop into the body of it. In this case the 
106462     ** correct response for the end-of-loop code (the OP_Return) is to 
106463     ** fall through to the next instruction, just as an OP_Next does if
106464     ** called on an uninitialized cursor.
106465     */
106466     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
106467       regRowset = ++pParse->nMem;
106468       regRowid = ++pParse->nMem;
106469       sqlcipher3VdbeAddOp2(v, OP_Null, 0, regRowset);
106470     }
106471     iRetInit = sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regReturn);
106472
106473     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
106474     ** Then for every term xN, evaluate as the subexpression: xN AND z
106475     ** That way, terms in y that are factored into the disjunction will
106476     ** be picked up by the recursive calls to sqlcipher3WhereBegin() below.
106477     */
106478     if( pWC->nTerm>1 ){
106479       pAndExpr = sqlcipher3ExprAlloc(pParse->db, TK_AND, 0, 0);
106480       pAndExpr->pRight = pWhere;
106481     }
106482
106483     for(ii=0; ii<pOrWc->nTerm; ii++){
106484       WhereTerm *pOrTerm = &pOrWc->a[ii];
106485       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
106486         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
106487         Expr *pOrExpr = pOrTerm->pExpr;
106488         if( pAndExpr ){
106489           pAndExpr->pLeft = pOrExpr;
106490           pOrExpr = pAndExpr;
106491         }
106492         /* Loop through table entries that match term pOrTerm. */
106493         pSubWInfo = sqlcipher3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
106494                         WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
106495                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
106496         if( pSubWInfo ){
106497           explainOneScan(
106498               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
106499           );
106500           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
106501             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
106502             int r;
106503             r = sqlcipher3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
106504                                          regRowid);
106505             sqlcipher3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
106506                                  sqlcipher3VdbeCurrentAddr(v)+2, r, iSet);
106507           }
106508           sqlcipher3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
106509
106510           /* The pSubWInfo->untestedTerms flag means that this OR term
106511           ** contained one or more AND term from a notReady table.  The
106512           ** terms from the notReady table could not be tested and will
106513           ** need to be tested later.
106514           */
106515           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
106516
106517           /* Finish the loop through table entries that match term pOrTerm. */
106518           sqlcipher3WhereEnd(pSubWInfo);
106519         }
106520       }
106521     }
106522     sqlcipher3DbFree(pParse->db, pAndExpr);
106523     sqlcipher3VdbeChangeP1(v, iRetInit, sqlcipher3VdbeCurrentAddr(v));
106524     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
106525     sqlcipher3VdbeResolveLabel(v, iLoopBody);
106526
106527     if( pWInfo->nLevel>1 ) sqlcipher3StackFree(pParse->db, pOrTab);
106528     if( !untestedTerms ) disableTerm(pLevel, pTerm);
106529   }else
106530 #endif /* SQLCIPHER_OMIT_OR_OPTIMIZATION */
106531
106532   {
106533     /* Case 5:  There is no usable index.  We must do a complete
106534     **          scan of the entire table.
106535     */
106536     static const u8 aStep[] = { OP_Next, OP_Prev };
106537     static const u8 aStart[] = { OP_Rewind, OP_Last };
106538     assert( bRev==0 || bRev==1 );
106539     assert( omitTable==0 );
106540     pLevel->op = aStep[bRev];
106541     pLevel->p1 = iCur;
106542     pLevel->p2 = 1 + sqlcipher3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
106543     pLevel->p5 = SQLCIPHER_STMTSTATUS_FULLSCAN_STEP;
106544   }
106545   notReady &= ~getMask(pWC->pMaskSet, iCur);
106546
106547   /* Insert code to test every subexpression that can be completely
106548   ** computed using the current set of tables.
106549   **
106550   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
106551   ** the use of indices become tests that are evaluated against each row of
106552   ** the relevant input tables.
106553   */
106554   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
106555     Expr *pE;
106556     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
106557     testcase( pTerm->wtFlags & TERM_CODED );
106558     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
106559     if( (pTerm->prereqAll & notReady)!=0 ){
106560       testcase( pWInfo->untestedTerms==0
106561                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
106562       pWInfo->untestedTerms = 1;
106563       continue;
106564     }
106565     pE = pTerm->pExpr;
106566     assert( pE!=0 );
106567     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
106568       continue;
106569     }
106570     sqlcipher3ExprIfFalse(pParse, pE, addrCont, SQLCIPHER_JUMPIFNULL);
106571     pTerm->wtFlags |= TERM_CODED;
106572   }
106573
106574   /* For a LEFT OUTER JOIN, generate code that will record the fact that
106575   ** at least one row of the right table has matched the left table.  
106576   */
106577   if( pLevel->iLeftJoin ){
106578     pLevel->addrFirst = sqlcipher3VdbeCurrentAddr(v);
106579     sqlcipher3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
106580     VdbeComment((v, "record LEFT JOIN hit"));
106581     sqlcipher3ExprCacheClear(pParse);
106582     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
106583       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
106584       testcase( pTerm->wtFlags & TERM_CODED );
106585       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
106586       if( (pTerm->prereqAll & notReady)!=0 ){
106587         assert( pWInfo->untestedTerms );
106588         continue;
106589       }
106590       assert( pTerm->pExpr );
106591       sqlcipher3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLCIPHER_JUMPIFNULL);
106592       pTerm->wtFlags |= TERM_CODED;
106593     }
106594   }
106595   sqlcipher3ReleaseTempReg(pParse, iReleaseReg);
106596
106597   return notReady;
106598 }
106599
106600 #if defined(SQLCIPHER_TEST)
106601 /*
106602 ** The following variable holds a text description of query plan generated
106603 ** by the most recent call to sqlcipher3WhereBegin().  Each call to WhereBegin
106604 ** overwrites the previous.  This information is used for testing and
106605 ** analysis only.
106606 */
106607 SQLCIPHER_API char sqlcipher3_query_plan[BMS*2*40];  /* Text of the join */
106608 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
106609
106610 #endif /* SQLCIPHER_TEST */
106611
106612
106613 /*
106614 ** Free a WhereInfo structure
106615 */
106616 static void whereInfoFree(sqlcipher3 *db, WhereInfo *pWInfo){
106617   if( ALWAYS(pWInfo) ){
106618     int i;
106619     for(i=0; i<pWInfo->nLevel; i++){
106620       sqlcipher3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
106621       if( pInfo ){
106622         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
106623         if( pInfo->needToFreeIdxStr ){
106624           sqlcipher3_free(pInfo->idxStr);
106625         }
106626         sqlcipher3DbFree(db, pInfo);
106627       }
106628       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
106629         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
106630         if( pIdx ){
106631           sqlcipher3DbFree(db, pIdx->zColAff);
106632           sqlcipher3DbFree(db, pIdx);
106633         }
106634       }
106635     }
106636     whereClauseClear(pWInfo->pWC);
106637     sqlcipher3DbFree(db, pWInfo);
106638   }
106639 }
106640
106641
106642 /*
106643 ** Generate the beginning of the loop used for WHERE clause processing.
106644 ** The return value is a pointer to an opaque structure that contains
106645 ** information needed to terminate the loop.  Later, the calling routine
106646 ** should invoke sqlcipher3WhereEnd() with the return value of this function
106647 ** in order to complete the WHERE clause processing.
106648 **
106649 ** If an error occurs, this routine returns NULL.
106650 **
106651 ** The basic idea is to do a nested loop, one loop for each table in
106652 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
106653 ** same as a SELECT with only a single table in the FROM clause.)  For
106654 ** example, if the SQL is this:
106655 **
106656 **       SELECT * FROM t1, t2, t3 WHERE ...;
106657 **
106658 ** Then the code generated is conceptually like the following:
106659 **
106660 **      foreach row1 in t1 do       \    Code generated
106661 **        foreach row2 in t2 do      |-- by sqlcipher3WhereBegin()
106662 **          foreach row3 in t3 do   /
106663 **            ...
106664 **          end                     \    Code generated
106665 **        end                        |-- by sqlcipher3WhereEnd()
106666 **      end                         /
106667 **
106668 ** Note that the loops might not be nested in the order in which they
106669 ** appear in the FROM clause if a different order is better able to make
106670 ** use of indices.  Note also that when the IN operator appears in
106671 ** the WHERE clause, it might result in additional nested loops for
106672 ** scanning through all values on the right-hand side of the IN.
106673 **
106674 ** There are Btree cursors associated with each table.  t1 uses cursor
106675 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
106676 ** And so forth.  This routine generates code to open those VDBE cursors
106677 ** and sqlcipher3WhereEnd() generates the code to close them.
106678 **
106679 ** The code that sqlcipher3WhereBegin() generates leaves the cursors named
106680 ** in pTabList pointing at their appropriate entries.  The [...] code
106681 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
106682 ** data from the various tables of the loop.
106683 **
106684 ** If the WHERE clause is empty, the foreach loops must each scan their
106685 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
106686 ** the tables have indices and there are terms in the WHERE clause that
106687 ** refer to those indices, a complete table scan can be avoided and the
106688 ** code will run much faster.  Most of the work of this routine is checking
106689 ** to see if there are indices that can be used to speed up the loop.
106690 **
106691 ** Terms of the WHERE clause are also used to limit which rows actually
106692 ** make it to the "..." in the middle of the loop.  After each "foreach",
106693 ** terms of the WHERE clause that use only terms in that loop and outer
106694 ** loops are evaluated and if false a jump is made around all subsequent
106695 ** inner loops (or around the "..." if the test occurs within the inner-
106696 ** most loop)
106697 **
106698 ** OUTER JOINS
106699 **
106700 ** An outer join of tables t1 and t2 is conceptally coded as follows:
106701 **
106702 **    foreach row1 in t1 do
106703 **      flag = 0
106704 **      foreach row2 in t2 do
106705 **        start:
106706 **          ...
106707 **          flag = 1
106708 **      end
106709 **      if flag==0 then
106710 **        move the row2 cursor to a null row
106711 **        goto start
106712 **      fi
106713 **    end
106714 **
106715 ** ORDER BY CLAUSE PROCESSING
106716 **
106717 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
106718 ** if there is one.  If there is no ORDER BY clause or if this routine
106719 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
106720 **
106721 ** If an index can be used so that the natural output order of the table
106722 ** scan is correct for the ORDER BY clause, then that index is used and
106723 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
106724 ** unnecessary sort of the result set if an index appropriate for the
106725 ** ORDER BY clause already exists.
106726 **
106727 ** If the where clause loops cannot be arranged to provide the correct
106728 ** output order, then the *ppOrderBy is unchanged.
106729 */
106730 SQLCIPHER_PRIVATE WhereInfo *sqlcipher3WhereBegin(
106731   Parse *pParse,        /* The parser context */
106732   SrcList *pTabList,    /* A list of all tables to be scanned */
106733   Expr *pWhere,         /* The WHERE clause */
106734   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
106735   ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
106736   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqlcipherInt.h */
106737 ){
106738   int i;                     /* Loop counter */
106739   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
106740   int nTabList;              /* Number of elements in pTabList */
106741   WhereInfo *pWInfo;         /* Will become the return value of this function */
106742   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
106743   Bitmask notReady;          /* Cursors that are not yet positioned */
106744   WhereMaskSet *pMaskSet;    /* The expression mask set */
106745   WhereClause *pWC;               /* Decomposition of the WHERE clause */
106746   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
106747   WhereLevel *pLevel;             /* A single level in the pWInfo list */
106748   int iFrom;                      /* First unused FROM clause element */
106749   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
106750   sqlcipher3 *db;               /* Database connection */
106751
106752   /* The number of tables in the FROM clause is limited by the number of
106753   ** bits in a Bitmask 
106754   */
106755   testcase( pTabList->nSrc==BMS );
106756   if( pTabList->nSrc>BMS ){
106757     sqlcipher3ErrorMsg(pParse, "at most %d tables in a join", BMS);
106758     return 0;
106759   }
106760
106761   /* This function normally generates a nested loop for all tables in 
106762   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
106763   ** only generate code for the first table in pTabList and assume that
106764   ** any cursors associated with subsequent tables are uninitialized.
106765   */
106766   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
106767
106768   /* Allocate and initialize the WhereInfo structure that will become the
106769   ** return value. A single allocation is used to store the WhereInfo
106770   ** struct, the contents of WhereInfo.a[], the WhereClause structure
106771   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
106772   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
106773   ** some architectures. Hence the ROUND8() below.
106774   */
106775   db = pParse->db;
106776   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
106777   pWInfo = sqlcipher3DbMallocZero(db, 
106778       nByteWInfo + 
106779       sizeof(WhereClause) +
106780       sizeof(WhereMaskSet)
106781   );
106782   if( db->mallocFailed ){
106783     sqlcipher3DbFree(db, pWInfo);
106784     pWInfo = 0;
106785     goto whereBeginError;
106786   }
106787   pWInfo->nLevel = nTabList;
106788   pWInfo->pParse = pParse;
106789   pWInfo->pTabList = pTabList;
106790   pWInfo->iBreak = sqlcipher3VdbeMakeLabel(v);
106791   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
106792   pWInfo->wctrlFlags = wctrlFlags;
106793   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
106794   pMaskSet = (WhereMaskSet*)&pWC[1];
106795
106796   /* Disable the DISTINCT optimization if SQLCIPHER_DistinctOpt is set via
106797   ** sqlcipher3_test_ctrl(SQLCIPHER_TESTCTRL_OPTIMIZATIONS,...) */
106798   if( db->flags & SQLCIPHER_DistinctOpt ) pDistinct = 0;
106799
106800   /* Split the WHERE clause into separate subexpressions where each
106801   ** subexpression is separated by an AND operator.
106802   */
106803   initMaskSet(pMaskSet);
106804   whereClauseInit(pWC, pParse, pMaskSet, wctrlFlags);
106805   sqlcipher3ExprCodeConstants(pParse, pWhere);
106806   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
106807     
106808   /* Special case: a WHERE clause that is constant.  Evaluate the
106809   ** expression and either jump over all of the code or fall thru.
106810   */
106811   if( pWhere && (nTabList==0 || sqlcipher3ExprIsConstantNotJoin(pWhere)) ){
106812     sqlcipher3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLCIPHER_JUMPIFNULL);
106813     pWhere = 0;
106814   }
106815
106816   /* Assign a bit from the bitmask to every term in the FROM clause.
106817   **
106818   ** When assigning bitmask values to FROM clause cursors, it must be
106819   ** the case that if X is the bitmask for the N-th FROM clause term then
106820   ** the bitmask for all FROM clause terms to the left of the N-th term
106821   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
106822   ** its Expr.iRightJoinTable value to find the bitmask of the right table
106823   ** of the join.  Subtracting one from the right table bitmask gives a
106824   ** bitmask for all tables to the left of the join.  Knowing the bitmask
106825   ** for all tables to the left of a left join is important.  Ticket #3015.
106826   **
106827   ** Configure the WhereClause.vmask variable so that bits that correspond
106828   ** to virtual table cursors are set. This is used to selectively disable 
106829   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
106830   ** with virtual tables.
106831   **
106832   ** Note that bitmasks are created for all pTabList->nSrc tables in
106833   ** pTabList, not just the first nTabList tables.  nTabList is normally
106834   ** equal to pTabList->nSrc but might be shortened to 1 if the
106835   ** WHERE_ONETABLE_ONLY flag is set.
106836   */
106837   assert( pWC->vmask==0 && pMaskSet->n==0 );
106838   for(i=0; i<pTabList->nSrc; i++){
106839     createMask(pMaskSet, pTabList->a[i].iCursor);
106840 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
106841     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
106842       pWC->vmask |= ((Bitmask)1 << i);
106843     }
106844 #endif
106845   }
106846 #ifndef NDEBUG
106847   {
106848     Bitmask toTheLeft = 0;
106849     for(i=0; i<pTabList->nSrc; i++){
106850       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
106851       assert( (m-1)==toTheLeft );
106852       toTheLeft |= m;
106853     }
106854   }
106855 #endif
106856
106857   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
106858   ** add new virtual terms onto the end of the WHERE clause.  We do not
106859   ** want to analyze these virtual terms, so start analyzing at the end
106860   ** and work forward so that the added virtual terms are never processed.
106861   */
106862   exprAnalyzeAll(pTabList, pWC);
106863   if( db->mallocFailed ){
106864     goto whereBeginError;
106865   }
106866
106867   /* Check if the DISTINCT qualifier, if there is one, is redundant. 
106868   ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
106869   ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
106870   */
106871   if( pDistinct && isDistinctRedundant(pParse, pTabList, pWC, pDistinct) ){
106872     pDistinct = 0;
106873     pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
106874   }
106875
106876   /* Chose the best index to use for each table in the FROM clause.
106877   **
106878   ** This loop fills in the following fields:
106879   **
106880   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
106881   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
106882   **   pWInfo->a[].nEq       The number of == and IN constraints
106883   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
106884   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
106885   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
106886   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
106887   **
106888   ** This loop also figures out the nesting order of tables in the FROM
106889   ** clause.
106890   */
106891   notReady = ~(Bitmask)0;
106892   andFlags = ~0;
106893   WHERETRACE(("*** Optimizer Start ***\n"));
106894   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
106895     WhereCost bestPlan;         /* Most efficient plan seen so far */
106896     Index *pIdx;                /* Index for FROM table at pTabItem */
106897     int j;                      /* For looping over FROM tables */
106898     int bestJ = -1;             /* The value of j */
106899     Bitmask m;                  /* Bitmask value for j or bestJ */
106900     int isOptimal;              /* Iterator for optimal/non-optimal search */
106901     int nUnconstrained;         /* Number tables without INDEXED BY */
106902     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
106903
106904     memset(&bestPlan, 0, sizeof(bestPlan));
106905     bestPlan.rCost = SQLCIPHER_BIG_DBL;
106906     WHERETRACE(("*** Begin search for loop %d ***\n", i));
106907
106908     /* Loop through the remaining entries in the FROM clause to find the
106909     ** next nested loop. The loop tests all FROM clause entries
106910     ** either once or twice. 
106911     **
106912     ** The first test is always performed if there are two or more entries
106913     ** remaining and never performed if there is only one FROM clause entry
106914     ** to choose from.  The first test looks for an "optimal" scan.  In
106915     ** this context an optimal scan is one that uses the same strategy
106916     ** for the given FROM clause entry as would be selected if the entry
106917     ** were used as the innermost nested loop.  In other words, a table
106918     ** is chosen such that the cost of running that table cannot be reduced
106919     ** by waiting for other tables to run first.  This "optimal" test works
106920     ** by first assuming that the FROM clause is on the inner loop and finding
106921     ** its query plan, then checking to see if that query plan uses any
106922     ** other FROM clause terms that are notReady.  If no notReady terms are
106923     ** used then the "optimal" query plan works.
106924     **
106925     ** Note that the WhereCost.nRow parameter for an optimal scan might
106926     ** not be as small as it would be if the table really were the innermost
106927     ** join.  The nRow value can be reduced by WHERE clause constraints
106928     ** that do not use indices.  But this nRow reduction only happens if the
106929     ** table really is the innermost join.  
106930     **
106931     ** The second loop iteration is only performed if no optimal scan
106932     ** strategies were found by the first iteration. This second iteration
106933     ** is used to search for the lowest cost scan overall.
106934     **
106935     ** Previous versions of SQLite performed only the second iteration -
106936     ** the next outermost loop was always that with the lowest overall
106937     ** cost. However, this meant that SQLite could select the wrong plan
106938     ** for scripts such as the following:
106939     **   
106940     **   CREATE TABLE t1(a, b); 
106941     **   CREATE TABLE t2(c, d);
106942     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
106943     **
106944     ** The best strategy is to iterate through table t1 first. However it
106945     ** is not possible to determine this with a simple greedy algorithm.
106946     ** Since the cost of a linear scan through table t2 is the same 
106947     ** as the cost of a linear scan through table t1, a simple greedy 
106948     ** algorithm may choose to use t2 for the outer loop, which is a much
106949     ** costlier approach.
106950     */
106951     nUnconstrained = 0;
106952     notIndexed = 0;
106953     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
106954       Bitmask mask;             /* Mask of tables not yet ready */
106955       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
106956         int doNotReorder;    /* True if this table should not be reordered */
106957         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
106958         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
106959         ExprList *pDist;     /* DISTINCT clause for index to optimize */
106960   
106961         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
106962         if( j!=iFrom && doNotReorder ) break;
106963         m = getMask(pMaskSet, pTabItem->iCursor);
106964         if( (m & notReady)==0 ){
106965           if( j==iFrom ) iFrom++;
106966           continue;
106967         }
106968         mask = (isOptimal ? m : notReady);
106969         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
106970         pDist = (i==0 ? pDistinct : 0);
106971         if( pTabItem->pIndex==0 ) nUnconstrained++;
106972   
106973         WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
106974                     j, isOptimal));
106975         assert( pTabItem->pTab );
106976 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
106977         if( IsVirtual(pTabItem->pTab) ){
106978           sqlcipher3_index_info **pp = &pWInfo->a[j].pIdxInfo;
106979           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
106980                            &sCost, pp);
106981         }else 
106982 #endif
106983         {
106984           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
106985               pDist, &sCost);
106986         }
106987         assert( isOptimal || (sCost.used&notReady)==0 );
106988
106989         /* If an INDEXED BY clause is present, then the plan must use that
106990         ** index if it uses any index at all */
106991         assert( pTabItem->pIndex==0 
106992                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
106993                   || sCost.plan.u.pIdx==pTabItem->pIndex );
106994
106995         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
106996           notIndexed |= m;
106997         }
106998
106999         /* Conditions under which this table becomes the best so far:
107000         **
107001         **   (1) The table must not depend on other tables that have not
107002         **       yet run.
107003         **
107004         **   (2) A full-table-scan plan cannot supercede indexed plan unless
107005         **       the full-table-scan is an "optimal" plan as defined above.
107006         **
107007         **   (3) All tables have an INDEXED BY clause or this table lacks an
107008         **       INDEXED BY clause or this table uses the specific
107009         **       index specified by its INDEXED BY clause.  This rule ensures
107010         **       that a best-so-far is always selected even if an impossible
107011         **       combination of INDEXED BY clauses are given.  The error
107012         **       will be detected and relayed back to the application later.
107013         **       The NEVER() comes about because rule (2) above prevents
107014         **       An indexable full-table-scan from reaching rule (3).
107015         **
107016         **   (4) The plan cost must be lower than prior plans or else the
107017         **       cost must be the same and the number of rows must be lower.
107018         */
107019         if( (sCost.used&notReady)==0                       /* (1) */
107020             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
107021                 || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
107022                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
107023             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
107024                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
107025             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
107026                 || (sCost.rCost<=bestPlan.rCost 
107027                  && sCost.plan.nRow<bestPlan.plan.nRow))
107028         ){
107029           WHERETRACE(("=== table %d is best so far"
107030                       " with cost=%g and nRow=%g\n",
107031                       j, sCost.rCost, sCost.plan.nRow));
107032           bestPlan = sCost;
107033           bestJ = j;
107034         }
107035         if( doNotReorder ) break;
107036       }
107037     }
107038     assert( bestJ>=0 );
107039     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
107040     WHERETRACE(("*** Optimizer selects table %d for loop %d"
107041                 " with cost=%g and nRow=%g\n",
107042                 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
107043     /* The ALWAYS() that follows was added to hush up clang scan-build */
107044     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 && ALWAYS(ppOrderBy) ){
107045       *ppOrderBy = 0;
107046     }
107047     if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
107048       assert( pWInfo->eDistinct==0 );
107049       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
107050     }
107051     andFlags &= bestPlan.plan.wsFlags;
107052     pLevel->plan = bestPlan.plan;
107053     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
107054     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
107055     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
107056       pLevel->iIdxCur = pParse->nTab++;
107057     }else{
107058       pLevel->iIdxCur = -1;
107059     }
107060     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
107061     pLevel->iFrom = (u8)bestJ;
107062     if( bestPlan.plan.nRow>=(double)1 ){
107063       pParse->nQueryLoop *= bestPlan.plan.nRow;
107064     }
107065
107066     /* Check that if the table scanned by this loop iteration had an
107067     ** INDEXED BY clause attached to it, that the named index is being
107068     ** used for the scan. If not, then query compilation has failed.
107069     ** Return an error.
107070     */
107071     pIdx = pTabList->a[bestJ].pIndex;
107072     if( pIdx ){
107073       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
107074         sqlcipher3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
107075         goto whereBeginError;
107076       }else{
107077         /* If an INDEXED BY clause is used, the bestIndex() function is
107078         ** guaranteed to find the index specified in the INDEXED BY clause
107079         ** if it find an index at all. */
107080         assert( bestPlan.plan.u.pIdx==pIdx );
107081       }
107082     }
107083   }
107084   WHERETRACE(("*** Optimizer Finished ***\n"));
107085   if( pParse->nErr || db->mallocFailed ){
107086     goto whereBeginError;
107087   }
107088
107089   /* If the total query only selects a single row, then the ORDER BY
107090   ** clause is irrelevant.
107091   */
107092   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
107093     *ppOrderBy = 0;
107094   }
107095
107096   /* If the caller is an UPDATE or DELETE statement that is requesting
107097   ** to use a one-pass algorithm, determine if this is appropriate.
107098   ** The one-pass algorithm only works if the WHERE clause constraints
107099   ** the statement to update a single row.
107100   */
107101   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
107102   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
107103     pWInfo->okOnePass = 1;
107104     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
107105   }
107106
107107   /* Open all tables in the pTabList and any indices selected for
107108   ** searching those tables.
107109   */
107110   sqlcipher3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
107111   notReady = ~(Bitmask)0;
107112   pWInfo->nRowOut = (double)1;
107113   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
107114     Table *pTab;     /* Table to open */
107115     int iDb;         /* Index of database containing table/index */
107116
107117     pTabItem = &pTabList->a[pLevel->iFrom];
107118     pTab = pTabItem->pTab;
107119     pLevel->iTabCur = pTabItem->iCursor;
107120     pWInfo->nRowOut *= pLevel->plan.nRow;
107121     iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
107122     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
107123       /* Do nothing */
107124     }else
107125 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
107126     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
107127       const char *pVTab = (const char *)sqlcipher3GetVTable(db, pTab);
107128       int iCur = pTabItem->iCursor;
107129       sqlcipher3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
107130     }else
107131 #endif
107132     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107133          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
107134       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
107135       sqlcipher3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
107136       testcase( pTab->nCol==BMS-1 );
107137       testcase( pTab->nCol==BMS );
107138       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
107139         Bitmask b = pTabItem->colUsed;
107140         int n = 0;
107141         for(; b; b=b>>1, n++){}
107142         sqlcipher3VdbeChangeP4(v, sqlcipher3VdbeCurrentAddr(v)-1, 
107143                             SQLCIPHER_INT_TO_PTR(n), P4_INT32);
107144         assert( n<=pTab->nCol );
107145       }
107146     }else{
107147       sqlcipher3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
107148     }
107149 #ifndef SQLCIPHER_OMIT_AUTOMATIC_INDEX
107150     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
107151       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
107152     }else
107153 #endif
107154     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
107155       Index *pIx = pLevel->plan.u.pIdx;
107156       KeyInfo *pKey = sqlcipher3IndexKeyinfo(pParse, pIx);
107157       int iIdxCur = pLevel->iIdxCur;
107158       assert( pIx->pSchema==pTab->pSchema );
107159       assert( iIdxCur>=0 );
107160       sqlcipher3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
107161                         (char*)pKey, P4_KEYINFO_HANDOFF);
107162       VdbeComment((v, "%s", pIx->zName));
107163     }
107164     sqlcipher3CodeVerifySchema(pParse, iDb);
107165     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
107166   }
107167   pWInfo->iTop = sqlcipher3VdbeCurrentAddr(v);
107168   if( db->mallocFailed ) goto whereBeginError;
107169
107170   /* Generate the code to do the search.  Each iteration of the for
107171   ** loop below generates code for a single nested loop of the VM
107172   ** program.
107173   */
107174   notReady = ~(Bitmask)0;
107175   for(i=0; i<nTabList; i++){
107176     pLevel = &pWInfo->a[i];
107177     explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
107178     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady, pWhere);
107179     pWInfo->iContinue = pLevel->addrCont;
107180   }
107181
107182 #ifdef SQLCIPHER_TEST  /* For testing and debugging use only */
107183   /* Record in the query plan information about the current table
107184   ** and the index used to access it (if any).  If the table itself
107185   ** is not used, its name is just '{}'.  If no index is used
107186   ** the index is listed as "{}".  If the primary key is used the
107187   ** index name is '*'.
107188   */
107189   for(i=0; i<nTabList; i++){
107190     char *z;
107191     int n;
107192     pLevel = &pWInfo->a[i];
107193     pTabItem = &pTabList->a[pLevel->iFrom];
107194     z = pTabItem->zAlias;
107195     if( z==0 ) z = pTabItem->pTab->zName;
107196     n = sqlcipher3Strlen30(z);
107197     if( n+nQPlan < sizeof(sqlcipher3_query_plan)-10 ){
107198       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
107199         memcpy(&sqlcipher3_query_plan[nQPlan], "{}", 2);
107200         nQPlan += 2;
107201       }else{
107202         memcpy(&sqlcipher3_query_plan[nQPlan], z, n);
107203         nQPlan += n;
107204       }
107205       sqlcipher3_query_plan[nQPlan++] = ' ';
107206     }
107207     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
107208     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
107209     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
107210       memcpy(&sqlcipher3_query_plan[nQPlan], "* ", 2);
107211       nQPlan += 2;
107212     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
107213       n = sqlcipher3Strlen30(pLevel->plan.u.pIdx->zName);
107214       if( n+nQPlan < sizeof(sqlcipher3_query_plan)-2 ){
107215         memcpy(&sqlcipher3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
107216         nQPlan += n;
107217         sqlcipher3_query_plan[nQPlan++] = ' ';
107218       }
107219     }else{
107220       memcpy(&sqlcipher3_query_plan[nQPlan], "{} ", 3);
107221       nQPlan += 3;
107222     }
107223   }
107224   while( nQPlan>0 && sqlcipher3_query_plan[nQPlan-1]==' ' ){
107225     sqlcipher3_query_plan[--nQPlan] = 0;
107226   }
107227   sqlcipher3_query_plan[nQPlan] = 0;
107228   nQPlan = 0;
107229 #endif /* SQLCIPHER_TEST // Testing and debugging use only */
107230
107231   /* Record the continuation address in the WhereInfo structure.  Then
107232   ** clean up and return.
107233   */
107234   return pWInfo;
107235
107236   /* Jump here if malloc fails */
107237 whereBeginError:
107238   if( pWInfo ){
107239     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
107240     whereInfoFree(db, pWInfo);
107241   }
107242   return 0;
107243 }
107244
107245 /*
107246 ** Generate the end of the WHERE loop.  See comments on 
107247 ** sqlcipher3WhereBegin() for additional information.
107248 */
107249 SQLCIPHER_PRIVATE void sqlcipher3WhereEnd(WhereInfo *pWInfo){
107250   Parse *pParse = pWInfo->pParse;
107251   Vdbe *v = pParse->pVdbe;
107252   int i;
107253   WhereLevel *pLevel;
107254   SrcList *pTabList = pWInfo->pTabList;
107255   sqlcipher3 *db = pParse->db;
107256
107257   /* Generate loop termination code.
107258   */
107259   sqlcipher3ExprCacheClear(pParse);
107260   for(i=pWInfo->nLevel-1; i>=0; i--){
107261     pLevel = &pWInfo->a[i];
107262     sqlcipher3VdbeResolveLabel(v, pLevel->addrCont);
107263     if( pLevel->op!=OP_Noop ){
107264       sqlcipher3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
107265       sqlcipher3VdbeChangeP5(v, pLevel->p5);
107266     }
107267     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
107268       struct InLoop *pIn;
107269       int j;
107270       sqlcipher3VdbeResolveLabel(v, pLevel->addrNxt);
107271       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
107272         sqlcipher3VdbeJumpHere(v, pIn->addrInTop+1);
107273         sqlcipher3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
107274         sqlcipher3VdbeJumpHere(v, pIn->addrInTop-1);
107275       }
107276       sqlcipher3DbFree(db, pLevel->u.in.aInLoop);
107277     }
107278     sqlcipher3VdbeResolveLabel(v, pLevel->addrBrk);
107279     if( pLevel->iLeftJoin ){
107280       int addr;
107281       addr = sqlcipher3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
107282       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107283            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
107284       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
107285         sqlcipher3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
107286       }
107287       if( pLevel->iIdxCur>=0 ){
107288         sqlcipher3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
107289       }
107290       if( pLevel->op==OP_Return ){
107291         sqlcipher3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
107292       }else{
107293         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
107294       }
107295       sqlcipher3VdbeJumpHere(v, addr);
107296     }
107297   }
107298
107299   /* The "break" point is here, just past the end of the outer loop.
107300   ** Set it.
107301   */
107302   sqlcipher3VdbeResolveLabel(v, pWInfo->iBreak);
107303
107304   /* Close all of the cursors that were opened by sqlcipher3WhereBegin.
107305   */
107306   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
107307   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
107308     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
107309     Table *pTab = pTabItem->pTab;
107310     assert( pTab!=0 );
107311     if( (pTab->tabFlags & TF_Ephemeral)==0
107312      && pTab->pSelect==0
107313      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
107314     ){
107315       int ws = pLevel->plan.wsFlags;
107316       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
107317         sqlcipher3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
107318       }
107319       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
107320         sqlcipher3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
107321       }
107322     }
107323
107324     /* If this scan uses an index, make code substitutions to read data
107325     ** from the index in preference to the table. Sometimes, this means
107326     ** the table need never be read from. This is a performance boost,
107327     ** as the vdbe level waits until the table is read before actually
107328     ** seeking the table cursor to the record corresponding to the current
107329     ** position in the index.
107330     ** 
107331     ** Calls to the code generator in between sqlcipher3WhereBegin and
107332     ** sqlcipher3WhereEnd will have created code that references the table
107333     ** directly.  This loop scans all that code looking for opcodes
107334     ** that reference the table and converts them into opcodes that
107335     ** reference the index.
107336     */
107337     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
107338       int k, j, last;
107339       VdbeOp *pOp;
107340       Index *pIdx = pLevel->plan.u.pIdx;
107341
107342       assert( pIdx!=0 );
107343       pOp = sqlcipher3VdbeGetOp(v, pWInfo->iTop);
107344       last = sqlcipher3VdbeCurrentAddr(v);
107345       for(k=pWInfo->iTop; k<last; k++, pOp++){
107346         if( pOp->p1!=pLevel->iTabCur ) continue;
107347         if( pOp->opcode==OP_Column ){
107348           for(j=0; j<pIdx->nColumn; j++){
107349             if( pOp->p2==pIdx->aiColumn[j] ){
107350               pOp->p2 = j;
107351               pOp->p1 = pLevel->iIdxCur;
107352               break;
107353             }
107354           }
107355           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107356                || j<pIdx->nColumn );
107357         }else if( pOp->opcode==OP_Rowid ){
107358           pOp->p1 = pLevel->iIdxCur;
107359           pOp->opcode = OP_IdxRowid;
107360         }
107361       }
107362     }
107363   }
107364
107365   /* Final cleanup
107366   */
107367   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
107368   whereInfoFree(db, pWInfo);
107369   return;
107370 }
107371
107372 /************** End of where.c ***********************************************/
107373 /************** Begin file parse.c *******************************************/
107374 /* Driver template for the LEMON parser generator.
107375 ** The author disclaims copyright to this source code.
107376 **
107377 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
107378 ** The only modifications are the addition of a couple of NEVER()
107379 ** macros to disable tests that are needed in the case of a general
107380 ** LALR(1) grammar but which are always false in the
107381 ** specific grammar used by SQLite.
107382 */
107383 /* First off, code is included that follows the "include" declaration
107384 ** in the input grammar file. */
107385 /* #include <stdio.h> */
107386
107387
107388 /*
107389 ** Disable all error recovery processing in the parser push-down
107390 ** automaton.
107391 */
107392 #define YYNOERRORRECOVERY 1
107393
107394 /*
107395 ** Make yytestcase() the same as testcase()
107396 */
107397 #define yytestcase(X) testcase(X)
107398
107399 /*
107400 ** An instance of this structure holds information about the
107401 ** LIMIT clause of a SELECT statement.
107402 */
107403 struct LimitVal {
107404   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
107405   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
107406 };
107407
107408 /*
107409 ** An instance of this structure is used to store the LIKE,
107410 ** GLOB, NOT LIKE, and NOT GLOB operators.
107411 */
107412 struct LikeOp {
107413   Token eOperator;  /* "like" or "glob" or "regexp" */
107414   int not;         /* True if the NOT keyword is present */
107415 };
107416
107417 /*
107418 ** An instance of the following structure describes the event of a
107419 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
107420 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
107421 **
107422 **      UPDATE ON (a,b,c)
107423 **
107424 ** Then the "b" IdList records the list "a,b,c".
107425 */
107426 struct TrigEvent { int a; IdList * b; };
107427
107428 /*
107429 ** An instance of this structure holds the ATTACH key and the key type.
107430 */
107431 struct AttachKey { int type;  Token key; };
107432
107433
107434   /* This is a utility routine used to set the ExprSpan.zStart and
107435   ** ExprSpan.zEnd values of pOut so that the span covers the complete
107436   ** range of text beginning with pStart and going to the end of pEnd.
107437   */
107438   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
107439     pOut->zStart = pStart->z;
107440     pOut->zEnd = &pEnd->z[pEnd->n];
107441   }
107442
107443   /* Construct a new Expr object from a single identifier.  Use the
107444   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
107445   ** that created the expression.
107446   */
107447   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
107448     pOut->pExpr = sqlcipher3PExpr(pParse, op, 0, 0, pValue);
107449     pOut->zStart = pValue->z;
107450     pOut->zEnd = &pValue->z[pValue->n];
107451   }
107452
107453   /* This routine constructs a binary expression node out of two ExprSpan
107454   ** objects and uses the result to populate a new ExprSpan object.
107455   */
107456   static void spanBinaryExpr(
107457     ExprSpan *pOut,     /* Write the result here */
107458     Parse *pParse,      /* The parsing context.  Errors accumulate here */
107459     int op,             /* The binary operation */
107460     ExprSpan *pLeft,    /* The left operand */
107461     ExprSpan *pRight    /* The right operand */
107462   ){
107463     pOut->pExpr = sqlcipher3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
107464     pOut->zStart = pLeft->zStart;
107465     pOut->zEnd = pRight->zEnd;
107466   }
107467
107468   /* Construct an expression node for a unary postfix operator
107469   */
107470   static void spanUnaryPostfix(
107471     ExprSpan *pOut,        /* Write the new expression node here */
107472     Parse *pParse,         /* Parsing context to record errors */
107473     int op,                /* The operator */
107474     ExprSpan *pOperand,    /* The operand */
107475     Token *pPostOp         /* The operand token for setting the span */
107476   ){
107477     pOut->pExpr = sqlcipher3PExpr(pParse, op, pOperand->pExpr, 0, 0);
107478     pOut->zStart = pOperand->zStart;
107479     pOut->zEnd = &pPostOp->z[pPostOp->n];
107480   }                           
107481
107482   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
107483   ** unary TK_ISNULL or TK_NOTNULL expression. */
107484   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
107485     sqlcipher3 *db = pParse->db;
107486     if( db->mallocFailed==0 && pY->op==TK_NULL ){
107487       pA->op = (u8)op;
107488       sqlcipher3ExprDelete(db, pA->pRight);
107489       pA->pRight = 0;
107490     }
107491   }
107492
107493   /* Construct an expression node for a unary prefix operator
107494   */
107495   static void spanUnaryPrefix(
107496     ExprSpan *pOut,        /* Write the new expression node here */
107497     Parse *pParse,         /* Parsing context to record errors */
107498     int op,                /* The operator */
107499     ExprSpan *pOperand,    /* The operand */
107500     Token *pPreOp         /* The operand token for setting the span */
107501   ){
107502     pOut->pExpr = sqlcipher3PExpr(pParse, op, pOperand->pExpr, 0, 0);
107503     pOut->zStart = pPreOp->z;
107504     pOut->zEnd = pOperand->zEnd;
107505   }
107506 /* Next is all token values, in a form suitable for use by makeheaders.
107507 ** This section will be null unless lemon is run with the -m switch.
107508 */
107509 /* 
107510 ** These constants (all generated automatically by the parser generator)
107511 ** specify the various kinds of tokens (terminals) that the parser
107512 ** understands. 
107513 **
107514 ** Each symbol here is a terminal symbol in the grammar.
107515 */
107516 /* Make sure the INTERFACE macro is defined.
107517 */
107518 #ifndef INTERFACE
107519 # define INTERFACE 1
107520 #endif
107521 /* The next thing included is series of defines which control
107522 ** various aspects of the generated parser.
107523 **    YYCODETYPE         is the data type used for storing terminal
107524 **                       and nonterminal numbers.  "unsigned char" is
107525 **                       used if there are fewer than 250 terminals
107526 **                       and nonterminals.  "int" is used otherwise.
107527 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
107528 **                       to no legal terminal or nonterminal number.  This
107529 **                       number is used to fill in empty slots of the hash 
107530 **                       table.
107531 **    YYFALLBACK         If defined, this indicates that one or more tokens
107532 **                       have fall-back values which should be used if the
107533 **                       original value of the token will not parse.
107534 **    YYACTIONTYPE       is the data type used for storing terminal
107535 **                       and nonterminal numbers.  "unsigned char" is
107536 **                       used if there are fewer than 250 rules and
107537 **                       states combined.  "int" is used otherwise.
107538 **    sqlcipher3ParserTOKENTYPE     is the data type used for minor tokens given 
107539 **                       directly to the parser from the tokenizer.
107540 **    YYMINORTYPE        is the data type used for all minor tokens.
107541 **                       This is typically a union of many types, one of
107542 **                       which is sqlcipher3ParserTOKENTYPE.  The entry in the union
107543 **                       for base tokens is called "yy0".
107544 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
107545 **                       zero the stack is dynamically sized using realloc()
107546 **    sqlcipher3ParserARG_SDECL     A static variable declaration for the %extra_argument
107547 **    sqlcipher3ParserARG_PDECL     A parameter declaration for the %extra_argument
107548 **    sqlcipher3ParserARG_STORE     Code to store %extra_argument into yypParser
107549 **    sqlcipher3ParserARG_FETCH     Code to extract %extra_argument from yypParser
107550 **    YYNSTATE           the combined number of states.
107551 **    YYNRULE            the number of rules in the grammar
107552 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
107553 **                       defined, then do no error processing.
107554 */
107555 #define YYCODETYPE unsigned char
107556 #define YYNOCODE 253
107557 #define YYACTIONTYPE unsigned short int
107558 #define YYWILDCARD 67
107559 #define sqlcipher3ParserTOKENTYPE Token
107560 typedef union {
107561   int yyinit;
107562   sqlcipher3ParserTOKENTYPE yy0;
107563   int yy4;
107564   struct TrigEvent yy90;
107565   ExprSpan yy118;
107566   TriggerStep* yy203;
107567   u8 yy210;
107568   struct {int value; int mask;} yy215;
107569   SrcList* yy259;
107570   struct LimitVal yy292;
107571   Expr* yy314;
107572   ExprList* yy322;
107573   struct LikeOp yy342;
107574   IdList* yy384;
107575   Select* yy387;
107576 } YYMINORTYPE;
107577 #ifndef YYSTACKDEPTH
107578 #define YYSTACKDEPTH 100
107579 #endif
107580 #define sqlcipher3ParserARG_SDECL Parse *pParse;
107581 #define sqlcipher3ParserARG_PDECL ,Parse *pParse
107582 #define sqlcipher3ParserARG_FETCH Parse *pParse = yypParser->pParse
107583 #define sqlcipher3ParserARG_STORE yypParser->pParse = pParse
107584 #define YYNSTATE 630
107585 #define YYNRULE 329
107586 #define YYFALLBACK 1
107587 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
107588 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
107589 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
107590
107591 /* The yyzerominor constant is used to initialize instances of
107592 ** YYMINORTYPE objects to zero. */
107593 static const YYMINORTYPE yyzerominor = { 0 };
107594
107595 /* Define the yytestcase() macro to be a no-op if is not already defined
107596 ** otherwise.
107597 **
107598 ** Applications can choose to define yytestcase() in the %include section
107599 ** to a macro that can assist in verifying code coverage.  For production
107600 ** code the yytestcase() macro should be turned off.  But it is useful
107601 ** for testing.
107602 */
107603 #ifndef yytestcase
107604 # define yytestcase(X)
107605 #endif
107606
107607
107608 /* Next are the tables used to determine what action to take based on the
107609 ** current state and lookahead token.  These tables are used to implement
107610 ** functions that take a state number and lookahead value and return an
107611 ** action integer.  
107612 **
107613 ** Suppose the action integer is N.  Then the action is determined as
107614 ** follows
107615 **
107616 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
107617 **                                      token onto the stack and goto state N.
107618 **
107619 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
107620 **
107621 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
107622 **
107623 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
107624 **
107625 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
107626 **                                      slots in the yy_action[] table.
107627 **
107628 ** The action table is constructed as a single large table named yy_action[].
107629 ** Given state S and lookahead X, the action is computed as
107630 **
107631 **      yy_action[ yy_shift_ofst[S] + X ]
107632 **
107633 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
107634 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
107635 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
107636 ** and that yy_default[S] should be used instead.  
107637 **
107638 ** The formula above is for computing the action when the lookahead is
107639 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
107640 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
107641 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
107642 ** YY_SHIFT_USE_DFLT.
107643 **
107644 ** The following are the tables generated in this section:
107645 **
107646 **  yy_action[]        A single table containing all actions.
107647 **  yy_lookahead[]     A table containing the lookahead for each entry in
107648 **                     yy_action.  Used to detect hash collisions.
107649 **  yy_shift_ofst[]    For each state, the offset into yy_action for
107650 **                     shifting terminals.
107651 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
107652 **                     shifting non-terminals after a reduce.
107653 **  yy_default[]       Default action for each state.
107654 */
107655 #define YY_ACTTAB_COUNT (1557)
107656 static const YYACTIONTYPE yy_action[] = {
107657  /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
107658  /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
107659  /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
107660  /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
107661  /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
107662  /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
107663  /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
107664  /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
107665  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
107666  /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
107667  /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
107668  /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
107669  /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
107670  /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
107671  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
107672  /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
107673  /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
107674  /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
107675  /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
107676  /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
107677  /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
107678  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
107679  /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
107680  /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
107681  /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
107682  /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
107683  /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
107684  /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
107685  /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
107686  /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
107687  /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
107688  /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
107689  /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
107690  /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
107691  /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
107692  /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
107693  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
107694  /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
107695  /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
107696  /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
107697  /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
107698  /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
107699  /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
107700  /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
107701  /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
107702  /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
107703  /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
107704  /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
107705  /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
107706  /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
107707  /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
107708  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
107709  /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
107710  /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
107711  /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
107712  /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
107713  /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
107714  /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
107715  /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
107716  /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
107717  /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
107718  /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
107719  /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
107720  /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
107721  /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
107722  /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
107723  /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
107724  /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
107725  /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
107726  /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
107727  /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
107728  /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
107729  /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
107730  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
107731  /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
107732  /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
107733  /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
107734  /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
107735  /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
107736  /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
107737  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
107738  /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
107739  /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
107740  /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
107741  /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
107742  /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
107743  /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
107744  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
107745  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
107746  /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
107747  /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
107748  /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
107749  /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
107750  /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
107751  /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
107752  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
107753  /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
107754  /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
107755  /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
107756  /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
107757  /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
107758  /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
107759  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
107760  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
107761  /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
107762  /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
107763  /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
107764  /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
107765  /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
107766  /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
107767  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
107768  /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
107769  /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
107770  /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
107771  /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
107772  /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
107773  /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
107774  /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
107775  /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
107776  /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
107777  /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
107778  /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
107779  /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
107780  /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
107781  /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
107782  /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
107783  /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
107784  /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
107785  /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
107786  /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
107787  /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
107788  /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
107789  /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
107790  /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
107791  /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
107792  /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
107793  /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
107794  /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
107795  /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
107796  /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
107797  /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
107798  /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
107799  /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
107800  /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
107801  /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
107802  /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
107803  /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
107804  /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
107805  /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
107806  /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
107807  /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
107808  /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
107809  /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
107810  /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
107811  /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
107812  /*  1550 */   961,  961,  961,  961,  961,  961,  370,
107813 };
107814 static const YYCODETYPE yy_lookahead[] = {
107815  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
107816  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
107817  /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
107818  /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
107819  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
107820  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
107821  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
107822  /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
107823  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
107824  /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
107825  /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
107826  /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
107827  /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
107828  /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
107829  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
107830  /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
107831  /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
107832  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
107833  /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
107834  /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
107835  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
107836  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
107837  /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
107838  /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
107839  /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
107840  /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
107841  /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
107842  /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
107843  /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
107844  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
107845  /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
107846  /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
107847  /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
107848  /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
107849  /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
107850  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
107851  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
107852  /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
107853  /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
107854  /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
107855  /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
107856  /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
107857  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
107858  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
107859  /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
107860  /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
107861  /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
107862  /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
107863  /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
107864  /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
107865  /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
107866  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
107867  /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
107868  /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
107869  /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
107870  /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
107871  /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
107872  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
107873  /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
107874  /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
107875  /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
107876  /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
107877  /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
107878  /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
107879  /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
107880  /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
107881  /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
107882  /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
107883  /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
107884  /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
107885  /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
107886  /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
107887  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
107888  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
107889  /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
107890  /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
107891  /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
107892  /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
107893  /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
107894  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
107895  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
107896  /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
107897  /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
107898  /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
107899  /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
107900  /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
107901  /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
107902  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
107903  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
107904  /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
107905  /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
107906  /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
107907  /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
107908  /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
107909  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
107910  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
107911  /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
107912  /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
107913  /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
107914  /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
107915  /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
107916  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
107917  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
107918  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
107919  /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
107920  /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
107921  /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
107922  /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
107923  /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
107924  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
107925  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
107926  /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
107927  /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
107928  /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
107929  /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
107930  /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
107931  /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
107932  /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
107933  /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
107934  /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
107935  /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
107936  /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
107937  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
107938  /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
107939  /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
107940  /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
107941  /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
107942  /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
107943  /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
107944  /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
107945  /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
107946  /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
107947  /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
107948  /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
107949  /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
107950  /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
107951  /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
107952  /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
107953  /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
107954  /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
107955  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
107956  /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
107957  /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
107958  /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
107959  /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
107960  /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
107961  /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
107962  /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
107963  /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
107964  /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
107965  /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
107966  /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
107967  /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
107968  /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
107969  /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
107970  /*  1550 */   252,  252,  252,  252,  252,  252,  236,
107971 };
107972 #define YY_SHIFT_USE_DFLT (-74)
107973 #define YY_SHIFT_COUNT (418)
107974 #define YY_SHIFT_MIN   (-73)
107975 #define YY_SHIFT_MAX   (1468)
107976 static const short yy_shift_ofst[] = {
107977  /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
107978  /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
107979  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
107980  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
107981  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
107982  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
107983  /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
107984  /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
107985  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
107986  /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
107987  /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
107988  /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
107989  /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
107990  /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
107991  /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
107992  /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
107993  /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
107994  /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
107995  /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
107996  /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
107997  /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
107998  /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
107999  /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
108000  /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
108001  /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
108002  /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
108003  /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
108004  /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
108005  /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
108006  /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
108007  /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
108008  /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
108009  /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
108010  /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
108011  /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
108012  /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
108013  /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
108014  /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
108015  /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
108016  /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
108017  /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
108018  /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
108019 };
108020 #define YY_REDUCE_USE_DFLT (-142)
108021 #define YY_REDUCE_COUNT (312)
108022 #define YY_REDUCE_MIN   (-141)
108023 #define YY_REDUCE_MAX   (1369)
108024 static const short yy_reduce_ofst[] = {
108025  /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
108026  /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
108027  /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
108028  /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
108029  /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
108030  /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
108031  /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
108032  /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
108033  /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
108034  /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
108035  /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
108036  /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
108037  /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
108038  /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
108039  /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
108040  /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
108041  /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
108042  /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
108043  /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
108044  /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
108045  /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
108046  /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
108047  /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
108048  /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
108049  /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
108050  /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
108051  /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
108052  /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
108053  /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
108054  /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
108055  /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
108056  /*   310 */  1031, 1023, 1030,
108057 };
108058 static const YYACTIONTYPE yy_default[] = {
108059  /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
108060  /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
108061  /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108062  /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108063  /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108064  /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108065  /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
108066  /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
108067  /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
108068  /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
108069  /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
108070  /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108071  /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
108072  /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
108073  /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108074  /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
108075  /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108076  /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108077  /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
108078  /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
108079  /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
108080  /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
108081  /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
108082  /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
108083  /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
108084  /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
108085  /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
108086  /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
108087  /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
108088  /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
108089  /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
108090  /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
108091  /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108092  /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
108093  /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108094  /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
108095  /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
108096  /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108097  /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108098  /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
108099  /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
108100  /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
108101  /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
108102  /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
108103  /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
108104  /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
108105  /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
108106  /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
108107  /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
108108  /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
108109  /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
108110  /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
108111  /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
108112  /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
108113  /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
108114  /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
108115  /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
108116  /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
108117  /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
108118  /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
108119  /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
108120  /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
108121  /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
108122 };
108123
108124 /* The next table maps tokens into fallback tokens.  If a construct
108125 ** like the following:
108126 ** 
108127 **      %fallback ID X Y Z.
108128 **
108129 ** appears in the grammar, then ID becomes a fallback token for X, Y,
108130 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
108131 ** but it does not parse, the type of the token is changed to ID and
108132 ** the parse is retried before an error is thrown.
108133 */
108134 #ifdef YYFALLBACK
108135 static const YYCODETYPE yyFallback[] = {
108136     0,  /*          $ => nothing */
108137     0,  /*       SEMI => nothing */
108138    26,  /*    EXPLAIN => ID */
108139    26,  /*      QUERY => ID */
108140    26,  /*       PLAN => ID */
108141    26,  /*      BEGIN => ID */
108142     0,  /* TRANSACTION => nothing */
108143    26,  /*   DEFERRED => ID */
108144    26,  /*  IMMEDIATE => ID */
108145    26,  /*  EXCLUSIVE => ID */
108146     0,  /*     COMMIT => nothing */
108147    26,  /*        END => ID */
108148    26,  /*   ROLLBACK => ID */
108149    26,  /*  SAVEPOINT => ID */
108150    26,  /*    RELEASE => ID */
108151     0,  /*         TO => nothing */
108152     0,  /*      TABLE => nothing */
108153     0,  /*     CREATE => nothing */
108154    26,  /*         IF => ID */
108155     0,  /*        NOT => nothing */
108156     0,  /*     EXISTS => nothing */
108157    26,  /*       TEMP => ID */
108158     0,  /*         LP => nothing */
108159     0,  /*         RP => nothing */
108160     0,  /*         AS => nothing */
108161     0,  /*      COMMA => nothing */
108162     0,  /*         ID => nothing */
108163     0,  /*    INDEXED => nothing */
108164    26,  /*      ABORT => ID */
108165    26,  /*     ACTION => ID */
108166    26,  /*      AFTER => ID */
108167    26,  /*    ANALYZE => ID */
108168    26,  /*        ASC => ID */
108169    26,  /*     ATTACH => ID */
108170    26,  /*     BEFORE => ID */
108171    26,  /*         BY => ID */
108172    26,  /*    CASCADE => ID */
108173    26,  /*       CAST => ID */
108174    26,  /*   COLUMNKW => ID */
108175    26,  /*   CONFLICT => ID */
108176    26,  /*   DATABASE => ID */
108177    26,  /*       DESC => ID */
108178    26,  /*     DETACH => ID */
108179    26,  /*       EACH => ID */
108180    26,  /*       FAIL => ID */
108181    26,  /*        FOR => ID */
108182    26,  /*     IGNORE => ID */
108183    26,  /*  INITIALLY => ID */
108184    26,  /*    INSTEAD => ID */
108185    26,  /*    LIKE_KW => ID */
108186    26,  /*      MATCH => ID */
108187    26,  /*         NO => ID */
108188    26,  /*        KEY => ID */
108189    26,  /*         OF => ID */
108190    26,  /*     OFFSET => ID */
108191    26,  /*     PRAGMA => ID */
108192    26,  /*      RAISE => ID */
108193    26,  /*    REPLACE => ID */
108194    26,  /*   RESTRICT => ID */
108195    26,  /*        ROW => ID */
108196    26,  /*    TRIGGER => ID */
108197    26,  /*     VACUUM => ID */
108198    26,  /*       VIEW => ID */
108199    26,  /*    VIRTUAL => ID */
108200    26,  /*    REINDEX => ID */
108201    26,  /*     RENAME => ID */
108202    26,  /*   CTIME_KW => ID */
108203 };
108204 #endif /* YYFALLBACK */
108205
108206 /* The following structure represents a single element of the
108207 ** parser's stack.  Information stored includes:
108208 **
108209 **   +  The state number for the parser at this level of the stack.
108210 **
108211 **   +  The value of the token stored at this level of the stack.
108212 **      (In other words, the "major" token.)
108213 **
108214 **   +  The semantic value stored at this level of the stack.  This is
108215 **      the information used by the action routines in the grammar.
108216 **      It is sometimes called the "minor" token.
108217 */
108218 struct yyStackEntry {
108219   YYACTIONTYPE stateno;  /* The state-number */
108220   YYCODETYPE major;      /* The major token value.  This is the code
108221                          ** number for the token at this stack level */
108222   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
108223                          ** is the value of the token  */
108224 };
108225 typedef struct yyStackEntry yyStackEntry;
108226
108227 /* The state of the parser is completely contained in an instance of
108228 ** the following structure */
108229 struct yyParser {
108230   int yyidx;                    /* Index of top element in stack */
108231 #ifdef YYTRACKMAXSTACKDEPTH
108232   int yyidxMax;                 /* Maximum value of yyidx */
108233 #endif
108234   int yyerrcnt;                 /* Shifts left before out of the error */
108235   sqlcipher3ParserARG_SDECL                /* A place to hold %extra_argument */
108236 #if YYSTACKDEPTH<=0
108237   int yystksz;                  /* Current side of the stack */
108238   yyStackEntry *yystack;        /* The parser's stack */
108239 #else
108240   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
108241 #endif
108242 };
108243 typedef struct yyParser yyParser;
108244
108245 #ifndef NDEBUG
108246 /* #include <stdio.h> */
108247 static FILE *yyTraceFILE = 0;
108248 static char *yyTracePrompt = 0;
108249 #endif /* NDEBUG */
108250
108251 #ifndef NDEBUG
108252 /* 
108253 ** Turn parser tracing on by giving a stream to which to write the trace
108254 ** and a prompt to preface each trace message.  Tracing is turned off
108255 ** by making either argument NULL 
108256 **
108257 ** Inputs:
108258 ** <ul>
108259 ** <li> A FILE* to which trace output should be written.
108260 **      If NULL, then tracing is turned off.
108261 ** <li> A prefix string written at the beginning of every
108262 **      line of trace output.  If NULL, then tracing is
108263 **      turned off.
108264 ** </ul>
108265 **
108266 ** Outputs:
108267 ** None.
108268 */
108269 SQLCIPHER_PRIVATE void sqlcipher3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
108270   yyTraceFILE = TraceFILE;
108271   yyTracePrompt = zTracePrompt;
108272   if( yyTraceFILE==0 ) yyTracePrompt = 0;
108273   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
108274 }
108275 #endif /* NDEBUG */
108276
108277 #ifndef NDEBUG
108278 /* For tracing shifts, the names of all terminals and nonterminals
108279 ** are required.  The following table supplies these names */
108280 static const char *const yyTokenName[] = { 
108281   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
108282   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
108283   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
108284   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
108285   "TABLE",         "CREATE",        "IF",            "NOT",         
108286   "EXISTS",        "TEMP",          "LP",            "RP",          
108287   "AS",            "COMMA",         "ID",            "INDEXED",     
108288   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
108289   "ASC",           "ATTACH",        "BEFORE",        "BY",          
108290   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
108291   "DATABASE",      "DESC",          "DETACH",        "EACH",        
108292   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
108293   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
108294   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
108295   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
108296   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
108297   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
108298   "OR",            "AND",           "IS",            "BETWEEN",     
108299   "IN",            "ISNULL",        "NOTNULL",       "NE",          
108300   "EQ",            "GT",            "LE",            "LT",          
108301   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
108302   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
108303   "STAR",          "SLASH",         "REM",           "CONCAT",      
108304   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
108305   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
108306   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
108307   "ON",            "INSERT",        "DELETE",        "UPDATE",      
108308   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
108309   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
108310   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
108311   "JOIN",          "USING",         "ORDER",         "GROUP",       
108312   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
108313   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
108314   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
108315   "THEN",          "ELSE",          "INDEX",         "ALTER",       
108316   "ADD",           "error",         "input",         "cmdlist",     
108317   "ecmd",          "explain",       "cmdx",          "cmd",         
108318   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
108319   "create_table",  "create_table_args",  "createkw",      "temp",        
108320   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
108321   "select",        "column",        "columnid",      "type",        
108322   "carglist",      "id",            "ids",           "typetoken",   
108323   "typename",      "signed",        "plus_num",      "minus_num",   
108324   "carg",          "ccons",         "term",          "expr",        
108325   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
108326   "refargs",       "defer_subclause",  "refarg",        "refact",      
108327   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
108328   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
108329   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
108330   "distinct",      "selcollist",    "from",          "where_opt",   
108331   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
108332   "sclp",          "as",            "seltablist",    "stl_prefix",  
108333   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
108334   "joinop2",       "inscollist",    "sortlist",      "sortitem",    
108335   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
108336   "itemlist",      "exprlist",      "likeop",        "between_op",  
108337   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
108338   "uniqueflag",    "collate",       "nmnum",         "plus_opt",    
108339   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
108340   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
108341   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",     
108342   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
108343   "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
108344 };
108345 #endif /* NDEBUG */
108346
108347 #ifndef NDEBUG
108348 /* For tracing reduce actions, the names of all rules are required.
108349 */
108350 static const char *const yyRuleName[] = {
108351  /*   0 */ "input ::= cmdlist",
108352  /*   1 */ "cmdlist ::= cmdlist ecmd",
108353  /*   2 */ "cmdlist ::= ecmd",
108354  /*   3 */ "ecmd ::= SEMI",
108355  /*   4 */ "ecmd ::= explain cmdx SEMI",
108356  /*   5 */ "explain ::=",
108357  /*   6 */ "explain ::= EXPLAIN",
108358  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
108359  /*   8 */ "cmdx ::= cmd",
108360  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
108361  /*  10 */ "trans_opt ::=",
108362  /*  11 */ "trans_opt ::= TRANSACTION",
108363  /*  12 */ "trans_opt ::= TRANSACTION nm",
108364  /*  13 */ "transtype ::=",
108365  /*  14 */ "transtype ::= DEFERRED",
108366  /*  15 */ "transtype ::= IMMEDIATE",
108367  /*  16 */ "transtype ::= EXCLUSIVE",
108368  /*  17 */ "cmd ::= COMMIT trans_opt",
108369  /*  18 */ "cmd ::= END trans_opt",
108370  /*  19 */ "cmd ::= ROLLBACK trans_opt",
108371  /*  20 */ "savepoint_opt ::= SAVEPOINT",
108372  /*  21 */ "savepoint_opt ::=",
108373  /*  22 */ "cmd ::= SAVEPOINT nm",
108374  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
108375  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
108376  /*  25 */ "cmd ::= create_table create_table_args",
108377  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
108378  /*  27 */ "createkw ::= CREATE",
108379  /*  28 */ "ifnotexists ::=",
108380  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
108381  /*  30 */ "temp ::= TEMP",
108382  /*  31 */ "temp ::=",
108383  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
108384  /*  33 */ "create_table_args ::= AS select",
108385  /*  34 */ "columnlist ::= columnlist COMMA column",
108386  /*  35 */ "columnlist ::= column",
108387  /*  36 */ "column ::= columnid type carglist",
108388  /*  37 */ "columnid ::= nm",
108389  /*  38 */ "id ::= ID",
108390  /*  39 */ "id ::= INDEXED",
108391  /*  40 */ "ids ::= ID|STRING",
108392  /*  41 */ "nm ::= id",
108393  /*  42 */ "nm ::= STRING",
108394  /*  43 */ "nm ::= JOIN_KW",
108395  /*  44 */ "type ::=",
108396  /*  45 */ "type ::= typetoken",
108397  /*  46 */ "typetoken ::= typename",
108398  /*  47 */ "typetoken ::= typename LP signed RP",
108399  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
108400  /*  49 */ "typename ::= ids",
108401  /*  50 */ "typename ::= typename ids",
108402  /*  51 */ "signed ::= plus_num",
108403  /*  52 */ "signed ::= minus_num",
108404  /*  53 */ "carglist ::= carglist carg",
108405  /*  54 */ "carglist ::=",
108406  /*  55 */ "carg ::= CONSTRAINT nm ccons",
108407  /*  56 */ "carg ::= ccons",
108408  /*  57 */ "ccons ::= DEFAULT term",
108409  /*  58 */ "ccons ::= DEFAULT LP expr RP",
108410  /*  59 */ "ccons ::= DEFAULT PLUS term",
108411  /*  60 */ "ccons ::= DEFAULT MINUS term",
108412  /*  61 */ "ccons ::= DEFAULT id",
108413  /*  62 */ "ccons ::= NULL onconf",
108414  /*  63 */ "ccons ::= NOT NULL onconf",
108415  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
108416  /*  65 */ "ccons ::= UNIQUE onconf",
108417  /*  66 */ "ccons ::= CHECK LP expr RP",
108418  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
108419  /*  68 */ "ccons ::= defer_subclause",
108420  /*  69 */ "ccons ::= COLLATE ids",
108421  /*  70 */ "autoinc ::=",
108422  /*  71 */ "autoinc ::= AUTOINCR",
108423  /*  72 */ "refargs ::=",
108424  /*  73 */ "refargs ::= refargs refarg",
108425  /*  74 */ "refarg ::= MATCH nm",
108426  /*  75 */ "refarg ::= ON INSERT refact",
108427  /*  76 */ "refarg ::= ON DELETE refact",
108428  /*  77 */ "refarg ::= ON UPDATE refact",
108429  /*  78 */ "refact ::= SET NULL",
108430  /*  79 */ "refact ::= SET DEFAULT",
108431  /*  80 */ "refact ::= CASCADE",
108432  /*  81 */ "refact ::= RESTRICT",
108433  /*  82 */ "refact ::= NO ACTION",
108434  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
108435  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
108436  /*  85 */ "init_deferred_pred_opt ::=",
108437  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
108438  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
108439  /*  88 */ "conslist_opt ::=",
108440  /*  89 */ "conslist_opt ::= COMMA conslist",
108441  /*  90 */ "conslist ::= conslist COMMA tcons",
108442  /*  91 */ "conslist ::= conslist tcons",
108443  /*  92 */ "conslist ::= tcons",
108444  /*  93 */ "tcons ::= CONSTRAINT nm",
108445  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
108446  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
108447  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
108448  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
108449  /*  98 */ "defer_subclause_opt ::=",
108450  /*  99 */ "defer_subclause_opt ::= defer_subclause",
108451  /* 100 */ "onconf ::=",
108452  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
108453  /* 102 */ "orconf ::=",
108454  /* 103 */ "orconf ::= OR resolvetype",
108455  /* 104 */ "resolvetype ::= raisetype",
108456  /* 105 */ "resolvetype ::= IGNORE",
108457  /* 106 */ "resolvetype ::= REPLACE",
108458  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
108459  /* 108 */ "ifexists ::= IF EXISTS",
108460  /* 109 */ "ifexists ::=",
108461  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
108462  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
108463  /* 112 */ "cmd ::= select",
108464  /* 113 */ "select ::= oneselect",
108465  /* 114 */ "select ::= select multiselect_op oneselect",
108466  /* 115 */ "multiselect_op ::= UNION",
108467  /* 116 */ "multiselect_op ::= UNION ALL",
108468  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
108469  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
108470  /* 119 */ "distinct ::= DISTINCT",
108471  /* 120 */ "distinct ::= ALL",
108472  /* 121 */ "distinct ::=",
108473  /* 122 */ "sclp ::= selcollist COMMA",
108474  /* 123 */ "sclp ::=",
108475  /* 124 */ "selcollist ::= sclp expr as",
108476  /* 125 */ "selcollist ::= sclp STAR",
108477  /* 126 */ "selcollist ::= sclp nm DOT STAR",
108478  /* 127 */ "as ::= AS nm",
108479  /* 128 */ "as ::= ids",
108480  /* 129 */ "as ::=",
108481  /* 130 */ "from ::=",
108482  /* 131 */ "from ::= FROM seltablist",
108483  /* 132 */ "stl_prefix ::= seltablist joinop",
108484  /* 133 */ "stl_prefix ::=",
108485  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
108486  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
108487  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
108488  /* 137 */ "dbnm ::=",
108489  /* 138 */ "dbnm ::= DOT nm",
108490  /* 139 */ "fullname ::= nm dbnm",
108491  /* 140 */ "joinop ::= COMMA|JOIN",
108492  /* 141 */ "joinop ::= JOIN_KW JOIN",
108493  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
108494  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
108495  /* 144 */ "on_opt ::= ON expr",
108496  /* 145 */ "on_opt ::=",
108497  /* 146 */ "indexed_opt ::=",
108498  /* 147 */ "indexed_opt ::= INDEXED BY nm",
108499  /* 148 */ "indexed_opt ::= NOT INDEXED",
108500  /* 149 */ "using_opt ::= USING LP inscollist RP",
108501  /* 150 */ "using_opt ::=",
108502  /* 151 */ "orderby_opt ::=",
108503  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
108504  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
108505  /* 154 */ "sortlist ::= sortitem sortorder",
108506  /* 155 */ "sortitem ::= expr",
108507  /* 156 */ "sortorder ::= ASC",
108508  /* 157 */ "sortorder ::= DESC",
108509  /* 158 */ "sortorder ::=",
108510  /* 159 */ "groupby_opt ::=",
108511  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
108512  /* 161 */ "having_opt ::=",
108513  /* 162 */ "having_opt ::= HAVING expr",
108514  /* 163 */ "limit_opt ::=",
108515  /* 164 */ "limit_opt ::= LIMIT expr",
108516  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
108517  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
108518  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
108519  /* 168 */ "where_opt ::=",
108520  /* 169 */ "where_opt ::= WHERE expr",
108521  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
108522  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
108523  /* 172 */ "setlist ::= nm EQ expr",
108524  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
108525  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
108526  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
108527  /* 176 */ "insert_cmd ::= INSERT orconf",
108528  /* 177 */ "insert_cmd ::= REPLACE",
108529  /* 178 */ "itemlist ::= itemlist COMMA expr",
108530  /* 179 */ "itemlist ::= expr",
108531  /* 180 */ "inscollist_opt ::=",
108532  /* 181 */ "inscollist_opt ::= LP inscollist RP",
108533  /* 182 */ "inscollist ::= inscollist COMMA nm",
108534  /* 183 */ "inscollist ::= nm",
108535  /* 184 */ "expr ::= term",
108536  /* 185 */ "expr ::= LP expr RP",
108537  /* 186 */ "term ::= NULL",
108538  /* 187 */ "expr ::= id",
108539  /* 188 */ "expr ::= JOIN_KW",
108540  /* 189 */ "expr ::= nm DOT nm",
108541  /* 190 */ "expr ::= nm DOT nm DOT nm",
108542  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
108543  /* 192 */ "term ::= STRING",
108544  /* 193 */ "expr ::= REGISTER",
108545  /* 194 */ "expr ::= VARIABLE",
108546  /* 195 */ "expr ::= expr COLLATE ids",
108547  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
108548  /* 197 */ "expr ::= ID LP distinct exprlist RP",
108549  /* 198 */ "expr ::= ID LP STAR RP",
108550  /* 199 */ "term ::= CTIME_KW",
108551  /* 200 */ "expr ::= expr AND expr",
108552  /* 201 */ "expr ::= expr OR expr",
108553  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
108554  /* 203 */ "expr ::= expr EQ|NE expr",
108555  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
108556  /* 205 */ "expr ::= expr PLUS|MINUS expr",
108557  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
108558  /* 207 */ "expr ::= expr CONCAT expr",
108559  /* 208 */ "likeop ::= LIKE_KW",
108560  /* 209 */ "likeop ::= NOT LIKE_KW",
108561  /* 210 */ "likeop ::= MATCH",
108562  /* 211 */ "likeop ::= NOT MATCH",
108563  /* 212 */ "expr ::= expr likeop expr",
108564  /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
108565  /* 214 */ "expr ::= expr ISNULL|NOTNULL",
108566  /* 215 */ "expr ::= expr NOT NULL",
108567  /* 216 */ "expr ::= expr IS expr",
108568  /* 217 */ "expr ::= expr IS NOT expr",
108569  /* 218 */ "expr ::= NOT expr",
108570  /* 219 */ "expr ::= BITNOT expr",
108571  /* 220 */ "expr ::= MINUS expr",
108572  /* 221 */ "expr ::= PLUS expr",
108573  /* 222 */ "between_op ::= BETWEEN",
108574  /* 223 */ "between_op ::= NOT BETWEEN",
108575  /* 224 */ "expr ::= expr between_op expr AND expr",
108576  /* 225 */ "in_op ::= IN",
108577  /* 226 */ "in_op ::= NOT IN",
108578  /* 227 */ "expr ::= expr in_op LP exprlist RP",
108579  /* 228 */ "expr ::= LP select RP",
108580  /* 229 */ "expr ::= expr in_op LP select RP",
108581  /* 230 */ "expr ::= expr in_op nm dbnm",
108582  /* 231 */ "expr ::= EXISTS LP select RP",
108583  /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
108584  /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
108585  /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
108586  /* 235 */ "case_else ::= ELSE expr",
108587  /* 236 */ "case_else ::=",
108588  /* 237 */ "case_operand ::= expr",
108589  /* 238 */ "case_operand ::=",
108590  /* 239 */ "exprlist ::= nexprlist",
108591  /* 240 */ "exprlist ::=",
108592  /* 241 */ "nexprlist ::= nexprlist COMMA expr",
108593  /* 242 */ "nexprlist ::= expr",
108594  /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
108595  /* 244 */ "uniqueflag ::= UNIQUE",
108596  /* 245 */ "uniqueflag ::=",
108597  /* 246 */ "idxlist_opt ::=",
108598  /* 247 */ "idxlist_opt ::= LP idxlist RP",
108599  /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
108600  /* 249 */ "idxlist ::= nm collate sortorder",
108601  /* 250 */ "collate ::=",
108602  /* 251 */ "collate ::= COLLATE ids",
108603  /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
108604  /* 253 */ "cmd ::= VACUUM",
108605  /* 254 */ "cmd ::= VACUUM nm",
108606  /* 255 */ "cmd ::= PRAGMA nm dbnm",
108607  /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
108608  /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
108609  /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
108610  /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
108611  /* 260 */ "nmnum ::= plus_num",
108612  /* 261 */ "nmnum ::= nm",
108613  /* 262 */ "nmnum ::= ON",
108614  /* 263 */ "nmnum ::= DELETE",
108615  /* 264 */ "nmnum ::= DEFAULT",
108616  /* 265 */ "plus_num ::= plus_opt number",
108617  /* 266 */ "minus_num ::= MINUS number",
108618  /* 267 */ "number ::= INTEGER|FLOAT",
108619  /* 268 */ "plus_opt ::= PLUS",
108620  /* 269 */ "plus_opt ::=",
108621  /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
108622  /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
108623  /* 272 */ "trigger_time ::= BEFORE",
108624  /* 273 */ "trigger_time ::= AFTER",
108625  /* 274 */ "trigger_time ::= INSTEAD OF",
108626  /* 275 */ "trigger_time ::=",
108627  /* 276 */ "trigger_event ::= DELETE|INSERT",
108628  /* 277 */ "trigger_event ::= UPDATE",
108629  /* 278 */ "trigger_event ::= UPDATE OF inscollist",
108630  /* 279 */ "foreach_clause ::=",
108631  /* 280 */ "foreach_clause ::= FOR EACH ROW",
108632  /* 281 */ "when_clause ::=",
108633  /* 282 */ "when_clause ::= WHEN expr",
108634  /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
108635  /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
108636  /* 285 */ "trnm ::= nm",
108637  /* 286 */ "trnm ::= nm DOT nm",
108638  /* 287 */ "tridxby ::=",
108639  /* 288 */ "tridxby ::= INDEXED BY nm",
108640  /* 289 */ "tridxby ::= NOT INDEXED",
108641  /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
108642  /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
108643  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
108644  /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
108645  /* 294 */ "trigger_cmd ::= select",
108646  /* 295 */ "expr ::= RAISE LP IGNORE RP",
108647  /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
108648  /* 297 */ "raisetype ::= ROLLBACK",
108649  /* 298 */ "raisetype ::= ABORT",
108650  /* 299 */ "raisetype ::= FAIL",
108651  /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
108652  /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
108653  /* 302 */ "cmd ::= DETACH database_kw_opt expr",
108654  /* 303 */ "key_opt ::=",
108655  /* 304 */ "key_opt ::= KEY expr",
108656  /* 305 */ "database_kw_opt ::= DATABASE",
108657  /* 306 */ "database_kw_opt ::=",
108658  /* 307 */ "cmd ::= REINDEX",
108659  /* 308 */ "cmd ::= REINDEX nm dbnm",
108660  /* 309 */ "cmd ::= ANALYZE",
108661  /* 310 */ "cmd ::= ANALYZE nm dbnm",
108662  /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
108663  /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
108664  /* 313 */ "add_column_fullname ::= fullname",
108665  /* 314 */ "kwcolumn_opt ::=",
108666  /* 315 */ "kwcolumn_opt ::= COLUMNKW",
108667  /* 316 */ "cmd ::= create_vtab",
108668  /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
108669  /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
108670  /* 319 */ "vtabarglist ::= vtabarg",
108671  /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
108672  /* 321 */ "vtabarg ::=",
108673  /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
108674  /* 323 */ "vtabargtoken ::= ANY",
108675  /* 324 */ "vtabargtoken ::= lp anylist RP",
108676  /* 325 */ "lp ::= LP",
108677  /* 326 */ "anylist ::=",
108678  /* 327 */ "anylist ::= anylist LP anylist RP",
108679  /* 328 */ "anylist ::= anylist ANY",
108680 };
108681 #endif /* NDEBUG */
108682
108683
108684 #if YYSTACKDEPTH<=0
108685 /*
108686 ** Try to increase the size of the parser stack.
108687 */
108688 static void yyGrowStack(yyParser *p){
108689   int newSize;
108690   yyStackEntry *pNew;
108691
108692   newSize = p->yystksz*2 + 100;
108693   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
108694   if( pNew ){
108695     p->yystack = pNew;
108696     p->yystksz = newSize;
108697 #ifndef NDEBUG
108698     if( yyTraceFILE ){
108699       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
108700               yyTracePrompt, p->yystksz);
108701     }
108702 #endif
108703   }
108704 }
108705 #endif
108706
108707 /* 
108708 ** This function allocates a new parser.
108709 ** The only argument is a pointer to a function which works like
108710 ** malloc.
108711 **
108712 ** Inputs:
108713 ** A pointer to the function used to allocate memory.
108714 **
108715 ** Outputs:
108716 ** A pointer to a parser.  This pointer is used in subsequent calls
108717 ** to sqlcipher3Parser and sqlcipher3ParserFree.
108718 */
108719 SQLCIPHER_PRIVATE void *sqlcipher3ParserAlloc(void *(*mallocProc)(size_t)){
108720   yyParser *pParser;
108721   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
108722   if( pParser ){
108723     pParser->yyidx = -1;
108724 #ifdef YYTRACKMAXSTACKDEPTH
108725     pParser->yyidxMax = 0;
108726 #endif
108727 #if YYSTACKDEPTH<=0
108728     pParser->yystack = NULL;
108729     pParser->yystksz = 0;
108730     yyGrowStack(pParser);
108731 #endif
108732   }
108733   return pParser;
108734 }
108735
108736 /* The following function deletes the value associated with a
108737 ** symbol.  The symbol can be either a terminal or nonterminal.
108738 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
108739 ** the value.
108740 */
108741 static void yy_destructor(
108742   yyParser *yypParser,    /* The parser */
108743   YYCODETYPE yymajor,     /* Type code for object to destroy */
108744   YYMINORTYPE *yypminor   /* The object to be destroyed */
108745 ){
108746   sqlcipher3ParserARG_FETCH;
108747   switch( yymajor ){
108748     /* Here is inserted the actions which take place when a
108749     ** terminal or non-terminal is destroyed.  This can happen
108750     ** when the symbol is popped from the stack during a
108751     ** reduce or during error processing or when a parser is 
108752     ** being destroyed before it is finished parsing.
108753     **
108754     ** Note: during a reduce, the only symbols destroyed are those
108755     ** which appear on the RHS of the rule, but which are not used
108756     ** inside the C code.
108757     */
108758     case 160: /* select */
108759     case 194: /* oneselect */
108760 {
108761 sqlcipher3SelectDelete(pParse->db, (yypminor->yy387));
108762 }
108763       break;
108764     case 174: /* term */
108765     case 175: /* expr */
108766 {
108767 sqlcipher3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
108768 }
108769       break;
108770     case 179: /* idxlist_opt */
108771     case 187: /* idxlist */
108772     case 197: /* selcollist */
108773     case 200: /* groupby_opt */
108774     case 202: /* orderby_opt */
108775     case 204: /* sclp */
108776     case 214: /* sortlist */
108777     case 216: /* nexprlist */
108778     case 217: /* setlist */
108779     case 220: /* itemlist */
108780     case 221: /* exprlist */
108781     case 226: /* case_exprlist */
108782 {
108783 sqlcipher3ExprListDelete(pParse->db, (yypminor->yy322));
108784 }
108785       break;
108786     case 193: /* fullname */
108787     case 198: /* from */
108788     case 206: /* seltablist */
108789     case 207: /* stl_prefix */
108790 {
108791 sqlcipher3SrcListDelete(pParse->db, (yypminor->yy259));
108792 }
108793       break;
108794     case 199: /* where_opt */
108795     case 201: /* having_opt */
108796     case 210: /* on_opt */
108797     case 215: /* sortitem */
108798     case 225: /* case_operand */
108799     case 227: /* case_else */
108800     case 238: /* when_clause */
108801     case 243: /* key_opt */
108802 {
108803 sqlcipher3ExprDelete(pParse->db, (yypminor->yy314));
108804 }
108805       break;
108806     case 211: /* using_opt */
108807     case 213: /* inscollist */
108808     case 219: /* inscollist_opt */
108809 {
108810 sqlcipher3IdListDelete(pParse->db, (yypminor->yy384));
108811 }
108812       break;
108813     case 234: /* trigger_cmd_list */
108814     case 239: /* trigger_cmd */
108815 {
108816 sqlcipher3DeleteTriggerStep(pParse->db, (yypminor->yy203));
108817 }
108818       break;
108819     case 236: /* trigger_event */
108820 {
108821 sqlcipher3IdListDelete(pParse->db, (yypminor->yy90).b);
108822 }
108823       break;
108824     default:  break;   /* If no destructor action specified: do nothing */
108825   }
108826 }
108827
108828 /*
108829 ** Pop the parser's stack once.
108830 **
108831 ** If there is a destructor routine associated with the token which
108832 ** is popped from the stack, then call it.
108833 **
108834 ** Return the major token number for the symbol popped.
108835 */
108836 static int yy_pop_parser_stack(yyParser *pParser){
108837   YYCODETYPE yymajor;
108838   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
108839
108840   /* There is no mechanism by which the parser stack can be popped below
108841   ** empty in SQLite.  */
108842   if( NEVER(pParser->yyidx<0) ) return 0;
108843 #ifndef NDEBUG
108844   if( yyTraceFILE && pParser->yyidx>=0 ){
108845     fprintf(yyTraceFILE,"%sPopping %s\n",
108846       yyTracePrompt,
108847       yyTokenName[yytos->major]);
108848   }
108849 #endif
108850   yymajor = yytos->major;
108851   yy_destructor(pParser, yymajor, &yytos->minor);
108852   pParser->yyidx--;
108853   return yymajor;
108854 }
108855
108856 /* 
108857 ** Deallocate and destroy a parser.  Destructors are all called for
108858 ** all stack elements before shutting the parser down.
108859 **
108860 ** Inputs:
108861 ** <ul>
108862 ** <li>  A pointer to the parser.  This should be a pointer
108863 **       obtained from sqlcipher3ParserAlloc.
108864 ** <li>  A pointer to a function used to reclaim memory obtained
108865 **       from malloc.
108866 ** </ul>
108867 */
108868 SQLCIPHER_PRIVATE void sqlcipher3ParserFree(
108869   void *p,                    /* The parser to be deleted */
108870   void (*freeProc)(void*)     /* Function used to reclaim memory */
108871 ){
108872   yyParser *pParser = (yyParser*)p;
108873   /* In SQLite, we never try to destroy a parser that was not successfully
108874   ** created in the first place. */
108875   if( NEVER(pParser==0) ) return;
108876   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
108877 #if YYSTACKDEPTH<=0
108878   free(pParser->yystack);
108879 #endif
108880   (*freeProc)((void*)pParser);
108881 }
108882
108883 /*
108884 ** Return the peak depth of the stack for a parser.
108885 */
108886 #ifdef YYTRACKMAXSTACKDEPTH
108887 SQLCIPHER_PRIVATE int sqlcipher3ParserStackPeak(void *p){
108888   yyParser *pParser = (yyParser*)p;
108889   return pParser->yyidxMax;
108890 }
108891 #endif
108892
108893 /*
108894 ** Find the appropriate action for a parser given the terminal
108895 ** look-ahead token iLookAhead.
108896 **
108897 ** If the look-ahead token is YYNOCODE, then check to see if the action is
108898 ** independent of the look-ahead.  If it is, return the action, otherwise
108899 ** return YY_NO_ACTION.
108900 */
108901 static int yy_find_shift_action(
108902   yyParser *pParser,        /* The parser */
108903   YYCODETYPE iLookAhead     /* The look-ahead token */
108904 ){
108905   int i;
108906   int stateno = pParser->yystack[pParser->yyidx].stateno;
108907  
108908   if( stateno>YY_SHIFT_COUNT
108909    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
108910     return yy_default[stateno];
108911   }
108912   assert( iLookAhead!=YYNOCODE );
108913   i += iLookAhead;
108914   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
108915     if( iLookAhead>0 ){
108916 #ifdef YYFALLBACK
108917       YYCODETYPE iFallback;            /* Fallback token */
108918       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
108919              && (iFallback = yyFallback[iLookAhead])!=0 ){
108920 #ifndef NDEBUG
108921         if( yyTraceFILE ){
108922           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
108923              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
108924         }
108925 #endif
108926         return yy_find_shift_action(pParser, iFallback);
108927       }
108928 #endif
108929 #ifdef YYWILDCARD
108930       {
108931         int j = i - iLookAhead + YYWILDCARD;
108932         if( 
108933 #if YY_SHIFT_MIN+YYWILDCARD<0
108934           j>=0 &&
108935 #endif
108936 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
108937           j<YY_ACTTAB_COUNT &&
108938 #endif
108939           yy_lookahead[j]==YYWILDCARD
108940         ){
108941 #ifndef NDEBUG
108942           if( yyTraceFILE ){
108943             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
108944                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
108945           }
108946 #endif /* NDEBUG */
108947           return yy_action[j];
108948         }
108949       }
108950 #endif /* YYWILDCARD */
108951     }
108952     return yy_default[stateno];
108953   }else{
108954     return yy_action[i];
108955   }
108956 }
108957
108958 /*
108959 ** Find the appropriate action for a parser given the non-terminal
108960 ** look-ahead token iLookAhead.
108961 **
108962 ** If the look-ahead token is YYNOCODE, then check to see if the action is
108963 ** independent of the look-ahead.  If it is, return the action, otherwise
108964 ** return YY_NO_ACTION.
108965 */
108966 static int yy_find_reduce_action(
108967   int stateno,              /* Current state number */
108968   YYCODETYPE iLookAhead     /* The look-ahead token */
108969 ){
108970   int i;
108971 #ifdef YYERRORSYMBOL
108972   if( stateno>YY_REDUCE_COUNT ){
108973     return yy_default[stateno];
108974   }
108975 #else
108976   assert( stateno<=YY_REDUCE_COUNT );
108977 #endif
108978   i = yy_reduce_ofst[stateno];
108979   assert( i!=YY_REDUCE_USE_DFLT );
108980   assert( iLookAhead!=YYNOCODE );
108981   i += iLookAhead;
108982 #ifdef YYERRORSYMBOL
108983   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
108984     return yy_default[stateno];
108985   }
108986 #else
108987   assert( i>=0 && i<YY_ACTTAB_COUNT );
108988   assert( yy_lookahead[i]==iLookAhead );
108989 #endif
108990   return yy_action[i];
108991 }
108992
108993 /*
108994 ** The following routine is called if the stack overflows.
108995 */
108996 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
108997    sqlcipher3ParserARG_FETCH;
108998    yypParser->yyidx--;
108999 #ifndef NDEBUG
109000    if( yyTraceFILE ){
109001      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
109002    }
109003 #endif
109004    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
109005    /* Here code is inserted which will execute if the parser
109006    ** stack every overflows */
109007
109008   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
109009   sqlcipher3ErrorMsg(pParse, "parser stack overflow");
109010   pParse->parseError = 1;
109011    sqlcipher3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
109012 }
109013
109014 /*
109015 ** Perform a shift action.
109016 */
109017 static void yy_shift(
109018   yyParser *yypParser,          /* The parser to be shifted */
109019   int yyNewState,               /* The new state to shift in */
109020   int yyMajor,                  /* The major token to shift in */
109021   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
109022 ){
109023   yyStackEntry *yytos;
109024   yypParser->yyidx++;
109025 #ifdef YYTRACKMAXSTACKDEPTH
109026   if( yypParser->yyidx>yypParser->yyidxMax ){
109027     yypParser->yyidxMax = yypParser->yyidx;
109028   }
109029 #endif
109030 #if YYSTACKDEPTH>0 
109031   if( yypParser->yyidx>=YYSTACKDEPTH ){
109032     yyStackOverflow(yypParser, yypMinor);
109033     return;
109034   }
109035 #else
109036   if( yypParser->yyidx>=yypParser->yystksz ){
109037     yyGrowStack(yypParser);
109038     if( yypParser->yyidx>=yypParser->yystksz ){
109039       yyStackOverflow(yypParser, yypMinor);
109040       return;
109041     }
109042   }
109043 #endif
109044   yytos = &yypParser->yystack[yypParser->yyidx];
109045   yytos->stateno = (YYACTIONTYPE)yyNewState;
109046   yytos->major = (YYCODETYPE)yyMajor;
109047   yytos->minor = *yypMinor;
109048 #ifndef NDEBUG
109049   if( yyTraceFILE && yypParser->yyidx>0 ){
109050     int i;
109051     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
109052     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
109053     for(i=1; i<=yypParser->yyidx; i++)
109054       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
109055     fprintf(yyTraceFILE,"\n");
109056   }
109057 #endif
109058 }
109059
109060 /* The following table contains information about every rule that
109061 ** is used during the reduce.
109062 */
109063 static const struct {
109064   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
109065   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
109066 } yyRuleInfo[] = {
109067   { 142, 1 },
109068   { 143, 2 },
109069   { 143, 1 },
109070   { 144, 1 },
109071   { 144, 3 },
109072   { 145, 0 },
109073   { 145, 1 },
109074   { 145, 3 },
109075   { 146, 1 },
109076   { 147, 3 },
109077   { 149, 0 },
109078   { 149, 1 },
109079   { 149, 2 },
109080   { 148, 0 },
109081   { 148, 1 },
109082   { 148, 1 },
109083   { 148, 1 },
109084   { 147, 2 },
109085   { 147, 2 },
109086   { 147, 2 },
109087   { 151, 1 },
109088   { 151, 0 },
109089   { 147, 2 },
109090   { 147, 3 },
109091   { 147, 5 },
109092   { 147, 2 },
109093   { 152, 6 },
109094   { 154, 1 },
109095   { 156, 0 },
109096   { 156, 3 },
109097   { 155, 1 },
109098   { 155, 0 },
109099   { 153, 4 },
109100   { 153, 2 },
109101   { 158, 3 },
109102   { 158, 1 },
109103   { 161, 3 },
109104   { 162, 1 },
109105   { 165, 1 },
109106   { 165, 1 },
109107   { 166, 1 },
109108   { 150, 1 },
109109   { 150, 1 },
109110   { 150, 1 },
109111   { 163, 0 },
109112   { 163, 1 },
109113   { 167, 1 },
109114   { 167, 4 },
109115   { 167, 6 },
109116   { 168, 1 },
109117   { 168, 2 },
109118   { 169, 1 },
109119   { 169, 1 },
109120   { 164, 2 },
109121   { 164, 0 },
109122   { 172, 3 },
109123   { 172, 1 },
109124   { 173, 2 },
109125   { 173, 4 },
109126   { 173, 3 },
109127   { 173, 3 },
109128   { 173, 2 },
109129   { 173, 2 },
109130   { 173, 3 },
109131   { 173, 5 },
109132   { 173, 2 },
109133   { 173, 4 },
109134   { 173, 4 },
109135   { 173, 1 },
109136   { 173, 2 },
109137   { 178, 0 },
109138   { 178, 1 },
109139   { 180, 0 },
109140   { 180, 2 },
109141   { 182, 2 },
109142   { 182, 3 },
109143   { 182, 3 },
109144   { 182, 3 },
109145   { 183, 2 },
109146   { 183, 2 },
109147   { 183, 1 },
109148   { 183, 1 },
109149   { 183, 2 },
109150   { 181, 3 },
109151   { 181, 2 },
109152   { 184, 0 },
109153   { 184, 2 },
109154   { 184, 2 },
109155   { 159, 0 },
109156   { 159, 2 },
109157   { 185, 3 },
109158   { 185, 2 },
109159   { 185, 1 },
109160   { 186, 2 },
109161   { 186, 7 },
109162   { 186, 5 },
109163   { 186, 5 },
109164   { 186, 10 },
109165   { 188, 0 },
109166   { 188, 1 },
109167   { 176, 0 },
109168   { 176, 3 },
109169   { 189, 0 },
109170   { 189, 2 },
109171   { 190, 1 },
109172   { 190, 1 },
109173   { 190, 1 },
109174   { 147, 4 },
109175   { 192, 2 },
109176   { 192, 0 },
109177   { 147, 8 },
109178   { 147, 4 },
109179   { 147, 1 },
109180   { 160, 1 },
109181   { 160, 3 },
109182   { 195, 1 },
109183   { 195, 2 },
109184   { 195, 1 },
109185   { 194, 9 },
109186   { 196, 1 },
109187   { 196, 1 },
109188   { 196, 0 },
109189   { 204, 2 },
109190   { 204, 0 },
109191   { 197, 3 },
109192   { 197, 2 },
109193   { 197, 4 },
109194   { 205, 2 },
109195   { 205, 1 },
109196   { 205, 0 },
109197   { 198, 0 },
109198   { 198, 2 },
109199   { 207, 2 },
109200   { 207, 0 },
109201   { 206, 7 },
109202   { 206, 7 },
109203   { 206, 7 },
109204   { 157, 0 },
109205   { 157, 2 },
109206   { 193, 2 },
109207   { 208, 1 },
109208   { 208, 2 },
109209   { 208, 3 },
109210   { 208, 4 },
109211   { 210, 2 },
109212   { 210, 0 },
109213   { 209, 0 },
109214   { 209, 3 },
109215   { 209, 2 },
109216   { 211, 4 },
109217   { 211, 0 },
109218   { 202, 0 },
109219   { 202, 3 },
109220   { 214, 4 },
109221   { 214, 2 },
109222   { 215, 1 },
109223   { 177, 1 },
109224   { 177, 1 },
109225   { 177, 0 },
109226   { 200, 0 },
109227   { 200, 3 },
109228   { 201, 0 },
109229   { 201, 2 },
109230   { 203, 0 },
109231   { 203, 2 },
109232   { 203, 4 },
109233   { 203, 4 },
109234   { 147, 5 },
109235   { 199, 0 },
109236   { 199, 2 },
109237   { 147, 7 },
109238   { 217, 5 },
109239   { 217, 3 },
109240   { 147, 8 },
109241   { 147, 5 },
109242   { 147, 6 },
109243   { 218, 2 },
109244   { 218, 1 },
109245   { 220, 3 },
109246   { 220, 1 },
109247   { 219, 0 },
109248   { 219, 3 },
109249   { 213, 3 },
109250   { 213, 1 },
109251   { 175, 1 },
109252   { 175, 3 },
109253   { 174, 1 },
109254   { 175, 1 },
109255   { 175, 1 },
109256   { 175, 3 },
109257   { 175, 5 },
109258   { 174, 1 },
109259   { 174, 1 },
109260   { 175, 1 },
109261   { 175, 1 },
109262   { 175, 3 },
109263   { 175, 6 },
109264   { 175, 5 },
109265   { 175, 4 },
109266   { 174, 1 },
109267   { 175, 3 },
109268   { 175, 3 },
109269   { 175, 3 },
109270   { 175, 3 },
109271   { 175, 3 },
109272   { 175, 3 },
109273   { 175, 3 },
109274   { 175, 3 },
109275   { 222, 1 },
109276   { 222, 2 },
109277   { 222, 1 },
109278   { 222, 2 },
109279   { 175, 3 },
109280   { 175, 5 },
109281   { 175, 2 },
109282   { 175, 3 },
109283   { 175, 3 },
109284   { 175, 4 },
109285   { 175, 2 },
109286   { 175, 2 },
109287   { 175, 2 },
109288   { 175, 2 },
109289   { 223, 1 },
109290   { 223, 2 },
109291   { 175, 5 },
109292   { 224, 1 },
109293   { 224, 2 },
109294   { 175, 5 },
109295   { 175, 3 },
109296   { 175, 5 },
109297   { 175, 4 },
109298   { 175, 4 },
109299   { 175, 5 },
109300   { 226, 5 },
109301   { 226, 4 },
109302   { 227, 2 },
109303   { 227, 0 },
109304   { 225, 1 },
109305   { 225, 0 },
109306   { 221, 1 },
109307   { 221, 0 },
109308   { 216, 3 },
109309   { 216, 1 },
109310   { 147, 11 },
109311   { 228, 1 },
109312   { 228, 0 },
109313   { 179, 0 },
109314   { 179, 3 },
109315   { 187, 5 },
109316   { 187, 3 },
109317   { 229, 0 },
109318   { 229, 2 },
109319   { 147, 4 },
109320   { 147, 1 },
109321   { 147, 2 },
109322   { 147, 3 },
109323   { 147, 5 },
109324   { 147, 6 },
109325   { 147, 5 },
109326   { 147, 6 },
109327   { 230, 1 },
109328   { 230, 1 },
109329   { 230, 1 },
109330   { 230, 1 },
109331   { 230, 1 },
109332   { 170, 2 },
109333   { 171, 2 },
109334   { 232, 1 },
109335   { 231, 1 },
109336   { 231, 0 },
109337   { 147, 5 },
109338   { 233, 11 },
109339   { 235, 1 },
109340   { 235, 1 },
109341   { 235, 2 },
109342   { 235, 0 },
109343   { 236, 1 },
109344   { 236, 1 },
109345   { 236, 3 },
109346   { 237, 0 },
109347   { 237, 3 },
109348   { 238, 0 },
109349   { 238, 2 },
109350   { 234, 3 },
109351   { 234, 2 },
109352   { 240, 1 },
109353   { 240, 3 },
109354   { 241, 0 },
109355   { 241, 3 },
109356   { 241, 2 },
109357   { 239, 7 },
109358   { 239, 8 },
109359   { 239, 5 },
109360   { 239, 5 },
109361   { 239, 1 },
109362   { 175, 4 },
109363   { 175, 6 },
109364   { 191, 1 },
109365   { 191, 1 },
109366   { 191, 1 },
109367   { 147, 4 },
109368   { 147, 6 },
109369   { 147, 3 },
109370   { 243, 0 },
109371   { 243, 2 },
109372   { 242, 1 },
109373   { 242, 0 },
109374   { 147, 1 },
109375   { 147, 3 },
109376   { 147, 1 },
109377   { 147, 3 },
109378   { 147, 6 },
109379   { 147, 6 },
109380   { 244, 1 },
109381   { 245, 0 },
109382   { 245, 1 },
109383   { 147, 1 },
109384   { 147, 4 },
109385   { 246, 7 },
109386   { 247, 1 },
109387   { 247, 3 },
109388   { 248, 0 },
109389   { 248, 2 },
109390   { 249, 1 },
109391   { 249, 3 },
109392   { 250, 1 },
109393   { 251, 0 },
109394   { 251, 4 },
109395   { 251, 2 },
109396 };
109397
109398 static void yy_accept(yyParser*);  /* Forward Declaration */
109399
109400 /*
109401 ** Perform a reduce action and the shift that must immediately
109402 ** follow the reduce.
109403 */
109404 static void yy_reduce(
109405   yyParser *yypParser,         /* The parser */
109406   int yyruleno                 /* Number of the rule by which to reduce */
109407 ){
109408   int yygoto;                     /* The next state */
109409   int yyact;                      /* The next action */
109410   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
109411   yyStackEntry *yymsp;            /* The top of the parser's stack */
109412   int yysize;                     /* Amount to pop the stack */
109413   sqlcipher3ParserARG_FETCH;
109414   yymsp = &yypParser->yystack[yypParser->yyidx];
109415 #ifndef NDEBUG
109416   if( yyTraceFILE && yyruleno>=0 
109417         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
109418     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
109419       yyRuleName[yyruleno]);
109420   }
109421 #endif /* NDEBUG */
109422
109423   /* Silence complaints from purify about yygotominor being uninitialized
109424   ** in some cases when it is copied into the stack after the following
109425   ** switch.  yygotominor is uninitialized when a rule reduces that does
109426   ** not set the value of its left-hand side nonterminal.  Leaving the
109427   ** value of the nonterminal uninitialized is utterly harmless as long
109428   ** as the value is never used.  So really the only thing this code
109429   ** accomplishes is to quieten purify.  
109430   **
109431   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
109432   ** without this code, their parser segfaults.  I'm not sure what there
109433   ** parser is doing to make this happen.  This is the second bug report
109434   ** from wireshark this week.  Clearly they are stressing Lemon in ways
109435   ** that it has not been previously stressed...  (SQLite ticket #2172)
109436   */
109437   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
109438   yygotominor = yyzerominor;
109439
109440
109441   switch( yyruleno ){
109442   /* Beginning here are the reduction cases.  A typical example
109443   ** follows:
109444   **   case 0:
109445   **  #line <lineno> <grammarfile>
109446   **     { ... }           // User supplied code
109447   **  #line <lineno> <thisfile>
109448   **     break;
109449   */
109450       case 5: /* explain ::= */
109451 { sqlcipher3BeginParse(pParse, 0); }
109452         break;
109453       case 6: /* explain ::= EXPLAIN */
109454 { sqlcipher3BeginParse(pParse, 1); }
109455         break;
109456       case 7: /* explain ::= EXPLAIN QUERY PLAN */
109457 { sqlcipher3BeginParse(pParse, 2); }
109458         break;
109459       case 8: /* cmdx ::= cmd */
109460 { sqlcipher3FinishCoding(pParse); }
109461         break;
109462       case 9: /* cmd ::= BEGIN transtype trans_opt */
109463 {sqlcipher3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
109464         break;
109465       case 13: /* transtype ::= */
109466 {yygotominor.yy4 = TK_DEFERRED;}
109467         break;
109468       case 14: /* transtype ::= DEFERRED */
109469       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
109470       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
109471       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
109472       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
109473 {yygotominor.yy4 = yymsp[0].major;}
109474         break;
109475       case 17: /* cmd ::= COMMIT trans_opt */
109476       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
109477 {sqlcipher3CommitTransaction(pParse);}
109478         break;
109479       case 19: /* cmd ::= ROLLBACK trans_opt */
109480 {sqlcipher3RollbackTransaction(pParse);}
109481         break;
109482       case 22: /* cmd ::= SAVEPOINT nm */
109483 {
109484   sqlcipher3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
109485 }
109486         break;
109487       case 23: /* cmd ::= RELEASE savepoint_opt nm */
109488 {
109489   sqlcipher3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
109490 }
109491         break;
109492       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
109493 {
109494   sqlcipher3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
109495 }
109496         break;
109497       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
109498 {
109499    sqlcipher3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
109500 }
109501         break;
109502       case 27: /* createkw ::= CREATE */
109503 {
109504   pParse->db->lookaside.bEnabled = 0;
109505   yygotominor.yy0 = yymsp[0].minor.yy0;
109506 }
109507         break;
109508       case 28: /* ifnotexists ::= */
109509       case 31: /* temp ::= */ yytestcase(yyruleno==31);
109510       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
109511       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
109512       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
109513       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
109514       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
109515       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
109516       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
109517       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
109518       case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
109519       case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
109520 {yygotominor.yy4 = 0;}
109521         break;
109522       case 29: /* ifnotexists ::= IF NOT EXISTS */
109523       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
109524       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
109525       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
109526       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
109527       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
109528       case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
109529       case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
109530 {yygotominor.yy4 = 1;}
109531         break;
109532       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
109533 {
109534   sqlcipher3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
109535 }
109536         break;
109537       case 33: /* create_table_args ::= AS select */
109538 {
109539   sqlcipher3EndTable(pParse,0,0,yymsp[0].minor.yy387);
109540   sqlcipher3SelectDelete(pParse->db, yymsp[0].minor.yy387);
109541 }
109542         break;
109543       case 36: /* column ::= columnid type carglist */
109544 {
109545   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
109546   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
109547 }
109548         break;
109549       case 37: /* columnid ::= nm */
109550 {
109551   sqlcipher3AddColumn(pParse,&yymsp[0].minor.yy0);
109552   yygotominor.yy0 = yymsp[0].minor.yy0;
109553 }
109554         break;
109555       case 38: /* id ::= ID */
109556       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
109557       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
109558       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
109559       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
109560       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
109561       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
109562       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
109563       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
109564       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
109565       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
109566       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
109567       case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
109568       case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
109569       case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
109570       case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
109571       case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
109572       case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
109573       case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
109574       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
109575       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
109576       case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
109577 {yygotominor.yy0 = yymsp[0].minor.yy0;}
109578         break;
109579       case 45: /* type ::= typetoken */
109580 {sqlcipher3AddColumnType(pParse,&yymsp[0].minor.yy0);}
109581         break;
109582       case 47: /* typetoken ::= typename LP signed RP */
109583 {
109584   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
109585   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
109586 }
109587         break;
109588       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
109589 {
109590   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
109591   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
109592 }
109593         break;
109594       case 50: /* typename ::= typename ids */
109595 {yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
109596         break;
109597       case 57: /* ccons ::= DEFAULT term */
109598       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
109599 {sqlcipher3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
109600         break;
109601       case 58: /* ccons ::= DEFAULT LP expr RP */
109602 {sqlcipher3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
109603         break;
109604       case 60: /* ccons ::= DEFAULT MINUS term */
109605 {
109606   ExprSpan v;
109607   v.pExpr = sqlcipher3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
109608   v.zStart = yymsp[-1].minor.yy0.z;
109609   v.zEnd = yymsp[0].minor.yy118.zEnd;
109610   sqlcipher3AddDefaultValue(pParse,&v);
109611 }
109612         break;
109613       case 61: /* ccons ::= DEFAULT id */
109614 {
109615   ExprSpan v;
109616   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
109617   sqlcipher3AddDefaultValue(pParse,&v);
109618 }
109619         break;
109620       case 63: /* ccons ::= NOT NULL onconf */
109621 {sqlcipher3AddNotNull(pParse, yymsp[0].minor.yy4);}
109622         break;
109623       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
109624 {sqlcipher3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
109625         break;
109626       case 65: /* ccons ::= UNIQUE onconf */
109627 {sqlcipher3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
109628         break;
109629       case 66: /* ccons ::= CHECK LP expr RP */
109630 {sqlcipher3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
109631         break;
109632       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
109633 {sqlcipher3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
109634         break;
109635       case 68: /* ccons ::= defer_subclause */
109636 {sqlcipher3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
109637         break;
109638       case 69: /* ccons ::= COLLATE ids */
109639 {sqlcipher3AddCollateType(pParse, &yymsp[0].minor.yy0);}
109640         break;
109641       case 72: /* refargs ::= */
109642 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
109643         break;
109644       case 73: /* refargs ::= refargs refarg */
109645 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
109646         break;
109647       case 74: /* refarg ::= MATCH nm */
109648       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
109649 { yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
109650         break;
109651       case 76: /* refarg ::= ON DELETE refact */
109652 { yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
109653         break;
109654       case 77: /* refarg ::= ON UPDATE refact */
109655 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
109656         break;
109657       case 78: /* refact ::= SET NULL */
109658 { yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
109659         break;
109660       case 79: /* refact ::= SET DEFAULT */
109661 { yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
109662         break;
109663       case 80: /* refact ::= CASCADE */
109664 { yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
109665         break;
109666       case 81: /* refact ::= RESTRICT */
109667 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
109668         break;
109669       case 82: /* refact ::= NO ACTION */
109670 { yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
109671         break;
109672       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
109673       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
109674       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
109675       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
109676 {yygotominor.yy4 = yymsp[0].minor.yy4;}
109677         break;
109678       case 88: /* conslist_opt ::= */
109679 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
109680         break;
109681       case 89: /* conslist_opt ::= COMMA conslist */
109682 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
109683         break;
109684       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
109685 {sqlcipher3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
109686         break;
109687       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
109688 {sqlcipher3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
109689         break;
109690       case 96: /* tcons ::= CHECK LP expr RP onconf */
109691 {sqlcipher3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
109692         break;
109693       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
109694 {
109695     sqlcipher3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
109696     sqlcipher3DeferForeignKey(pParse, yymsp[0].minor.yy4);
109697 }
109698         break;
109699       case 100: /* onconf ::= */
109700 {yygotominor.yy4 = OE_Default;}
109701         break;
109702       case 102: /* orconf ::= */
109703 {yygotominor.yy210 = OE_Default;}
109704         break;
109705       case 103: /* orconf ::= OR resolvetype */
109706 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
109707         break;
109708       case 105: /* resolvetype ::= IGNORE */
109709 {yygotominor.yy4 = OE_Ignore;}
109710         break;
109711       case 106: /* resolvetype ::= REPLACE */
109712 {yygotominor.yy4 = OE_Replace;}
109713         break;
109714       case 107: /* cmd ::= DROP TABLE ifexists fullname */
109715 {
109716   sqlcipher3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
109717 }
109718         break;
109719       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
109720 {
109721   sqlcipher3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy387, yymsp[-6].minor.yy4, yymsp[-4].minor.yy4);
109722 }
109723         break;
109724       case 111: /* cmd ::= DROP VIEW ifexists fullname */
109725 {
109726   sqlcipher3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
109727 }
109728         break;
109729       case 112: /* cmd ::= select */
109730 {
109731   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
109732   sqlcipher3Select(pParse, yymsp[0].minor.yy387, &dest);
109733   sqlcipher3SelectDelete(pParse->db, yymsp[0].minor.yy387);
109734 }
109735         break;
109736       case 113: /* select ::= oneselect */
109737 {yygotominor.yy387 = yymsp[0].minor.yy387;}
109738         break;
109739       case 114: /* select ::= select multiselect_op oneselect */
109740 {
109741   if( yymsp[0].minor.yy387 ){
109742     yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
109743     yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
109744   }else{
109745     sqlcipher3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
109746   }
109747   yygotominor.yy387 = yymsp[0].minor.yy387;
109748 }
109749         break;
109750       case 116: /* multiselect_op ::= UNION ALL */
109751 {yygotominor.yy4 = TK_ALL;}
109752         break;
109753       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
109754 {
109755   yygotominor.yy387 = sqlcipher3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy259,yymsp[-4].minor.yy314,yymsp[-3].minor.yy322,yymsp[-2].minor.yy314,yymsp[-1].minor.yy322,yymsp[-7].minor.yy4,yymsp[0].minor.yy292.pLimit,yymsp[0].minor.yy292.pOffset);
109756 }
109757         break;
109758       case 122: /* sclp ::= selcollist COMMA */
109759       case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
109760 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
109761         break;
109762       case 123: /* sclp ::= */
109763       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
109764       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
109765       case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
109766       case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
109767 {yygotominor.yy322 = 0;}
109768         break;
109769       case 124: /* selcollist ::= sclp expr as */
109770 {
109771    yygotominor.yy322 = sqlcipher3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
109772    if( yymsp[0].minor.yy0.n>0 ) sqlcipher3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
109773    sqlcipher3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
109774 }
109775         break;
109776       case 125: /* selcollist ::= sclp STAR */
109777 {
109778   Expr *p = sqlcipher3Expr(pParse->db, TK_ALL, 0);
109779   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
109780 }
109781         break;
109782       case 126: /* selcollist ::= sclp nm DOT STAR */
109783 {
109784   Expr *pRight = sqlcipher3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
109785   Expr *pLeft = sqlcipher3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
109786   Expr *pDot = sqlcipher3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
109787   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
109788 }
109789         break;
109790       case 129: /* as ::= */
109791 {yygotominor.yy0.n = 0;}
109792         break;
109793       case 130: /* from ::= */
109794 {yygotominor.yy259 = sqlcipher3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
109795         break;
109796       case 131: /* from ::= FROM seltablist */
109797 {
109798   yygotominor.yy259 = yymsp[0].minor.yy259;
109799   sqlcipher3SrcListShiftJoinType(yygotominor.yy259);
109800 }
109801         break;
109802       case 132: /* stl_prefix ::= seltablist joinop */
109803 {
109804    yygotominor.yy259 = yymsp[-1].minor.yy259;
109805    if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
109806 }
109807         break;
109808       case 133: /* stl_prefix ::= */
109809 {yygotominor.yy259 = 0;}
109810         break;
109811       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
109812 {
109813   yygotominor.yy259 = sqlcipher3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
109814   sqlcipher3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
109815 }
109816         break;
109817       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
109818 {
109819     yygotominor.yy259 = sqlcipher3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
109820   }
109821         break;
109822       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
109823 {
109824     if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
109825       yygotominor.yy259 = yymsp[-4].minor.yy259;
109826     }else{
109827       Select *pSubquery;
109828       sqlcipher3SrcListShiftJoinType(yymsp[-4].minor.yy259);
109829       pSubquery = sqlcipher3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
109830       yygotominor.yy259 = sqlcipher3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
109831     }
109832   }
109833         break;
109834       case 137: /* dbnm ::= */
109835       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
109836 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
109837         break;
109838       case 139: /* fullname ::= nm dbnm */
109839 {yygotominor.yy259 = sqlcipher3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
109840         break;
109841       case 140: /* joinop ::= COMMA|JOIN */
109842 { yygotominor.yy4 = JT_INNER; }
109843         break;
109844       case 141: /* joinop ::= JOIN_KW JOIN */
109845 { yygotominor.yy4 = sqlcipher3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
109846         break;
109847       case 142: /* joinop ::= JOIN_KW nm JOIN */
109848 { yygotominor.yy4 = sqlcipher3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
109849         break;
109850       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
109851 { yygotominor.yy4 = sqlcipher3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
109852         break;
109853       case 144: /* on_opt ::= ON expr */
109854       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
109855       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
109856       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
109857       case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
109858       case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
109859 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
109860         break;
109861       case 145: /* on_opt ::= */
109862       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
109863       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
109864       case 236: /* case_else ::= */ yytestcase(yyruleno==236);
109865       case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
109866 {yygotominor.yy314 = 0;}
109867         break;
109868       case 148: /* indexed_opt ::= NOT INDEXED */
109869 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
109870         break;
109871       case 149: /* using_opt ::= USING LP inscollist RP */
109872       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
109873 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
109874         break;
109875       case 150: /* using_opt ::= */
109876       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
109877 {yygotominor.yy384 = 0;}
109878         break;
109879       case 152: /* orderby_opt ::= ORDER BY sortlist */
109880       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
109881       case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
109882 {yygotominor.yy322 = yymsp[0].minor.yy322;}
109883         break;
109884       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
109885 {
109886   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
109887   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
109888 }
109889         break;
109890       case 154: /* sortlist ::= sortitem sortorder */
109891 {
109892   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
109893   if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
109894 }
109895         break;
109896       case 156: /* sortorder ::= ASC */
109897       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
109898 {yygotominor.yy4 = SQLCIPHER_SO_ASC;}
109899         break;
109900       case 157: /* sortorder ::= DESC */
109901 {yygotominor.yy4 = SQLCIPHER_SO_DESC;}
109902         break;
109903       case 163: /* limit_opt ::= */
109904 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
109905         break;
109906       case 164: /* limit_opt ::= LIMIT expr */
109907 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
109908         break;
109909       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
109910 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
109911         break;
109912       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
109913 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
109914         break;
109915       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
109916 {
109917   sqlcipher3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
109918   sqlcipher3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
109919 }
109920         break;
109921       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
109922 {
109923   sqlcipher3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
109924   sqlcipher3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list"); 
109925   sqlcipher3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
109926 }
109927         break;
109928       case 171: /* setlist ::= setlist COMMA nm EQ expr */
109929 {
109930   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
109931   sqlcipher3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
109932 }
109933         break;
109934       case 172: /* setlist ::= nm EQ expr */
109935 {
109936   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
109937   sqlcipher3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
109938 }
109939         break;
109940       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
109941 {sqlcipher3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
109942         break;
109943       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
109944 {sqlcipher3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
109945         break;
109946       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
109947 {sqlcipher3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
109948         break;
109949       case 176: /* insert_cmd ::= INSERT orconf */
109950 {yygotominor.yy210 = yymsp[0].minor.yy210;}
109951         break;
109952       case 177: /* insert_cmd ::= REPLACE */
109953 {yygotominor.yy210 = OE_Replace;}
109954         break;
109955       case 178: /* itemlist ::= itemlist COMMA expr */
109956       case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
109957 {yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
109958         break;
109959       case 179: /* itemlist ::= expr */
109960       case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
109961 {yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
109962         break;
109963       case 182: /* inscollist ::= inscollist COMMA nm */
109964 {yygotominor.yy384 = sqlcipher3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
109965         break;
109966       case 183: /* inscollist ::= nm */
109967 {yygotominor.yy384 = sqlcipher3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
109968         break;
109969       case 184: /* expr ::= term */
109970 {yygotominor.yy118 = yymsp[0].minor.yy118;}
109971         break;
109972       case 185: /* expr ::= LP expr RP */
109973 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
109974         break;
109975       case 186: /* term ::= NULL */
109976       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
109977       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
109978 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
109979         break;
109980       case 187: /* expr ::= id */
109981       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
109982 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
109983         break;
109984       case 189: /* expr ::= nm DOT nm */
109985 {
109986   Expr *temp1 = sqlcipher3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
109987   Expr *temp2 = sqlcipher3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
109988   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_DOT, temp1, temp2, 0);
109989   spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
109990 }
109991         break;
109992       case 190: /* expr ::= nm DOT nm DOT nm */
109993 {
109994   Expr *temp1 = sqlcipher3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
109995   Expr *temp2 = sqlcipher3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
109996   Expr *temp3 = sqlcipher3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
109997   Expr *temp4 = sqlcipher3PExpr(pParse, TK_DOT, temp2, temp3, 0);
109998   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_DOT, temp1, temp4, 0);
109999   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
110000 }
110001         break;
110002       case 193: /* expr ::= REGISTER */
110003 {
110004   /* When doing a nested parse, one can include terms in an expression
110005   ** that look like this:   #1 #2 ...  These terms refer to registers
110006   ** in the virtual machine.  #N is the N-th register. */
110007   if( pParse->nested==0 ){
110008     sqlcipher3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
110009     yygotominor.yy118.pExpr = 0;
110010   }else{
110011     yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
110012     if( yygotominor.yy118.pExpr ) sqlcipher3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
110013   }
110014   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110015 }
110016         break;
110017       case 194: /* expr ::= VARIABLE */
110018 {
110019   spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
110020   sqlcipher3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
110021   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110022 }
110023         break;
110024       case 195: /* expr ::= expr COLLATE ids */
110025 {
110026   yygotominor.yy118.pExpr = sqlcipher3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
110027   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
110028   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110029 }
110030         break;
110031       case 196: /* expr ::= CAST LP expr AS typetoken RP */
110032 {
110033   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
110034   spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
110035 }
110036         break;
110037       case 197: /* expr ::= ID LP distinct exprlist RP */
110038 {
110039   if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLCIPHER_LIMIT_FUNCTION_ARG] ){
110040     sqlcipher3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
110041   }
110042   yygotominor.yy118.pExpr = sqlcipher3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
110043   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
110044   if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
110045     yygotominor.yy118.pExpr->flags |= EP_Distinct;
110046   }
110047 }
110048         break;
110049       case 198: /* expr ::= ID LP STAR RP */
110050 {
110051   yygotominor.yy118.pExpr = sqlcipher3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
110052   spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
110053 }
110054         break;
110055       case 199: /* term ::= CTIME_KW */
110056 {
110057   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
110058   ** treated as functions that return constants */
110059   yygotominor.yy118.pExpr = sqlcipher3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
110060   if( yygotominor.yy118.pExpr ){
110061     yygotominor.yy118.pExpr->op = TK_CONST_FUNC;  
110062   }
110063   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110064 }
110065         break;
110066       case 200: /* expr ::= expr AND expr */
110067       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
110068       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
110069       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
110070       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
110071       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
110072       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
110073       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
110074 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
110075         break;
110076       case 208: /* likeop ::= LIKE_KW */
110077       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
110078 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
110079         break;
110080       case 209: /* likeop ::= NOT LIKE_KW */
110081       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
110082 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
110083         break;
110084       case 212: /* expr ::= expr likeop expr */
110085 {
110086   ExprList *pList;
110087   pList = sqlcipher3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
110088   pList = sqlcipher3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
110089   yygotominor.yy118.pExpr = sqlcipher3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
110090   if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
110091   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
110092   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
110093   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
110094 }
110095         break;
110096       case 213: /* expr ::= expr likeop expr ESCAPE expr */
110097 {
110098   ExprList *pList;
110099   pList = sqlcipher3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
110100   pList = sqlcipher3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
110101   pList = sqlcipher3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
110102   yygotominor.yy118.pExpr = sqlcipher3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
110103   if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
110104   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
110105   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
110106   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
110107 }
110108         break;
110109       case 214: /* expr ::= expr ISNULL|NOTNULL */
110110 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
110111         break;
110112       case 215: /* expr ::= expr NOT NULL */
110113 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
110114         break;
110115       case 216: /* expr ::= expr IS expr */
110116 {
110117   spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
110118   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
110119 }
110120         break;
110121       case 217: /* expr ::= expr IS NOT expr */
110122 {
110123   spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
110124   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
110125 }
110126         break;
110127       case 218: /* expr ::= NOT expr */
110128       case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
110129 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
110130         break;
110131       case 220: /* expr ::= MINUS expr */
110132 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
110133         break;
110134       case 221: /* expr ::= PLUS expr */
110135 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
110136         break;
110137       case 224: /* expr ::= expr between_op expr AND expr */
110138 {
110139   ExprList *pList = sqlcipher3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
110140   pList = sqlcipher3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
110141   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
110142   if( yygotominor.yy118.pExpr ){
110143     yygotominor.yy118.pExpr->x.pList = pList;
110144   }else{
110145     sqlcipher3ExprListDelete(pParse->db, pList);
110146   } 
110147   if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
110148   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
110149   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
110150 }
110151         break;
110152       case 227: /* expr ::= expr in_op LP exprlist RP */
110153 {
110154     if( yymsp[-1].minor.yy322==0 ){
110155       /* Expressions of the form
110156       **
110157       **      expr1 IN ()
110158       **      expr1 NOT IN ()
110159       **
110160       ** simplify to constants 0 (false) and 1 (true), respectively,
110161       ** regardless of the value of expr1.
110162       */
110163       yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_INTEGER, 0, 0, &sqlcipher3IntTokens[yymsp[-3].minor.yy4]);
110164       sqlcipher3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
110165     }else{
110166       yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
110167       if( yygotominor.yy118.pExpr ){
110168         yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
110169         sqlcipher3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
110170       }else{
110171         sqlcipher3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
110172       }
110173       if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
110174     }
110175     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
110176     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110177   }
110178         break;
110179       case 228: /* expr ::= LP select RP */
110180 {
110181     yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_SELECT, 0, 0, 0);
110182     if( yygotominor.yy118.pExpr ){
110183       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
110184       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
110185       sqlcipher3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
110186     }else{
110187       sqlcipher3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
110188     }
110189     yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
110190     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110191   }
110192         break;
110193       case 229: /* expr ::= expr in_op LP select RP */
110194 {
110195     yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
110196     if( yygotominor.yy118.pExpr ){
110197       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
110198       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
110199       sqlcipher3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
110200     }else{
110201       sqlcipher3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
110202     }
110203     if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
110204     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
110205     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110206   }
110207         break;
110208       case 230: /* expr ::= expr in_op nm dbnm */
110209 {
110210     SrcList *pSrc = sqlcipher3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
110211     yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
110212     if( yygotominor.yy118.pExpr ){
110213       yygotominor.yy118.pExpr->x.pSelect = sqlcipher3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
110214       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
110215       sqlcipher3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
110216     }else{
110217       sqlcipher3SrcListDelete(pParse->db, pSrc);
110218     }
110219     if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
110220     yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
110221     yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
110222   }
110223         break;
110224       case 231: /* expr ::= EXISTS LP select RP */
110225 {
110226     Expr *p = yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_EXISTS, 0, 0, 0);
110227     if( p ){
110228       p->x.pSelect = yymsp[-1].minor.yy387;
110229       ExprSetProperty(p, EP_xIsSelect);
110230       sqlcipher3ExprSetHeight(pParse, p);
110231     }else{
110232       sqlcipher3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
110233     }
110234     yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
110235     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110236   }
110237         break;
110238       case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
110239 {
110240   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
110241   if( yygotominor.yy118.pExpr ){
110242     yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
110243     sqlcipher3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
110244   }else{
110245     sqlcipher3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
110246   }
110247   yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
110248   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110249 }
110250         break;
110251       case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
110252 {
110253   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
110254   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
110255 }
110256         break;
110257       case 234: /* case_exprlist ::= WHEN expr THEN expr */
110258 {
110259   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
110260   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
110261 }
110262         break;
110263       case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
110264 {
110265   sqlcipher3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
110266                      sqlcipher3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
110267                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLCIPHER_SO_ASC, yymsp[-7].minor.yy4);
110268 }
110269         break;
110270       case 244: /* uniqueflag ::= UNIQUE */
110271       case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
110272 {yygotominor.yy4 = OE_Abort;}
110273         break;
110274       case 245: /* uniqueflag ::= */
110275 {yygotominor.yy4 = OE_None;}
110276         break;
110277       case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
110278 {
110279   Expr *p = 0;
110280   if( yymsp[-1].minor.yy0.n>0 ){
110281     p = sqlcipher3Expr(pParse->db, TK_COLUMN, 0);
110282     sqlcipher3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
110283   }
110284   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
110285   sqlcipher3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
110286   sqlcipher3ExprListCheckLength(pParse, yygotominor.yy322, "index");
110287   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
110288 }
110289         break;
110290       case 249: /* idxlist ::= nm collate sortorder */
110291 {
110292   Expr *p = 0;
110293   if( yymsp[-1].minor.yy0.n>0 ){
110294     p = sqlcipher3PExpr(pParse, TK_COLUMN, 0, 0, 0);
110295     sqlcipher3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
110296   }
110297   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,0, p);
110298   sqlcipher3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
110299   sqlcipher3ExprListCheckLength(pParse, yygotominor.yy322, "index");
110300   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
110301 }
110302         break;
110303       case 250: /* collate ::= */
110304 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
110305         break;
110306       case 252: /* cmd ::= DROP INDEX ifexists fullname */
110307 {sqlcipher3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
110308         break;
110309       case 253: /* cmd ::= VACUUM */
110310       case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
110311 {sqlcipher3Vacuum(pParse);}
110312         break;
110313       case 255: /* cmd ::= PRAGMA nm dbnm */
110314 {sqlcipher3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
110315         break;
110316       case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
110317 {sqlcipher3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
110318         break;
110319       case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
110320 {sqlcipher3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
110321         break;
110322       case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
110323 {sqlcipher3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
110324         break;
110325       case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
110326 {sqlcipher3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
110327         break;
110328       case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
110329 {
110330   Token all;
110331   all.z = yymsp[-3].minor.yy0.z;
110332   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
110333   sqlcipher3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
110334 }
110335         break;
110336       case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
110337 {
110338   sqlcipher3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4);
110339   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
110340 }
110341         break;
110342       case 272: /* trigger_time ::= BEFORE */
110343       case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
110344 { yygotominor.yy4 = TK_BEFORE; }
110345         break;
110346       case 273: /* trigger_time ::= AFTER */
110347 { yygotominor.yy4 = TK_AFTER;  }
110348         break;
110349       case 274: /* trigger_time ::= INSTEAD OF */
110350 { yygotominor.yy4 = TK_INSTEAD;}
110351         break;
110352       case 276: /* trigger_event ::= DELETE|INSERT */
110353       case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
110354 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
110355         break;
110356       case 278: /* trigger_event ::= UPDATE OF inscollist */
110357 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
110358         break;
110359       case 281: /* when_clause ::= */
110360       case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
110361 { yygotominor.yy314 = 0; }
110362         break;
110363       case 282: /* when_clause ::= WHEN expr */
110364       case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
110365 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
110366         break;
110367       case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
110368 {
110369   assert( yymsp[-2].minor.yy203!=0 );
110370   yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
110371   yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
110372   yygotominor.yy203 = yymsp[-2].minor.yy203;
110373 }
110374         break;
110375       case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
110376
110377   assert( yymsp[-1].minor.yy203!=0 );
110378   yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
110379   yygotominor.yy203 = yymsp[-1].minor.yy203;
110380 }
110381         break;
110382       case 286: /* trnm ::= nm DOT nm */
110383 {
110384   yygotominor.yy0 = yymsp[0].minor.yy0;
110385   sqlcipher3ErrorMsg(pParse, 
110386         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
110387         "statements within triggers");
110388 }
110389         break;
110390       case 288: /* tridxby ::= INDEXED BY nm */
110391 {
110392   sqlcipher3ErrorMsg(pParse,
110393         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
110394         "within triggers");
110395 }
110396         break;
110397       case 289: /* tridxby ::= NOT INDEXED */
110398 {
110399   sqlcipher3ErrorMsg(pParse,
110400         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
110401         "within triggers");
110402 }
110403         break;
110404       case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
110405 { yygotominor.yy203 = sqlcipher3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
110406         break;
110407       case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
110408 {yygotominor.yy203 = sqlcipher3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
110409         break;
110410       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
110411 {yygotominor.yy203 = sqlcipher3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
110412         break;
110413       case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
110414 {yygotominor.yy203 = sqlcipher3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
110415         break;
110416       case 294: /* trigger_cmd ::= select */
110417 {yygotominor.yy203 = sqlcipher3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
110418         break;
110419       case 295: /* expr ::= RAISE LP IGNORE RP */
110420 {
110421   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_RAISE, 0, 0, 0); 
110422   if( yygotominor.yy118.pExpr ){
110423     yygotominor.yy118.pExpr->affinity = OE_Ignore;
110424   }
110425   yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
110426   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110427 }
110428         break;
110429       case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
110430 {
110431   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
110432   if( yygotominor.yy118.pExpr ) {
110433     yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
110434   }
110435   yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
110436   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110437 }
110438         break;
110439       case 297: /* raisetype ::= ROLLBACK */
110440 {yygotominor.yy4 = OE_Rollback;}
110441         break;
110442       case 299: /* raisetype ::= FAIL */
110443 {yygotominor.yy4 = OE_Fail;}
110444         break;
110445       case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
110446 {
110447   sqlcipher3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
110448 }
110449         break;
110450       case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
110451 {
110452   sqlcipher3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
110453 }
110454         break;
110455       case 302: /* cmd ::= DETACH database_kw_opt expr */
110456 {
110457   sqlcipher3Detach(pParse, yymsp[0].minor.yy118.pExpr);
110458 }
110459         break;
110460       case 307: /* cmd ::= REINDEX */
110461 {sqlcipher3Reindex(pParse, 0, 0);}
110462         break;
110463       case 308: /* cmd ::= REINDEX nm dbnm */
110464 {sqlcipher3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
110465         break;
110466       case 309: /* cmd ::= ANALYZE */
110467 {sqlcipher3Analyze(pParse, 0, 0);}
110468         break;
110469       case 310: /* cmd ::= ANALYZE nm dbnm */
110470 {sqlcipher3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
110471         break;
110472       case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
110473 {
110474   sqlcipher3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
110475 }
110476         break;
110477       case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
110478 {
110479   sqlcipher3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
110480 }
110481         break;
110482       case 313: /* add_column_fullname ::= fullname */
110483 {
110484   pParse->db->lookaside.bEnabled = 0;
110485   sqlcipher3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
110486 }
110487         break;
110488       case 316: /* cmd ::= create_vtab */
110489 {sqlcipher3VtabFinishParse(pParse,0);}
110490         break;
110491       case 317: /* cmd ::= create_vtab LP vtabarglist RP */
110492 {sqlcipher3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
110493         break;
110494       case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
110495 {
110496     sqlcipher3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
110497 }
110498         break;
110499       case 321: /* vtabarg ::= */
110500 {sqlcipher3VtabArgInit(pParse);}
110501         break;
110502       case 323: /* vtabargtoken ::= ANY */
110503       case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
110504       case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
110505 {sqlcipher3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
110506         break;
110507       default:
110508       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
110509       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
110510       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
110511       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
110512       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
110513       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
110514       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
110515       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
110516       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
110517       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
110518       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
110519       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
110520       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
110521       /* (44) type ::= */ yytestcase(yyruleno==44);
110522       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
110523       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
110524       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
110525       /* (54) carglist ::= */ yytestcase(yyruleno==54);
110526       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
110527       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
110528       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
110529       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
110530       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
110531       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
110532       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
110533       /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
110534       /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
110535       /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
110536       /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
110537       /* (287) tridxby ::= */ yytestcase(yyruleno==287);
110538       /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
110539       /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
110540       /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
110541       /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
110542       /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
110543       /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
110544       /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
110545       /* (326) anylist ::= */ yytestcase(yyruleno==326);
110546       /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
110547       /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
110548         break;
110549   };
110550   yygoto = yyRuleInfo[yyruleno].lhs;
110551   yysize = yyRuleInfo[yyruleno].nrhs;
110552   yypParser->yyidx -= yysize;
110553   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
110554   if( yyact < YYNSTATE ){
110555 #ifdef NDEBUG
110556     /* If we are not debugging and the reduce action popped at least
110557     ** one element off the stack, then we can push the new element back
110558     ** onto the stack here, and skip the stack overflow test in yy_shift().
110559     ** That gives a significant speed improvement. */
110560     if( yysize ){
110561       yypParser->yyidx++;
110562       yymsp -= yysize-1;
110563       yymsp->stateno = (YYACTIONTYPE)yyact;
110564       yymsp->major = (YYCODETYPE)yygoto;
110565       yymsp->minor = yygotominor;
110566     }else
110567 #endif
110568     {
110569       yy_shift(yypParser,yyact,yygoto,&yygotominor);
110570     }
110571   }else{
110572     assert( yyact == YYNSTATE + YYNRULE + 1 );
110573     yy_accept(yypParser);
110574   }
110575 }
110576
110577 /*
110578 ** The following code executes when the parse fails
110579 */
110580 #ifndef YYNOERRORRECOVERY
110581 static void yy_parse_failed(
110582   yyParser *yypParser           /* The parser */
110583 ){
110584   sqlcipher3ParserARG_FETCH;
110585 #ifndef NDEBUG
110586   if( yyTraceFILE ){
110587     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
110588   }
110589 #endif
110590   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
110591   /* Here code is inserted which will be executed whenever the
110592   ** parser fails */
110593   sqlcipher3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
110594 }
110595 #endif /* YYNOERRORRECOVERY */
110596
110597 /*
110598 ** The following code executes when a syntax error first occurs.
110599 */
110600 static void yy_syntax_error(
110601   yyParser *yypParser,           /* The parser */
110602   int yymajor,                   /* The major type of the error token */
110603   YYMINORTYPE yyminor            /* The minor type of the error token */
110604 ){
110605   sqlcipher3ParserARG_FETCH;
110606 #define TOKEN (yyminor.yy0)
110607
110608   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
110609   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
110610   sqlcipher3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
110611   pParse->parseError = 1;
110612   sqlcipher3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
110613 }
110614
110615 /*
110616 ** The following is executed when the parser accepts
110617 */
110618 static void yy_accept(
110619   yyParser *yypParser           /* The parser */
110620 ){
110621   sqlcipher3ParserARG_FETCH;
110622 #ifndef NDEBUG
110623   if( yyTraceFILE ){
110624     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
110625   }
110626 #endif
110627   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
110628   /* Here code is inserted which will be executed whenever the
110629   ** parser accepts */
110630   sqlcipher3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
110631 }
110632
110633 /* The main parser program.
110634 ** The first argument is a pointer to a structure obtained from
110635 ** "sqlcipher3ParserAlloc" which describes the current state of the parser.
110636 ** The second argument is the major token number.  The third is
110637 ** the minor token.  The fourth optional argument is whatever the
110638 ** user wants (and specified in the grammar) and is available for
110639 ** use by the action routines.
110640 **
110641 ** Inputs:
110642 ** <ul>
110643 ** <li> A pointer to the parser (an opaque structure.)
110644 ** <li> The major token number.
110645 ** <li> The minor token number.
110646 ** <li> An option argument of a grammar-specified type.
110647 ** </ul>
110648 **
110649 ** Outputs:
110650 ** None.
110651 */
110652 SQLCIPHER_PRIVATE void sqlcipher3Parser(
110653   void *yyp,                   /* The parser */
110654   int yymajor,                 /* The major token code number */
110655   sqlcipher3ParserTOKENTYPE yyminor       /* The value for the token */
110656   sqlcipher3ParserARG_PDECL               /* Optional %extra_argument parameter */
110657 ){
110658   YYMINORTYPE yyminorunion;
110659   int yyact;            /* The parser action. */
110660 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
110661   int yyendofinput;     /* True if we are at the end of input */
110662 #endif
110663 #ifdef YYERRORSYMBOL
110664   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
110665 #endif
110666   yyParser *yypParser;  /* The parser */
110667
110668   /* (re)initialize the parser, if necessary */
110669   yypParser = (yyParser*)yyp;
110670   if( yypParser->yyidx<0 ){
110671 #if YYSTACKDEPTH<=0
110672     if( yypParser->yystksz <=0 ){
110673       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
110674       yyminorunion = yyzerominor;
110675       yyStackOverflow(yypParser, &yyminorunion);
110676       return;
110677     }
110678 #endif
110679     yypParser->yyidx = 0;
110680     yypParser->yyerrcnt = -1;
110681     yypParser->yystack[0].stateno = 0;
110682     yypParser->yystack[0].major = 0;
110683   }
110684   yyminorunion.yy0 = yyminor;
110685 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
110686   yyendofinput = (yymajor==0);
110687 #endif
110688   sqlcipher3ParserARG_STORE;
110689
110690 #ifndef NDEBUG
110691   if( yyTraceFILE ){
110692     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
110693   }
110694 #endif
110695
110696   do{
110697     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
110698     if( yyact<YYNSTATE ){
110699       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
110700       yypParser->yyerrcnt--;
110701       yymajor = YYNOCODE;
110702     }else if( yyact < YYNSTATE + YYNRULE ){
110703       yy_reduce(yypParser,yyact-YYNSTATE);
110704     }else{
110705       assert( yyact == YY_ERROR_ACTION );
110706 #ifdef YYERRORSYMBOL
110707       int yymx;
110708 #endif
110709 #ifndef NDEBUG
110710       if( yyTraceFILE ){
110711         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
110712       }
110713 #endif
110714 #ifdef YYERRORSYMBOL
110715       /* A syntax error has occurred.
110716       ** The response to an error depends upon whether or not the
110717       ** grammar defines an error token "ERROR".  
110718       **
110719       ** This is what we do if the grammar does define ERROR:
110720       **
110721       **  * Call the %syntax_error function.
110722       **
110723       **  * Begin popping the stack until we enter a state where
110724       **    it is legal to shift the error symbol, then shift
110725       **    the error symbol.
110726       **
110727       **  * Set the error count to three.
110728       **
110729       **  * Begin accepting and shifting new tokens.  No new error
110730       **    processing will occur until three tokens have been
110731       **    shifted successfully.
110732       **
110733       */
110734       if( yypParser->yyerrcnt<0 ){
110735         yy_syntax_error(yypParser,yymajor,yyminorunion);
110736       }
110737       yymx = yypParser->yystack[yypParser->yyidx].major;
110738       if( yymx==YYERRORSYMBOL || yyerrorhit ){
110739 #ifndef NDEBUG
110740         if( yyTraceFILE ){
110741           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
110742              yyTracePrompt,yyTokenName[yymajor]);
110743         }
110744 #endif
110745         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
110746         yymajor = YYNOCODE;
110747       }else{
110748          while(
110749           yypParser->yyidx >= 0 &&
110750           yymx != YYERRORSYMBOL &&
110751           (yyact = yy_find_reduce_action(
110752                         yypParser->yystack[yypParser->yyidx].stateno,
110753                         YYERRORSYMBOL)) >= YYNSTATE
110754         ){
110755           yy_pop_parser_stack(yypParser);
110756         }
110757         if( yypParser->yyidx < 0 || yymajor==0 ){
110758           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
110759           yy_parse_failed(yypParser);
110760           yymajor = YYNOCODE;
110761         }else if( yymx!=YYERRORSYMBOL ){
110762           YYMINORTYPE u2;
110763           u2.YYERRSYMDT = 0;
110764           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
110765         }
110766       }
110767       yypParser->yyerrcnt = 3;
110768       yyerrorhit = 1;
110769 #elif defined(YYNOERRORRECOVERY)
110770       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
110771       ** do any kind of error recovery.  Instead, simply invoke the syntax
110772       ** error routine and continue going as if nothing had happened.
110773       **
110774       ** Applications can set this macro (for example inside %include) if
110775       ** they intend to abandon the parse upon the first syntax error seen.
110776       */
110777       yy_syntax_error(yypParser,yymajor,yyminorunion);
110778       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
110779       yymajor = YYNOCODE;
110780       
110781 #else  /* YYERRORSYMBOL is not defined */
110782       /* This is what we do if the grammar does not define ERROR:
110783       **
110784       **  * Report an error message, and throw away the input token.
110785       **
110786       **  * If the input token is $, then fail the parse.
110787       **
110788       ** As before, subsequent error messages are suppressed until
110789       ** three input tokens have been successfully shifted.
110790       */
110791       if( yypParser->yyerrcnt<=0 ){
110792         yy_syntax_error(yypParser,yymajor,yyminorunion);
110793       }
110794       yypParser->yyerrcnt = 3;
110795       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
110796       if( yyendofinput ){
110797         yy_parse_failed(yypParser);
110798       }
110799       yymajor = YYNOCODE;
110800 #endif
110801     }
110802   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
110803   return;
110804 }
110805
110806 /************** End of parse.c ***********************************************/
110807 /************** Begin file tokenize.c ****************************************/
110808 /*
110809 ** 2001 September 15
110810 **
110811 ** The author disclaims copyright to this source code.  In place of
110812 ** a legal notice, here is a blessing:
110813 **
110814 **    May you do good and not evil.
110815 **    May you find forgiveness for yourself and forgive others.
110816 **    May you share freely, never taking more than you give.
110817 **
110818 *************************************************************************
110819 ** An tokenizer for SQL
110820 **
110821 ** This file contains C code that splits an SQL input string up into
110822 ** individual tokens and sends those tokens one-by-one over to the
110823 ** parser for analysis.
110824 */
110825 /* #include <stdlib.h> */
110826
110827 /*
110828 ** The charMap() macro maps alphabetic characters into their
110829 ** lower-case ASCII equivalent.  On ASCII machines, this is just
110830 ** an upper-to-lower case map.  On EBCDIC machines we also need
110831 ** to adjust the encoding.  Only alphabetic characters and underscores
110832 ** need to be translated.
110833 */
110834 #ifdef SQLCIPHER_ASCII
110835 # define charMap(X) sqlcipher3UpperToLower[(unsigned char)X]
110836 #endif
110837 #ifdef SQLCIPHER_EBCDIC
110838 # define charMap(X) ebcdicToAscii[(unsigned char)X]
110839 const unsigned char ebcdicToAscii[] = {
110840 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
110841    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
110842    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
110843    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
110844    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
110845    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
110846    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
110847    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
110848    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
110849    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
110850    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
110851    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
110852    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
110853    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
110854    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
110855    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
110856    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
110857 };
110858 #endif
110859
110860 /*
110861 ** The sqlcipher3KeywordCode function looks up an identifier to determine if
110862 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
110863 ** returned.  If the input is not a keyword, TK_ID is returned.
110864 **
110865 ** The implementation of this routine was generated by a program,
110866 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
110867 ** The output of the mkkeywordhash.c program is written into a file
110868 ** named keywordhash.h and then included into this source file by
110869 ** the #include below.
110870 */
110871 /************** Include keywordhash.h in the middle of tokenize.c ************/
110872 /************** Begin file keywordhash.h *************************************/
110873 /***** This file contains automatically generated code ******
110874 **
110875 ** The code in this file has been automatically generated by
110876 **
110877 **   sqlcipher/tool/mkkeywordhash.c
110878 **
110879 ** The code in this file implements a function that determines whether
110880 ** or not a given identifier is really an SQL keyword.  The same thing
110881 ** might be implemented more directly using a hand-written hash table.
110882 ** But by using this automatically generated code, the size of the code
110883 ** is substantially reduced.  This is important for embedded applications
110884 ** on platforms with limited memory.
110885 */
110886 /* Hash score: 175 */
110887 static int keywordCode(const char *z, int n){
110888   /* zText[] encodes 811 bytes of keywords in 541 bytes */
110889   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
110890   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
110891   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
110892   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
110893   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
110894   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
110895   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
110896   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
110897   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
110898   /*   INITIALLY                                                          */
110899   static const char zText[540] = {
110900     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
110901     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
110902     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
110903     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
110904     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
110905     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
110906     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
110907     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
110908     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
110909     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
110910     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
110911     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
110912     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
110913     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
110914     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
110915     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
110916     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
110917     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
110918     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
110919     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
110920     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
110921     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
110922     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
110923     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
110924     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
110925     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
110926     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
110927     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
110928     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
110929     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
110930   };
110931   static const unsigned char aHash[127] = {
110932       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
110933       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
110934      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
110935        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
110936        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
110937       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
110938       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
110939       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
110940       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
110941       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
110942   };
110943   static const unsigned char aNext[121] = {
110944        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
110945        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
110946        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
110947        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
110948        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
110949       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
110950       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
110951        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
110952      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
110953       35,  64,   0,   0,
110954   };
110955   static const unsigned char aLen[121] = {
110956        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
110957        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
110958       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
110959        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
110960        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
110961        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
110962        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
110963        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
110964        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
110965        6,   4,   9,   3,
110966   };
110967   static const unsigned short int aOffset[121] = {
110968        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
110969       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
110970       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
110971      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
110972      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
110973      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
110974      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
110975      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
110976      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
110977      521, 527, 531, 536,
110978   };
110979   static const unsigned char aCode[121] = {
110980     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
110981     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
110982     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
110983     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
110984     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
110985     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
110986     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
110987     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
110988     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
110989     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
110990     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
110991     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
110992     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
110993     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
110994     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
110995     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
110996     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
110997     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
110998     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
110999     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
111000     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
111001     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
111002     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
111003     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
111004     TK_ALL,        
111005   };
111006   int h, i;
111007   if( n<2 ) return TK_ID;
111008   h = ((charMap(z[0])*4) ^
111009       (charMap(z[n-1])*3) ^
111010       n) % 127;
111011   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
111012     if( aLen[i]==n && sqlcipher3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
111013       testcase( i==0 ); /* REINDEX */
111014       testcase( i==1 ); /* INDEXED */
111015       testcase( i==2 ); /* INDEX */
111016       testcase( i==3 ); /* DESC */
111017       testcase( i==4 ); /* ESCAPE */
111018       testcase( i==5 ); /* EACH */
111019       testcase( i==6 ); /* CHECK */
111020       testcase( i==7 ); /* KEY */
111021       testcase( i==8 ); /* BEFORE */
111022       testcase( i==9 ); /* FOREIGN */
111023       testcase( i==10 ); /* FOR */
111024       testcase( i==11 ); /* IGNORE */
111025       testcase( i==12 ); /* REGEXP */
111026       testcase( i==13 ); /* EXPLAIN */
111027       testcase( i==14 ); /* INSTEAD */
111028       testcase( i==15 ); /* ADD */
111029       testcase( i==16 ); /* DATABASE */
111030       testcase( i==17 ); /* AS */
111031       testcase( i==18 ); /* SELECT */
111032       testcase( i==19 ); /* TABLE */
111033       testcase( i==20 ); /* LEFT */
111034       testcase( i==21 ); /* THEN */
111035       testcase( i==22 ); /* END */
111036       testcase( i==23 ); /* DEFERRABLE */
111037       testcase( i==24 ); /* ELSE */
111038       testcase( i==25 ); /* EXCEPT */
111039       testcase( i==26 ); /* TRANSACTION */
111040       testcase( i==27 ); /* ACTION */
111041       testcase( i==28 ); /* ON */
111042       testcase( i==29 ); /* NATURAL */
111043       testcase( i==30 ); /* ALTER */
111044       testcase( i==31 ); /* RAISE */
111045       testcase( i==32 ); /* EXCLUSIVE */
111046       testcase( i==33 ); /* EXISTS */
111047       testcase( i==34 ); /* SAVEPOINT */
111048       testcase( i==35 ); /* INTERSECT */
111049       testcase( i==36 ); /* TRIGGER */
111050       testcase( i==37 ); /* REFERENCES */
111051       testcase( i==38 ); /* CONSTRAINT */
111052       testcase( i==39 ); /* INTO */
111053       testcase( i==40 ); /* OFFSET */
111054       testcase( i==41 ); /* OF */
111055       testcase( i==42 ); /* SET */
111056       testcase( i==43 ); /* TEMPORARY */
111057       testcase( i==44 ); /* TEMP */
111058       testcase( i==45 ); /* OR */
111059       testcase( i==46 ); /* UNIQUE */
111060       testcase( i==47 ); /* QUERY */
111061       testcase( i==48 ); /* ATTACH */
111062       testcase( i==49 ); /* HAVING */
111063       testcase( i==50 ); /* GROUP */
111064       testcase( i==51 ); /* UPDATE */
111065       testcase( i==52 ); /* BEGIN */
111066       testcase( i==53 ); /* INNER */
111067       testcase( i==54 ); /* RELEASE */
111068       testcase( i==55 ); /* BETWEEN */
111069       testcase( i==56 ); /* NOTNULL */
111070       testcase( i==57 ); /* NOT */
111071       testcase( i==58 ); /* NO */
111072       testcase( i==59 ); /* NULL */
111073       testcase( i==60 ); /* LIKE */
111074       testcase( i==61 ); /* CASCADE */
111075       testcase( i==62 ); /* ASC */
111076       testcase( i==63 ); /* DELETE */
111077       testcase( i==64 ); /* CASE */
111078       testcase( i==65 ); /* COLLATE */
111079       testcase( i==66 ); /* CREATE */
111080       testcase( i==67 ); /* CURRENT_DATE */
111081       testcase( i==68 ); /* DETACH */
111082       testcase( i==69 ); /* IMMEDIATE */
111083       testcase( i==70 ); /* JOIN */
111084       testcase( i==71 ); /* INSERT */
111085       testcase( i==72 ); /* MATCH */
111086       testcase( i==73 ); /* PLAN */
111087       testcase( i==74 ); /* ANALYZE */
111088       testcase( i==75 ); /* PRAGMA */
111089       testcase( i==76 ); /* ABORT */
111090       testcase( i==77 ); /* VALUES */
111091       testcase( i==78 ); /* VIRTUAL */
111092       testcase( i==79 ); /* LIMIT */
111093       testcase( i==80 ); /* WHEN */
111094       testcase( i==81 ); /* WHERE */
111095       testcase( i==82 ); /* RENAME */
111096       testcase( i==83 ); /* AFTER */
111097       testcase( i==84 ); /* REPLACE */
111098       testcase( i==85 ); /* AND */
111099       testcase( i==86 ); /* DEFAULT */
111100       testcase( i==87 ); /* AUTOINCREMENT */
111101       testcase( i==88 ); /* TO */
111102       testcase( i==89 ); /* IN */
111103       testcase( i==90 ); /* CAST */
111104       testcase( i==91 ); /* COLUMN */
111105       testcase( i==92 ); /* COMMIT */
111106       testcase( i==93 ); /* CONFLICT */
111107       testcase( i==94 ); /* CROSS */
111108       testcase( i==95 ); /* CURRENT_TIMESTAMP */
111109       testcase( i==96 ); /* CURRENT_TIME */
111110       testcase( i==97 ); /* PRIMARY */
111111       testcase( i==98 ); /* DEFERRED */
111112       testcase( i==99 ); /* DISTINCT */
111113       testcase( i==100 ); /* IS */
111114       testcase( i==101 ); /* DROP */
111115       testcase( i==102 ); /* FAIL */
111116       testcase( i==103 ); /* FROM */
111117       testcase( i==104 ); /* FULL */
111118       testcase( i==105 ); /* GLOB */
111119       testcase( i==106 ); /* BY */
111120       testcase( i==107 ); /* IF */
111121       testcase( i==108 ); /* ISNULL */
111122       testcase( i==109 ); /* ORDER */
111123       testcase( i==110 ); /* RESTRICT */
111124       testcase( i==111 ); /* OUTER */
111125       testcase( i==112 ); /* RIGHT */
111126       testcase( i==113 ); /* ROLLBACK */
111127       testcase( i==114 ); /* ROW */
111128       testcase( i==115 ); /* UNION */
111129       testcase( i==116 ); /* USING */
111130       testcase( i==117 ); /* VACUUM */
111131       testcase( i==118 ); /* VIEW */
111132       testcase( i==119 ); /* INITIALLY */
111133       testcase( i==120 ); /* ALL */
111134       return aCode[i];
111135     }
111136   }
111137   return TK_ID;
111138 }
111139 SQLCIPHER_PRIVATE int sqlcipher3KeywordCode(const unsigned char *z, int n){
111140   return keywordCode((char*)z, n);
111141 }
111142 #define SQLCIPHER_N_KEYWORD 121
111143
111144 /************** End of keywordhash.h *****************************************/
111145 /************** Continuing where we left off in tokenize.c *******************/
111146
111147
111148 /*
111149 ** If X is a character that can be used in an identifier then
111150 ** IdChar(X) will be true.  Otherwise it is false.
111151 **
111152 ** For ASCII, any character with the high-order bit set is
111153 ** allowed in an identifier.  For 7-bit characters, 
111154 ** sqlcipher3IsIdChar[X] must be 1.
111155 **
111156 ** For EBCDIC, the rules are more complex but have the same
111157 ** end result.
111158 **
111159 ** Ticket #1066.  the SQL standard does not allow '$' in the
111160 ** middle of identfiers.  But many SQL implementations do. 
111161 ** SQLite will allow '$' in identifiers for compatibility.
111162 ** But the feature is undocumented.
111163 */
111164 #ifdef SQLCIPHER_ASCII
111165 #define IdChar(C)  ((sqlcipher3CtypeMap[(unsigned char)C]&0x46)!=0)
111166 #endif
111167 #ifdef SQLCIPHER_EBCDIC
111168 SQLCIPHER_PRIVATE const char sqlcipher3IsEbcdicIdChar[] = {
111169 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
111170     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
111171     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
111172     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
111173     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
111174     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
111175     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
111176     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
111177     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
111178     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
111179     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
111180     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
111181     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
111182 };
111183 #define IdChar(C)  (((c=C)>=0x42 && sqlcipher3IsEbcdicIdChar[c-0x40]))
111184 #endif
111185
111186
111187 /*
111188 ** Return the length of the token that begins at z[0]. 
111189 ** Store the token type in *tokenType before returning.
111190 */
111191 SQLCIPHER_PRIVATE int sqlcipher3GetToken(const unsigned char *z, int *tokenType){
111192   int i, c;
111193   switch( *z ){
111194     case ' ': case '\t': case '\n': case '\f': case '\r': {
111195       testcase( z[0]==' ' );
111196       testcase( z[0]=='\t' );
111197       testcase( z[0]=='\n' );
111198       testcase( z[0]=='\f' );
111199       testcase( z[0]=='\r' );
111200       for(i=1; sqlcipher3Isspace(z[i]); i++){}
111201       *tokenType = TK_SPACE;
111202       return i;
111203     }
111204     case '-': {
111205       if( z[1]=='-' ){
111206         /* IMP: R-15891-05542 -- syntax diagram for comments */
111207         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
111208         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
111209         return i;
111210       }
111211       *tokenType = TK_MINUS;
111212       return 1;
111213     }
111214     case '(': {
111215       *tokenType = TK_LP;
111216       return 1;
111217     }
111218     case ')': {
111219       *tokenType = TK_RP;
111220       return 1;
111221     }
111222     case ';': {
111223       *tokenType = TK_SEMI;
111224       return 1;
111225     }
111226     case '+': {
111227       *tokenType = TK_PLUS;
111228       return 1;
111229     }
111230     case '*': {
111231       *tokenType = TK_STAR;
111232       return 1;
111233     }
111234     case '/': {
111235       if( z[1]!='*' || z[2]==0 ){
111236         *tokenType = TK_SLASH;
111237         return 1;
111238       }
111239       /* IMP: R-15891-05542 -- syntax diagram for comments */
111240       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
111241       if( c ) i++;
111242       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
111243       return i;
111244     }
111245     case '%': {
111246       *tokenType = TK_REM;
111247       return 1;
111248     }
111249     case '=': {
111250       *tokenType = TK_EQ;
111251       return 1 + (z[1]=='=');
111252     }
111253     case '<': {
111254       if( (c=z[1])=='=' ){
111255         *tokenType = TK_LE;
111256         return 2;
111257       }else if( c=='>' ){
111258         *tokenType = TK_NE;
111259         return 2;
111260       }else if( c=='<' ){
111261         *tokenType = TK_LSHIFT;
111262         return 2;
111263       }else{
111264         *tokenType = TK_LT;
111265         return 1;
111266       }
111267     }
111268     case '>': {
111269       if( (c=z[1])=='=' ){
111270         *tokenType = TK_GE;
111271         return 2;
111272       }else if( c=='>' ){
111273         *tokenType = TK_RSHIFT;
111274         return 2;
111275       }else{
111276         *tokenType = TK_GT;
111277         return 1;
111278       }
111279     }
111280     case '!': {
111281       if( z[1]!='=' ){
111282         *tokenType = TK_ILLEGAL;
111283         return 2;
111284       }else{
111285         *tokenType = TK_NE;
111286         return 2;
111287       }
111288     }
111289     case '|': {
111290       if( z[1]!='|' ){
111291         *tokenType = TK_BITOR;
111292         return 1;
111293       }else{
111294         *tokenType = TK_CONCAT;
111295         return 2;
111296       }
111297     }
111298     case ',': {
111299       *tokenType = TK_COMMA;
111300       return 1;
111301     }
111302     case '&': {
111303       *tokenType = TK_BITAND;
111304       return 1;
111305     }
111306     case '~': {
111307       *tokenType = TK_BITNOT;
111308       return 1;
111309     }
111310     case '`':
111311     case '\'':
111312     case '"': {
111313       int delim = z[0];
111314       testcase( delim=='`' );
111315       testcase( delim=='\'' );
111316       testcase( delim=='"' );
111317       for(i=1; (c=z[i])!=0; i++){
111318         if( c==delim ){
111319           if( z[i+1]==delim ){
111320             i++;
111321           }else{
111322             break;
111323           }
111324         }
111325       }
111326       if( c=='\'' ){
111327         *tokenType = TK_STRING;
111328         return i+1;
111329       }else if( c!=0 ){
111330         *tokenType = TK_ID;
111331         return i+1;
111332       }else{
111333         *tokenType = TK_ILLEGAL;
111334         return i;
111335       }
111336     }
111337     case '.': {
111338 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
111339       if( !sqlcipher3Isdigit(z[1]) )
111340 #endif
111341       {
111342         *tokenType = TK_DOT;
111343         return 1;
111344       }
111345       /* If the next character is a digit, this is a floating point
111346       ** number that begins with ".".  Fall thru into the next case */
111347     }
111348     case '0': case '1': case '2': case '3': case '4':
111349     case '5': case '6': case '7': case '8': case '9': {
111350       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
111351       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
111352       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
111353       testcase( z[0]=='9' );
111354       *tokenType = TK_INTEGER;
111355       for(i=0; sqlcipher3Isdigit(z[i]); i++){}
111356 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
111357       if( z[i]=='.' ){
111358         i++;
111359         while( sqlcipher3Isdigit(z[i]) ){ i++; }
111360         *tokenType = TK_FLOAT;
111361       }
111362       if( (z[i]=='e' || z[i]=='E') &&
111363            ( sqlcipher3Isdigit(z[i+1]) 
111364             || ((z[i+1]=='+' || z[i+1]=='-') && sqlcipher3Isdigit(z[i+2]))
111365            )
111366       ){
111367         i += 2;
111368         while( sqlcipher3Isdigit(z[i]) ){ i++; }
111369         *tokenType = TK_FLOAT;
111370       }
111371 #endif
111372       while( IdChar(z[i]) ){
111373         *tokenType = TK_ILLEGAL;
111374         i++;
111375       }
111376       return i;
111377     }
111378     case '[': {
111379       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
111380       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
111381       return i;
111382     }
111383     case '?': {
111384       *tokenType = TK_VARIABLE;
111385       for(i=1; sqlcipher3Isdigit(z[i]); i++){}
111386       return i;
111387     }
111388     case '#': {
111389       for(i=1; sqlcipher3Isdigit(z[i]); i++){}
111390       if( i>1 ){
111391         /* Parameters of the form #NNN (where NNN is a number) are used
111392         ** internally by sqlcipher3NestedParse.  */
111393         *tokenType = TK_REGISTER;
111394         return i;
111395       }
111396       /* Fall through into the next case if the '#' is not followed by
111397       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
111398     }
111399 #ifndef SQLCIPHER_OMIT_TCL_VARIABLE
111400     case '$':
111401 #endif
111402     case '@':  /* For compatibility with MS SQL Server */
111403     case ':': {
111404       int n = 0;
111405       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
111406       *tokenType = TK_VARIABLE;
111407       for(i=1; (c=z[i])!=0; i++){
111408         if( IdChar(c) ){
111409           n++;
111410 #ifndef SQLCIPHER_OMIT_TCL_VARIABLE
111411         }else if( c=='(' && n>0 ){
111412           do{
111413             i++;
111414           }while( (c=z[i])!=0 && !sqlcipher3Isspace(c) && c!=')' );
111415           if( c==')' ){
111416             i++;
111417           }else{
111418             *tokenType = TK_ILLEGAL;
111419           }
111420           break;
111421         }else if( c==':' && z[i+1]==':' ){
111422           i++;
111423 #endif
111424         }else{
111425           break;
111426         }
111427       }
111428       if( n==0 ) *tokenType = TK_ILLEGAL;
111429       return i;
111430     }
111431 #ifndef SQLCIPHER_OMIT_BLOB_LITERAL
111432     case 'x': case 'X': {
111433       testcase( z[0]=='x' ); testcase( z[0]=='X' );
111434       if( z[1]=='\'' ){
111435         *tokenType = TK_BLOB;
111436         for(i=2; sqlcipher3Isxdigit(z[i]); i++){}
111437         if( z[i]!='\'' || i%2 ){
111438           *tokenType = TK_ILLEGAL;
111439           while( z[i] && z[i]!='\'' ){ i++; }
111440         }
111441         if( z[i] ) i++;
111442         return i;
111443       }
111444       /* Otherwise fall through to the next case */
111445     }
111446 #endif
111447     default: {
111448       if( !IdChar(*z) ){
111449         break;
111450       }
111451       for(i=1; IdChar(z[i]); i++){}
111452       *tokenType = keywordCode((char*)z, i);
111453       return i;
111454     }
111455   }
111456   *tokenType = TK_ILLEGAL;
111457   return 1;
111458 }
111459
111460 /*
111461 ** Run the parser on the given SQL string.  The parser structure is
111462 ** passed in.  An SQLCIPHER_ status code is returned.  If an error occurs
111463 ** then an and attempt is made to write an error message into 
111464 ** memory obtained from sqlcipher3_malloc() and to make *pzErrMsg point to that
111465 ** error message.
111466 */
111467 SQLCIPHER_PRIVATE int sqlcipher3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
111468   int nErr = 0;                   /* Number of errors encountered */
111469   int i;                          /* Loop counter */
111470   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
111471   int tokenType;                  /* type of the next token */
111472   int lastTokenParsed = -1;       /* type of the previous token */
111473   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
111474   sqlcipher3 *db = pParse->db;       /* The database connection */
111475   int mxSqlLen;                   /* Max length of an SQL string */
111476
111477
111478   mxSqlLen = db->aLimit[SQLCIPHER_LIMIT_SQL_LENGTH];
111479   if( db->activeVdbeCnt==0 ){
111480     db->u1.isInterrupted = 0;
111481   }
111482   pParse->rc = SQLCIPHER_OK;
111483   pParse->zTail = zSql;
111484   i = 0;
111485   assert( pzErrMsg!=0 );
111486   pEngine = sqlcipher3ParserAlloc((void*(*)(size_t))sqlcipher3Malloc);
111487   if( pEngine==0 ){
111488     db->mallocFailed = 1;
111489     return SQLCIPHER_NOMEM;
111490   }
111491   assert( pParse->pNewTable==0 );
111492   assert( pParse->pNewTrigger==0 );
111493   assert( pParse->nVar==0 );
111494   assert( pParse->nzVar==0 );
111495   assert( pParse->azVar==0 );
111496   enableLookaside = db->lookaside.bEnabled;
111497   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
111498   while( !db->mallocFailed && zSql[i]!=0 ){
111499     assert( i>=0 );
111500     pParse->sLastToken.z = &zSql[i];
111501     pParse->sLastToken.n = sqlcipher3GetToken((unsigned char*)&zSql[i],&tokenType);
111502     i += pParse->sLastToken.n;
111503     if( i>mxSqlLen ){
111504       pParse->rc = SQLCIPHER_TOOBIG;
111505       break;
111506     }
111507     switch( tokenType ){
111508       case TK_SPACE: {
111509         if( db->u1.isInterrupted ){
111510           sqlcipher3ErrorMsg(pParse, "interrupt");
111511           pParse->rc = SQLCIPHER_INTERRUPT;
111512           goto abort_parse;
111513         }
111514         break;
111515       }
111516       case TK_ILLEGAL: {
111517         sqlcipher3DbFree(db, *pzErrMsg);
111518         *pzErrMsg = sqlcipher3MPrintf(db, "unrecognized token: \"%T\"",
111519                         &pParse->sLastToken);
111520         nErr++;
111521         goto abort_parse;
111522       }
111523       case TK_SEMI: {
111524         pParse->zTail = &zSql[i];
111525         /* Fall thru into the default case */
111526       }
111527       default: {
111528         sqlcipher3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
111529         lastTokenParsed = tokenType;
111530         if( pParse->rc!=SQLCIPHER_OK ){
111531           goto abort_parse;
111532         }
111533         break;
111534       }
111535     }
111536   }
111537 abort_parse:
111538   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLCIPHER_OK ){
111539     if( lastTokenParsed!=TK_SEMI ){
111540       sqlcipher3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
111541       pParse->zTail = &zSql[i];
111542     }
111543     sqlcipher3Parser(pEngine, 0, pParse->sLastToken, pParse);
111544   }
111545 #ifdef YYTRACKMAXSTACKDEPTH
111546   sqlcipher3StatusSet(SQLCIPHER_STATUS_PARSER_STACK,
111547       sqlcipher3ParserStackPeak(pEngine)
111548   );
111549 #endif /* YYDEBUG */
111550   sqlcipher3ParserFree(pEngine, sqlcipher3_free);
111551   db->lookaside.bEnabled = enableLookaside;
111552   if( db->mallocFailed ){
111553     pParse->rc = SQLCIPHER_NOMEM;
111554   }
111555   if( pParse->rc!=SQLCIPHER_OK && pParse->rc!=SQLCIPHER_DONE && pParse->zErrMsg==0 ){
111556     sqlcipher3SetString(&pParse->zErrMsg, db, "%s", sqlcipher3ErrStr(pParse->rc));
111557   }
111558   assert( pzErrMsg!=0 );
111559   if( pParse->zErrMsg ){
111560     *pzErrMsg = pParse->zErrMsg;
111561     sqlcipher3_log(pParse->rc, "%s", *pzErrMsg);
111562     pParse->zErrMsg = 0;
111563     nErr++;
111564   }
111565   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
111566     sqlcipher3VdbeDelete(pParse->pVdbe);
111567     pParse->pVdbe = 0;
111568   }
111569 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
111570   if( pParse->nested==0 ){
111571     sqlcipher3DbFree(db, pParse->aTableLock);
111572     pParse->aTableLock = 0;
111573     pParse->nTableLock = 0;
111574   }
111575 #endif
111576 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
111577   sqlcipher3_free(pParse->apVtabLock);
111578 #endif
111579
111580   if( !IN_DECLARE_VTAB ){
111581     /* If the pParse->declareVtab flag is set, do not delete any table 
111582     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
111583     ** will take responsibility for freeing the Table structure.
111584     */
111585     sqlcipher3DeleteTable(db, pParse->pNewTable);
111586   }
111587
111588   sqlcipher3DeleteTrigger(db, pParse->pNewTrigger);
111589   for(i=pParse->nzVar-1; i>=0; i--) sqlcipher3DbFree(db, pParse->azVar[i]);
111590   sqlcipher3DbFree(db, pParse->azVar);
111591   sqlcipher3DbFree(db, pParse->aAlias);
111592   while( pParse->pAinc ){
111593     AutoincInfo *p = pParse->pAinc;
111594     pParse->pAinc = p->pNext;
111595     sqlcipher3DbFree(db, p);
111596   }
111597   while( pParse->pZombieTab ){
111598     Table *p = pParse->pZombieTab;
111599     pParse->pZombieTab = p->pNextZombie;
111600     sqlcipher3DeleteTable(db, p);
111601   }
111602   if( nErr>0 && pParse->rc==SQLCIPHER_OK ){
111603     pParse->rc = SQLCIPHER_ERROR;
111604   }
111605   return nErr;
111606 }
111607
111608 /************** End of tokenize.c ********************************************/
111609 /************** Begin file complete.c ****************************************/
111610 /*
111611 ** 2001 September 15
111612 **
111613 ** The author disclaims copyright to this source code.  In place of
111614 ** a legal notice, here is a blessing:
111615 **
111616 **    May you do good and not evil.
111617 **    May you find forgiveness for yourself and forgive others.
111618 **    May you share freely, never taking more than you give.
111619 **
111620 *************************************************************************
111621 ** An tokenizer for SQL
111622 **
111623 ** This file contains C code that implements the sqlcipher3_complete() API.
111624 ** This code used to be part of the tokenizer.c source file.  But by
111625 ** separating it out, the code will be automatically omitted from
111626 ** static links that do not use it.
111627 */
111628 #ifndef SQLCIPHER_OMIT_COMPLETE
111629
111630 /*
111631 ** This is defined in tokenize.c.  We just have to import the definition.
111632 */
111633 #ifndef SQLCIPHER_AMALGAMATION
111634 #ifdef SQLCIPHER_ASCII
111635 #define IdChar(C)  ((sqlcipher3CtypeMap[(unsigned char)C]&0x46)!=0)
111636 #endif
111637 #ifdef SQLCIPHER_EBCDIC
111638 SQLCIPHER_PRIVATE const char sqlcipher3IsEbcdicIdChar[];
111639 #define IdChar(C)  (((c=C)>=0x42 && sqlcipher3IsEbcdicIdChar[c-0x40]))
111640 #endif
111641 #endif /* SQLCIPHER_AMALGAMATION */
111642
111643
111644 /*
111645 ** Token types used by the sqlcipher3_complete() routine.  See the header
111646 ** comments on that procedure for additional information.
111647 */
111648 #define tkSEMI    0
111649 #define tkWS      1
111650 #define tkOTHER   2
111651 #ifndef SQLCIPHER_OMIT_TRIGGER
111652 #define tkEXPLAIN 3
111653 #define tkCREATE  4
111654 #define tkTEMP    5
111655 #define tkTRIGGER 6
111656 #define tkEND     7
111657 #endif
111658
111659 /*
111660 ** Return TRUE if the given SQL string ends in a semicolon.
111661 **
111662 ** Special handling is require for CREATE TRIGGER statements.
111663 ** Whenever the CREATE TRIGGER keywords are seen, the statement
111664 ** must end with ";END;".
111665 **
111666 ** This implementation uses a state machine with 8 states:
111667 **
111668 **   (0) INVALID   We have not yet seen a non-whitespace character.
111669 **
111670 **   (1) START     At the beginning or end of an SQL statement.  This routine
111671 **                 returns 1 if it ends in the START state and 0 if it ends
111672 **                 in any other state.
111673 **
111674 **   (2) NORMAL    We are in the middle of statement which ends with a single
111675 **                 semicolon.
111676 **
111677 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
111678 **                 a statement.
111679 **
111680 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
111681 **                 statement, possibly preceeded by EXPLAIN and/or followed by
111682 **                 TEMP or TEMPORARY
111683 **
111684 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
111685 **                 ended by a semicolon, the keyword END, and another semicolon.
111686 **
111687 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
111688 **                 the end of a trigger definition.
111689 **
111690 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
111691 **                 of a trigger difinition.
111692 **
111693 ** Transitions between states above are determined by tokens extracted
111694 ** from the input.  The following tokens are significant:
111695 **
111696 **   (0) tkSEMI      A semicolon.
111697 **   (1) tkWS        Whitespace.
111698 **   (2) tkOTHER     Any other SQL token.
111699 **   (3) tkEXPLAIN   The "explain" keyword.
111700 **   (4) tkCREATE    The "create" keyword.
111701 **   (5) tkTEMP      The "temp" or "temporary" keyword.
111702 **   (6) tkTRIGGER   The "trigger" keyword.
111703 **   (7) tkEND       The "end" keyword.
111704 **
111705 ** Whitespace never causes a state transition and is always ignored.
111706 ** This means that a SQL string of all whitespace is invalid.
111707 **
111708 ** If we compile with SQLCIPHER_OMIT_TRIGGER, all of the computation needed
111709 ** to recognize the end of a trigger can be omitted.  All we have to do
111710 ** is look for a semicolon that is not part of an string or comment.
111711 */
111712 SQLCIPHER_API int sqlcipher3_complete(const char *zSql){
111713   u8 state = 0;   /* Current state, using numbers defined in header comment */
111714   u8 token;       /* Value of the next token */
111715
111716 #ifndef SQLCIPHER_OMIT_TRIGGER
111717   /* A complex statement machine used to detect the end of a CREATE TRIGGER
111718   ** statement.  This is the normal case.
111719   */
111720   static const u8 trans[8][8] = {
111721                      /* Token:                                                */
111722      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
111723      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
111724      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
111725      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
111726      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
111727      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
111728      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
111729      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
111730      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
111731   };
111732 #else
111733   /* If triggers are not supported by this compile then the statement machine
111734   ** used to detect the end of a statement is much simplier
111735   */
111736   static const u8 trans[3][3] = {
111737                      /* Token:           */
111738      /* State:       **  SEMI  WS  OTHER */
111739      /* 0 INVALID: */ {    1,  0,     2, },
111740      /* 1   START: */ {    1,  1,     2, },
111741      /* 2  NORMAL: */ {    1,  2,     2, },
111742   };
111743 #endif /* SQLCIPHER_OMIT_TRIGGER */
111744
111745   while( *zSql ){
111746     switch( *zSql ){
111747       case ';': {  /* A semicolon */
111748         token = tkSEMI;
111749         break;
111750       }
111751       case ' ':
111752       case '\r':
111753       case '\t':
111754       case '\n':
111755       case '\f': {  /* White space is ignored */
111756         token = tkWS;
111757         break;
111758       }
111759       case '/': {   /* C-style comments */
111760         if( zSql[1]!='*' ){
111761           token = tkOTHER;
111762           break;
111763         }
111764         zSql += 2;
111765         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
111766         if( zSql[0]==0 ) return 0;
111767         zSql++;
111768         token = tkWS;
111769         break;
111770       }
111771       case '-': {   /* SQL-style comments from "--" to end of line */
111772         if( zSql[1]!='-' ){
111773           token = tkOTHER;
111774           break;
111775         }
111776         while( *zSql && *zSql!='\n' ){ zSql++; }
111777         if( *zSql==0 ) return state==1;
111778         token = tkWS;
111779         break;
111780       }
111781       case '[': {   /* Microsoft-style identifiers in [...] */
111782         zSql++;
111783         while( *zSql && *zSql!=']' ){ zSql++; }
111784         if( *zSql==0 ) return 0;
111785         token = tkOTHER;
111786         break;
111787       }
111788       case '`':     /* Grave-accent quoted symbols used by MySQL */
111789       case '"':     /* single- and double-quoted strings */
111790       case '\'': {
111791         int c = *zSql;
111792         zSql++;
111793         while( *zSql && *zSql!=c ){ zSql++; }
111794         if( *zSql==0 ) return 0;
111795         token = tkOTHER;
111796         break;
111797       }
111798       default: {
111799 #ifdef SQLCIPHER_EBCDIC
111800         unsigned char c;
111801 #endif
111802         if( IdChar((u8)*zSql) ){
111803           /* Keywords and unquoted identifiers */
111804           int nId;
111805           for(nId=1; IdChar(zSql[nId]); nId++){}
111806 #ifdef SQLCIPHER_OMIT_TRIGGER
111807           token = tkOTHER;
111808 #else
111809           switch( *zSql ){
111810             case 'c': case 'C': {
111811               if( nId==6 && sqlcipher3StrNICmp(zSql, "create", 6)==0 ){
111812                 token = tkCREATE;
111813               }else{
111814                 token = tkOTHER;
111815               }
111816               break;
111817             }
111818             case 't': case 'T': {
111819               if( nId==7 && sqlcipher3StrNICmp(zSql, "trigger", 7)==0 ){
111820                 token = tkTRIGGER;
111821               }else if( nId==4 && sqlcipher3StrNICmp(zSql, "temp", 4)==0 ){
111822                 token = tkTEMP;
111823               }else if( nId==9 && sqlcipher3StrNICmp(zSql, "temporary", 9)==0 ){
111824                 token = tkTEMP;
111825               }else{
111826                 token = tkOTHER;
111827               }
111828               break;
111829             }
111830             case 'e':  case 'E': {
111831               if( nId==3 && sqlcipher3StrNICmp(zSql, "end", 3)==0 ){
111832                 token = tkEND;
111833               }else
111834 #ifndef SQLCIPHER_OMIT_EXPLAIN
111835               if( nId==7 && sqlcipher3StrNICmp(zSql, "explain", 7)==0 ){
111836                 token = tkEXPLAIN;
111837               }else
111838 #endif
111839               {
111840                 token = tkOTHER;
111841               }
111842               break;
111843             }
111844             default: {
111845               token = tkOTHER;
111846               break;
111847             }
111848           }
111849 #endif /* SQLCIPHER_OMIT_TRIGGER */
111850           zSql += nId-1;
111851         }else{
111852           /* Operators and special symbols */
111853           token = tkOTHER;
111854         }
111855         break;
111856       }
111857     }
111858     state = trans[state][token];
111859     zSql++;
111860   }
111861   return state==1;
111862 }
111863
111864 #ifndef SQLCIPHER_OMIT_UTF16
111865 /*
111866 ** This routine is the same as the sqlcipher3_complete() routine described
111867 ** above, except that the parameter is required to be UTF-16 encoded, not
111868 ** UTF-8.
111869 */
111870 SQLCIPHER_API int sqlcipher3_complete16(const void *zSql){
111871   sqlcipher3_value *pVal;
111872   char const *zSql8;
111873   int rc = SQLCIPHER_NOMEM;
111874
111875 #ifndef SQLCIPHER_OMIT_AUTOINIT
111876   rc = sqlcipher3_initialize();
111877   if( rc ) return rc;
111878 #endif
111879   pVal = sqlcipher3ValueNew(0);
111880   sqlcipher3ValueSetStr(pVal, -1, zSql, SQLCIPHER_UTF16NATIVE, SQLCIPHER_STATIC);
111881   zSql8 = sqlcipher3ValueText(pVal, SQLCIPHER_UTF8);
111882   if( zSql8 ){
111883     rc = sqlcipher3_complete(zSql8);
111884   }else{
111885     rc = SQLCIPHER_NOMEM;
111886   }
111887   sqlcipher3ValueFree(pVal);
111888   return sqlcipher3ApiExit(0, rc);
111889 }
111890 #endif /* SQLCIPHER_OMIT_UTF16 */
111891 #endif /* SQLCIPHER_OMIT_COMPLETE */
111892
111893 /************** End of complete.c ********************************************/
111894 /************** Begin file main.c ********************************************/
111895 /*
111896 ** 2001 September 15
111897 **
111898 ** The author disclaims copyright to this source code.  In place of
111899 ** a legal notice, here is a blessing:
111900 **
111901 **    May you do good and not evil.
111902 **    May you find forgiveness for yourself and forgive others.
111903 **    May you share freely, never taking more than you give.
111904 **
111905 *************************************************************************
111906 ** Main file for the SQLite library.  The routines in this file
111907 ** implement the programmer interface to the library.  Routines in
111908 ** other files are for internal use by SQLite and should not be
111909 ** accessed by users of the library.
111910 */
111911
111912 #ifdef SQLCIPHER_ENABLE_FTS3
111913 /************** Include fts3.h in the middle of main.c ***********************/
111914 /************** Begin file fts3.h ********************************************/
111915 /*
111916 ** 2006 Oct 10
111917 **
111918 ** The author disclaims copyright to this source code.  In place of
111919 ** a legal notice, here is a blessing:
111920 **
111921 **    May you do good and not evil.
111922 **    May you find forgiveness for yourself and forgive others.
111923 **    May you share freely, never taking more than you give.
111924 **
111925 ******************************************************************************
111926 **
111927 ** This header file is used by programs that want to link against the
111928 ** FTS3 library.  All it does is declare the sqlcipher3Fts3Init() interface.
111929 */
111930
111931 #if 0
111932 extern "C" {
111933 #endif  /* __cplusplus */
111934
111935 SQLCIPHER_PRIVATE int sqlcipher3Fts3Init(sqlcipher3 *db);
111936
111937 #if 0
111938 }  /* extern "C" */
111939 #endif  /* __cplusplus */
111940
111941 /************** End of fts3.h ************************************************/
111942 /************** Continuing where we left off in main.c ***********************/
111943 #endif
111944 #ifdef SQLCIPHER_ENABLE_RTREE
111945 /************** Include rtree.h in the middle of main.c **********************/
111946 /************** Begin file rtree.h *******************************************/
111947 /*
111948 ** 2008 May 26
111949 **
111950 ** The author disclaims copyright to this source code.  In place of
111951 ** a legal notice, here is a blessing:
111952 **
111953 **    May you do good and not evil.
111954 **    May you find forgiveness for yourself and forgive others.
111955 **    May you share freely, never taking more than you give.
111956 **
111957 ******************************************************************************
111958 **
111959 ** This header file is used by programs that want to link against the
111960 ** RTREE library.  All it does is declare the sqlcipher3RtreeInit() interface.
111961 */
111962
111963 #if 0
111964 extern "C" {
111965 #endif  /* __cplusplus */
111966
111967 SQLCIPHER_PRIVATE int sqlcipher3RtreeInit(sqlcipher3 *db);
111968
111969 #if 0
111970 }  /* extern "C" */
111971 #endif  /* __cplusplus */
111972
111973 /************** End of rtree.h ***********************************************/
111974 /************** Continuing where we left off in main.c ***********************/
111975 #endif
111976 #ifdef SQLCIPHER_ENABLE_ICU
111977 /************** Include sqlciphericu.h in the middle of main.c ******************/
111978 /************** Begin file sqlciphericu.h ***************************************/
111979 /*
111980 ** 2008 May 26
111981 **
111982 ** The author disclaims copyright to this source code.  In place of
111983 ** a legal notice, here is a blessing:
111984 **
111985 **    May you do good and not evil.
111986 **    May you find forgiveness for yourself and forgive others.
111987 **    May you share freely, never taking more than you give.
111988 **
111989 ******************************************************************************
111990 **
111991 ** This header file is used by programs that want to link against the
111992 ** ICU extension.  All it does is declare the sqlcipher3IcuInit() interface.
111993 */
111994
111995 #if 0
111996 extern "C" {
111997 #endif  /* __cplusplus */
111998
111999 SQLCIPHER_PRIVATE int sqlcipher3IcuInit(sqlcipher3 *db);
112000
112001 #if 0
112002 }  /* extern "C" */
112003 #endif  /* __cplusplus */
112004
112005
112006 /************** End of sqlciphericu.h *******************************************/
112007 /************** Continuing where we left off in main.c ***********************/
112008 #endif
112009
112010 #ifndef SQLCIPHER_AMALGAMATION
112011 /* IMPLEMENTATION-OF: R-46656-45156 The sqlcipher3_version[] string constant
112012 ** contains the text of SQLCIPHER_VERSION macro. 
112013 */
112014 SQLCIPHER_API const char sqlcipher3_version[] = SQLCIPHER_VERSION;
112015 #endif
112016
112017 /* IMPLEMENTATION-OF: R-53536-42575 The sqlcipher3_libversion() function returns
112018 ** a pointer to the to the sqlcipher3_version[] string constant. 
112019 */
112020 SQLCIPHER_API const char *sqlcipher3_libversion(void){ return sqlcipher3_version; }
112021
112022 /* IMPLEMENTATION-OF: R-63124-39300 The sqlcipher3_sourceid() function returns a
112023 ** pointer to a string constant whose value is the same as the
112024 ** SQLCIPHER_SOURCE_ID C preprocessor macro. 
112025 */
112026 SQLCIPHER_API const char *sqlcipher3_sourceid(void){ return SQLCIPHER_SOURCE_ID; }
112027
112028 /* IMPLEMENTATION-OF: R-35210-63508 The sqlcipher3_libversion_number() function
112029 ** returns an integer equal to SQLCIPHER_VERSION_NUMBER.
112030 */
112031 SQLCIPHER_API int sqlcipher3_libversion_number(void){ return SQLCIPHER_VERSION_NUMBER; }
112032
112033 /* IMPLEMENTATION-OF: R-54823-41343 The sqlcipher3_threadsafe() function returns
112034 ** zero if and only if SQLite was compiled mutexing code omitted due to
112035 ** the SQLCIPHER_THREADSAFE compile-time option being set to 0.
112036 */
112037 SQLCIPHER_API int sqlcipher3_threadsafe(void){ return SQLCIPHER_THREADSAFE; }
112038
112039 #if !defined(SQLCIPHER_OMIT_TRACE) && defined(SQLCIPHER_ENABLE_IOTRACE)
112040 /*
112041 ** If the following function pointer is not NULL and if
112042 ** SQLCIPHER_ENABLE_IOTRACE is enabled, then messages describing
112043 ** I/O active are written using this function.  These messages
112044 ** are intended for debugging activity only.
112045 */
112046 SQLCIPHER_PRIVATE void (*sqlcipher3IoTrace)(const char*, ...) = 0;
112047 #endif
112048
112049 /*
112050 ** If the following global variable points to a string which is the
112051 ** name of a directory, then that directory will be used to store
112052 ** temporary files.
112053 **
112054 ** See also the "PRAGMA temp_store_directory" SQL command.
112055 */
112056 SQLCIPHER_API char *sqlcipher3_temp_directory = 0;
112057
112058 /*
112059 ** Initialize SQLite.  
112060 **
112061 ** This routine must be called to initialize the memory allocation,
112062 ** VFS, and mutex subsystems prior to doing any serious work with
112063 ** SQLite.  But as long as you do not compile with SQLCIPHER_OMIT_AUTOINIT
112064 ** this routine will be called automatically by key routines such as
112065 ** sqlcipher3_open().  
112066 **
112067 ** This routine is a no-op except on its very first call for the process,
112068 ** or for the first call after a call to sqlcipher3_shutdown.
112069 **
112070 ** The first thread to call this routine runs the initialization to
112071 ** completion.  If subsequent threads call this routine before the first
112072 ** thread has finished the initialization process, then the subsequent
112073 ** threads must block until the first thread finishes with the initialization.
112074 **
112075 ** The first thread might call this routine recursively.  Recursive
112076 ** calls to this routine should not block, of course.  Otherwise the
112077 ** initialization process would never complete.
112078 **
112079 ** Let X be the first thread to enter this routine.  Let Y be some other
112080 ** thread.  Then while the initial invocation of this routine by X is
112081 ** incomplete, it is required that:
112082 **
112083 **    *  Calls to this routine from Y must block until the outer-most
112084 **       call by X completes.
112085 **
112086 **    *  Recursive calls to this routine from thread X return immediately
112087 **       without blocking.
112088 */
112089 SQLCIPHER_API int sqlcipher3_initialize(void){
112090   MUTEX_LOGIC( sqlcipher3_mutex *pMaster; )       /* The main static mutex */
112091   int rc;                                      /* Result code */
112092
112093 #ifdef SQLCIPHER_OMIT_WSD
112094   rc = sqlcipher3_wsd_init(4096, 24);
112095   if( rc!=SQLCIPHER_OK ){
112096     return rc;
112097   }
112098 #endif
112099
112100   /* If SQLite is already completely initialized, then this call
112101   ** to sqlcipher3_initialize() should be a no-op.  But the initialization
112102   ** must be complete.  So isInit must not be set until the very end
112103   ** of this routine.
112104   */
112105   if( sqlcipher3GlobalConfig.isInit ) return SQLCIPHER_OK;
112106
112107   /* Make sure the mutex subsystem is initialized.  If unable to 
112108   ** initialize the mutex subsystem, return early with the error.
112109   ** If the system is so sick that we are unable to allocate a mutex,
112110   ** there is not much SQLite is going to be able to do.
112111   **
112112   ** The mutex subsystem must take care of serializing its own
112113   ** initialization.
112114   */
112115   rc = sqlcipher3MutexInit();
112116   if( rc ) return rc;
112117
112118   /* Initialize the malloc() system and the recursive pInitMutex mutex.
112119   ** This operation is protected by the STATIC_MASTER mutex.  Note that
112120   ** MutexAlloc() is called for a static mutex prior to initializing the
112121   ** malloc subsystem - this implies that the allocation of a static
112122   ** mutex must not require support from the malloc subsystem.
112123   */
112124   MUTEX_LOGIC( pMaster = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER); )
112125   sqlcipher3_mutex_enter(pMaster);
112126   sqlcipher3GlobalConfig.isMutexInit = 1;
112127   if( !sqlcipher3GlobalConfig.isMallocInit ){
112128     rc = sqlcipher3MallocInit();
112129   }
112130   if( rc==SQLCIPHER_OK ){
112131     sqlcipher3GlobalConfig.isMallocInit = 1;
112132     if( !sqlcipher3GlobalConfig.pInitMutex ){
112133       sqlcipher3GlobalConfig.pInitMutex =
112134            sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_RECURSIVE);
112135       if( sqlcipher3GlobalConfig.bCoreMutex && !sqlcipher3GlobalConfig.pInitMutex ){
112136         rc = SQLCIPHER_NOMEM;
112137       }
112138     }
112139   }
112140   if( rc==SQLCIPHER_OK ){
112141     sqlcipher3GlobalConfig.nRefInitMutex++;
112142   }
112143   sqlcipher3_mutex_leave(pMaster);
112144
112145   /* If rc is not SQLCIPHER_OK at this point, then either the malloc
112146   ** subsystem could not be initialized or the system failed to allocate
112147   ** the pInitMutex mutex. Return an error in either case.  */
112148   if( rc!=SQLCIPHER_OK ){
112149     return rc;
112150   }
112151
112152   /* Do the rest of the initialization under the recursive mutex so
112153   ** that we will be able to handle recursive calls into
112154   ** sqlcipher3_initialize().  The recursive calls normally come through
112155   ** sqlcipher3_os_init() when it invokes sqlcipher3_vfs_register(), but other
112156   ** recursive calls might also be possible.
112157   **
112158   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
112159   ** to the xInit method, so the xInit method need not be threadsafe.
112160   **
112161   ** The following mutex is what serializes access to the appdef pcache xInit
112162   ** methods.  The sqlcipher3_pcache_methods.xInit() all is embedded in the
112163   ** call to sqlcipher3PcacheInitialize().
112164   */
112165   sqlcipher3_mutex_enter(sqlcipher3GlobalConfig.pInitMutex);
112166   if( sqlcipher3GlobalConfig.isInit==0 && sqlcipher3GlobalConfig.inProgress==0 ){
112167     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlcipher3GlobalFunctions);
112168     sqlcipher3GlobalConfig.inProgress = 1;
112169     memset(pHash, 0, sizeof(sqlcipher3GlobalFunctions));
112170     sqlcipher3RegisterGlobalFunctions();
112171     if( sqlcipher3GlobalConfig.isPCacheInit==0 ){
112172       rc = sqlcipher3PcacheInitialize();
112173     }
112174     if( rc==SQLCIPHER_OK ){
112175       sqlcipher3GlobalConfig.isPCacheInit = 1;
112176       rc = sqlcipher3OsInit();
112177     }
112178     if( rc==SQLCIPHER_OK ){
112179       sqlcipher3PCacheBufferSetup( sqlcipher3GlobalConfig.pPage, 
112180           sqlcipher3GlobalConfig.szPage, sqlcipher3GlobalConfig.nPage);
112181       sqlcipher3GlobalConfig.isInit = 1;
112182     }
112183     sqlcipher3GlobalConfig.inProgress = 0;
112184   }
112185   sqlcipher3_mutex_leave(sqlcipher3GlobalConfig.pInitMutex);
112186
112187   /* Go back under the static mutex and clean up the recursive
112188   ** mutex to prevent a resource leak.
112189   */
112190   sqlcipher3_mutex_enter(pMaster);
112191   sqlcipher3GlobalConfig.nRefInitMutex--;
112192   if( sqlcipher3GlobalConfig.nRefInitMutex<=0 ){
112193     assert( sqlcipher3GlobalConfig.nRefInitMutex==0 );
112194     sqlcipher3_mutex_free(sqlcipher3GlobalConfig.pInitMutex);
112195     sqlcipher3GlobalConfig.pInitMutex = 0;
112196   }
112197   sqlcipher3_mutex_leave(pMaster);
112198
112199   /* The following is just a sanity check to make sure SQLite has
112200   ** been compiled correctly.  It is important to run this code, but
112201   ** we don't want to run it too often and soak up CPU cycles for no
112202   ** reason.  So we run it once during initialization.
112203   */
112204 #ifndef NDEBUG
112205 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
112206   /* This section of code's only "output" is via assert() statements. */
112207   if ( rc==SQLCIPHER_OK ){
112208     u64 x = (((u64)1)<<63)-1;
112209     double y;
112210     assert(sizeof(x)==8);
112211     assert(sizeof(x)==sizeof(y));
112212     memcpy(&y, &x, 8);
112213     assert( sqlcipher3IsNaN(y) );
112214   }
112215 #endif
112216 #endif
112217
112218   /* Do extra initialization steps requested by the SQLCIPHER_EXTRA_INIT
112219   ** compile-time option.
112220   */
112221 #ifdef SQLCIPHER_EXTRA_INIT
112222   if( rc==SQLCIPHER_OK && sqlcipher3GlobalConfig.isInit ){
112223     int SQLCIPHER_EXTRA_INIT(void);
112224     rc = SQLCIPHER_EXTRA_INIT();
112225   }
112226 #endif
112227
112228   return rc;
112229 }
112230
112231 /*
112232 ** Undo the effects of sqlcipher3_initialize().  Must not be called while
112233 ** there are outstanding database connections or memory allocations or
112234 ** while any part of SQLite is otherwise in use in any thread.  This
112235 ** routine is not threadsafe.  But it is safe to invoke this routine
112236 ** on when SQLite is already shut down.  If SQLite is already shut down
112237 ** when this routine is invoked, then this routine is a harmless no-op.
112238 */
112239 SQLCIPHER_API int sqlcipher3_shutdown(void){
112240   if( sqlcipher3GlobalConfig.isInit ){
112241     sqlcipher3_os_end();
112242     sqlcipher3_reset_auto_extension();
112243     sqlcipher3GlobalConfig.isInit = 0;
112244   }
112245   if( sqlcipher3GlobalConfig.isPCacheInit ){
112246     sqlcipher3PcacheShutdown();
112247     sqlcipher3GlobalConfig.isPCacheInit = 0;
112248   }
112249   if( sqlcipher3GlobalConfig.isMallocInit ){
112250     sqlcipher3MallocEnd();
112251     sqlcipher3GlobalConfig.isMallocInit = 0;
112252   }
112253   if( sqlcipher3GlobalConfig.isMutexInit ){
112254     sqlcipher3MutexEnd();
112255     sqlcipher3GlobalConfig.isMutexInit = 0;
112256   }
112257
112258   return SQLCIPHER_OK;
112259 }
112260
112261 /*
112262 ** This API allows applications to modify the global configuration of
112263 ** the SQLite library at run-time.
112264 **
112265 ** This routine should only be called when there are no outstanding
112266 ** database connections or memory allocations.  This routine is not
112267 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
112268 ** behavior.
112269 */
112270 SQLCIPHER_API int sqlcipher3_config(int op, ...){
112271   va_list ap;
112272   int rc = SQLCIPHER_OK;
112273
112274   /* sqlcipher3_config() shall return SQLCIPHER_MISUSE if it is invoked while
112275   ** the SQLite library is in use. */
112276   if( sqlcipher3GlobalConfig.isInit ) return SQLCIPHER_MISUSE_BKPT;
112277
112278   va_start(ap, op);
112279   switch( op ){
112280
112281     /* Mutex configuration options are only available in a threadsafe
112282     ** compile. 
112283     */
112284 #if defined(SQLCIPHER_THREADSAFE) && SQLCIPHER_THREADSAFE>0
112285     case SQLCIPHER_CONFIG_SINGLETHREAD: {
112286       /* Disable all mutexing */
112287       sqlcipher3GlobalConfig.bCoreMutex = 0;
112288       sqlcipher3GlobalConfig.bFullMutex = 0;
112289       break;
112290     }
112291     case SQLCIPHER_CONFIG_MULTITHREAD: {
112292       /* Disable mutexing of database connections */
112293       /* Enable mutexing of core data structures */
112294       sqlcipher3GlobalConfig.bCoreMutex = 1;
112295       sqlcipher3GlobalConfig.bFullMutex = 0;
112296       break;
112297     }
112298     case SQLCIPHER_CONFIG_SERIALIZED: {
112299       /* Enable all mutexing */
112300       sqlcipher3GlobalConfig.bCoreMutex = 1;
112301       sqlcipher3GlobalConfig.bFullMutex = 1;
112302       break;
112303     }
112304     case SQLCIPHER_CONFIG_MUTEX: {
112305       /* Specify an alternative mutex implementation */
112306       sqlcipher3GlobalConfig.mutex = *va_arg(ap, sqlcipher3_mutex_methods*);
112307       break;
112308     }
112309     case SQLCIPHER_CONFIG_GETMUTEX: {
112310       /* Retrieve the current mutex implementation */
112311       *va_arg(ap, sqlcipher3_mutex_methods*) = sqlcipher3GlobalConfig.mutex;
112312       break;
112313     }
112314 #endif
112315
112316
112317     case SQLCIPHER_CONFIG_MALLOC: {
112318       /* Specify an alternative malloc implementation */
112319       sqlcipher3GlobalConfig.m = *va_arg(ap, sqlcipher3_mem_methods*);
112320       break;
112321     }
112322     case SQLCIPHER_CONFIG_GETMALLOC: {
112323       /* Retrieve the current malloc() implementation */
112324       if( sqlcipher3GlobalConfig.m.xMalloc==0 ) sqlcipher3MemSetDefault();
112325       *va_arg(ap, sqlcipher3_mem_methods*) = sqlcipher3GlobalConfig.m;
112326       break;
112327     }
112328     case SQLCIPHER_CONFIG_MEMSTATUS: {
112329       /* Enable or disable the malloc status collection */
112330       sqlcipher3GlobalConfig.bMemstat = va_arg(ap, int);
112331       break;
112332     }
112333     case SQLCIPHER_CONFIG_SCRATCH: {
112334       /* Designate a buffer for scratch memory space */
112335       sqlcipher3GlobalConfig.pScratch = va_arg(ap, void*);
112336       sqlcipher3GlobalConfig.szScratch = va_arg(ap, int);
112337       sqlcipher3GlobalConfig.nScratch = va_arg(ap, int);
112338       break;
112339     }
112340     case SQLCIPHER_CONFIG_PAGECACHE: {
112341       /* Designate a buffer for page cache memory space */
112342       sqlcipher3GlobalConfig.pPage = va_arg(ap, void*);
112343       sqlcipher3GlobalConfig.szPage = va_arg(ap, int);
112344       sqlcipher3GlobalConfig.nPage = va_arg(ap, int);
112345       break;
112346     }
112347
112348     case SQLCIPHER_CONFIG_PCACHE: {
112349       /* Specify an alternative page cache implementation */
112350       sqlcipher3GlobalConfig.pcache = *va_arg(ap, sqlcipher3_pcache_methods*);
112351       break;
112352     }
112353
112354     case SQLCIPHER_CONFIG_GETPCACHE: {
112355       if( sqlcipher3GlobalConfig.pcache.xInit==0 ){
112356         sqlcipher3PCacheSetDefault();
112357       }
112358       *va_arg(ap, sqlcipher3_pcache_methods*) = sqlcipher3GlobalConfig.pcache;
112359       break;
112360     }
112361
112362 #if defined(SQLCIPHER_ENABLE_MEMSYS3) || defined(SQLCIPHER_ENABLE_MEMSYS5)
112363     case SQLCIPHER_CONFIG_HEAP: {
112364       /* Designate a buffer for heap memory space */
112365       sqlcipher3GlobalConfig.pHeap = va_arg(ap, void*);
112366       sqlcipher3GlobalConfig.nHeap = va_arg(ap, int);
112367       sqlcipher3GlobalConfig.mnReq = va_arg(ap, int);
112368
112369       if( sqlcipher3GlobalConfig.mnReq<1 ){
112370         sqlcipher3GlobalConfig.mnReq = 1;
112371       }else if( sqlcipher3GlobalConfig.mnReq>(1<<12) ){
112372         /* cap min request size at 2^12 */
112373         sqlcipher3GlobalConfig.mnReq = (1<<12);
112374       }
112375
112376       if( sqlcipher3GlobalConfig.pHeap==0 ){
112377         /* If the heap pointer is NULL, then restore the malloc implementation
112378         ** back to NULL pointers too.  This will cause the malloc to go
112379         ** back to its default implementation when sqlcipher3_initialize() is
112380         ** run.
112381         */
112382         memset(&sqlcipher3GlobalConfig.m, 0, sizeof(sqlcipher3GlobalConfig.m));
112383       }else{
112384         /* The heap pointer is not NULL, then install one of the
112385         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
112386         ** ENABLE_MEMSYS5 is defined, return an error.
112387         */
112388 #ifdef SQLCIPHER_ENABLE_MEMSYS3
112389         sqlcipher3GlobalConfig.m = *sqlcipher3MemGetMemsys3();
112390 #endif
112391 #ifdef SQLCIPHER_ENABLE_MEMSYS5
112392         sqlcipher3GlobalConfig.m = *sqlcipher3MemGetMemsys5();
112393 #endif
112394       }
112395       break;
112396     }
112397 #endif
112398
112399     case SQLCIPHER_CONFIG_LOOKASIDE: {
112400       sqlcipher3GlobalConfig.szLookaside = va_arg(ap, int);
112401       sqlcipher3GlobalConfig.nLookaside = va_arg(ap, int);
112402       break;
112403     }
112404     
112405     /* Record a pointer to the logger funcction and its first argument.
112406     ** The default is NULL.  Logging is disabled if the function pointer is
112407     ** NULL.
112408     */
112409     case SQLCIPHER_CONFIG_LOG: {
112410       /* MSVC is picky about pulling func ptrs from va lists.
112411       ** http://support.microsoft.com/kb/47961
112412       ** sqlcipher3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
112413       */
112414       typedef void(*LOGFUNC_t)(void*,int,const char*);
112415       sqlcipher3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
112416       sqlcipher3GlobalConfig.pLogArg = va_arg(ap, void*);
112417       break;
112418     }
112419
112420     case SQLCIPHER_CONFIG_URI: {
112421       sqlcipher3GlobalConfig.bOpenUri = va_arg(ap, int);
112422       break;
112423     }
112424
112425     default: {
112426       rc = SQLCIPHER_ERROR;
112427       break;
112428     }
112429   }
112430   va_end(ap);
112431   return rc;
112432 }
112433
112434 /*
112435 ** Set up the lookaside buffers for a database connection.
112436 ** Return SQLCIPHER_OK on success.  
112437 ** If lookaside is already active, return SQLCIPHER_BUSY.
112438 **
112439 ** The sz parameter is the number of bytes in each lookaside slot.
112440 ** The cnt parameter is the number of slots.  If pStart is NULL the
112441 ** space for the lookaside memory is obtained from sqlcipher3_malloc().
112442 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
112443 ** the lookaside memory.
112444 */
112445 static int setupLookaside(sqlcipher3 *db, void *pBuf, int sz, int cnt){
112446   void *pStart;
112447   if( db->lookaside.nOut ){
112448     return SQLCIPHER_BUSY;
112449   }
112450   /* Free any existing lookaside buffer for this handle before
112451   ** allocating a new one so we don't have to have space for 
112452   ** both at the same time.
112453   */
112454   if( db->lookaside.bMalloced ){
112455     sqlcipher3_free(db->lookaside.pStart);
112456   }
112457   /* The size of a lookaside slot needs to be larger than a pointer
112458   ** to be useful.
112459   */
112460   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
112461   if( cnt<0 ) cnt = 0;
112462   if( sz==0 || cnt==0 ){
112463     sz = 0;
112464     pStart = 0;
112465   }else if( pBuf==0 ){
112466     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
112467     sqlcipher3BeginBenignMalloc();
112468     pStart = sqlcipher3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
112469     sqlcipher3EndBenignMalloc();
112470   }else{
112471     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
112472     pStart = pBuf;
112473   }
112474   db->lookaside.pStart = pStart;
112475   db->lookaside.pFree = 0;
112476   db->lookaside.sz = (u16)sz;
112477   if( pStart ){
112478     int i;
112479     LookasideSlot *p;
112480     assert( sz > (int)sizeof(LookasideSlot*) );
112481     p = (LookasideSlot*)pStart;
112482     for(i=cnt-1; i>=0; i--){
112483       p->pNext = db->lookaside.pFree;
112484       db->lookaside.pFree = p;
112485       p = (LookasideSlot*)&((u8*)p)[sz];
112486     }
112487     db->lookaside.pEnd = p;
112488     db->lookaside.bEnabled = 1;
112489     db->lookaside.bMalloced = pBuf==0 ?1:0;
112490   }else{
112491     db->lookaside.pEnd = 0;
112492     db->lookaside.bEnabled = 0;
112493     db->lookaside.bMalloced = 0;
112494   }
112495   return SQLCIPHER_OK;
112496 }
112497
112498 /*
112499 ** Return the mutex associated with a database connection.
112500 */
112501 SQLCIPHER_API sqlcipher3_mutex *sqlcipher3_db_mutex(sqlcipher3 *db){
112502   return db->mutex;
112503 }
112504
112505 /*
112506 ** Configuration settings for an individual database connection
112507 */
112508 SQLCIPHER_API int sqlcipher3_db_config(sqlcipher3 *db, int op, ...){
112509   va_list ap;
112510   int rc;
112511   va_start(ap, op);
112512   switch( op ){
112513     case SQLCIPHER_DBCONFIG_LOOKASIDE: {
112514       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
112515       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
112516       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
112517       rc = setupLookaside(db, pBuf, sz, cnt);
112518       break;
112519     }
112520     default: {
112521       static const struct {
112522         int op;      /* The opcode */
112523         u32 mask;    /* Mask of the bit in sqlcipher3.flags to set/clear */
112524       } aFlagOp[] = {
112525         { SQLCIPHER_DBCONFIG_ENABLE_FKEY,    SQLCIPHER_ForeignKeys    },
112526         { SQLCIPHER_DBCONFIG_ENABLE_TRIGGER, SQLCIPHER_EnableTrigger  },
112527       };
112528       unsigned int i;
112529       rc = SQLCIPHER_ERROR; /* IMP: R-42790-23372 */
112530       for(i=0; i<ArraySize(aFlagOp); i++){
112531         if( aFlagOp[i].op==op ){
112532           int onoff = va_arg(ap, int);
112533           int *pRes = va_arg(ap, int*);
112534           int oldFlags = db->flags;
112535           if( onoff>0 ){
112536             db->flags |= aFlagOp[i].mask;
112537           }else if( onoff==0 ){
112538             db->flags &= ~aFlagOp[i].mask;
112539           }
112540           if( oldFlags!=db->flags ){
112541             sqlcipher3ExpirePreparedStatements(db);
112542           }
112543           if( pRes ){
112544             *pRes = (db->flags & aFlagOp[i].mask)!=0;
112545           }
112546           rc = SQLCIPHER_OK;
112547           break;
112548         }
112549       }
112550       break;
112551     }
112552   }
112553   va_end(ap);
112554   return rc;
112555 }
112556
112557
112558 /*
112559 ** Return true if the buffer z[0..n-1] contains all spaces.
112560 */
112561 static int allSpaces(const char *z, int n){
112562   while( n>0 && z[n-1]==' ' ){ n--; }
112563   return n==0;
112564 }
112565
112566 /*
112567 ** This is the default collating function named "BINARY" which is always
112568 ** available.
112569 **
112570 ** If the padFlag argument is not NULL then space padding at the end
112571 ** of strings is ignored.  This implements the RTRIM collation.
112572 */
112573 static int binCollFunc(
112574   void *padFlag,
112575   int nKey1, const void *pKey1,
112576   int nKey2, const void *pKey2
112577 ){
112578   int rc, n;
112579   n = nKey1<nKey2 ? nKey1 : nKey2;
112580   rc = memcmp(pKey1, pKey2, n);
112581   if( rc==0 ){
112582     if( padFlag
112583      && allSpaces(((char*)pKey1)+n, nKey1-n)
112584      && allSpaces(((char*)pKey2)+n, nKey2-n)
112585     ){
112586       /* Leave rc unchanged at 0 */
112587     }else{
112588       rc = nKey1 - nKey2;
112589     }
112590   }
112591   return rc;
112592 }
112593
112594 /*
112595 ** Another built-in collating sequence: NOCASE. 
112596 **
112597 ** This collating sequence is intended to be used for "case independant
112598 ** comparison". SQLite's knowledge of upper and lower case equivalents
112599 ** extends only to the 26 characters used in the English language.
112600 **
112601 ** At the moment there is only a UTF-8 implementation.
112602 */
112603 static int nocaseCollatingFunc(
112604   void *NotUsed,
112605   int nKey1, const void *pKey1,
112606   int nKey2, const void *pKey2
112607 ){
112608   int r = sqlcipher3StrNICmp(
112609       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
112610   UNUSED_PARAMETER(NotUsed);
112611   if( 0==r ){
112612     r = nKey1-nKey2;
112613   }
112614   return r;
112615 }
112616
112617 /*
112618 ** Return the ROWID of the most recent insert
112619 */
112620 SQLCIPHER_API sqlcipher_int64 sqlcipher3_last_insert_rowid(sqlcipher3 *db){
112621   return db->lastRowid;
112622 }
112623
112624 /*
112625 ** Return the number of changes in the most recent call to sqlcipher3_exec().
112626 */
112627 SQLCIPHER_API int sqlcipher3_changes(sqlcipher3 *db){
112628   return db->nChange;
112629 }
112630
112631 /*
112632 ** Return the number of changes since the database handle was opened.
112633 */
112634 SQLCIPHER_API int sqlcipher3_total_changes(sqlcipher3 *db){
112635   return db->nTotalChange;
112636 }
112637
112638 /*
112639 ** Close all open savepoints. This function only manipulates fields of the
112640 ** database handle object, it does not close any savepoints that may be open
112641 ** at the b-tree/pager level.
112642 */
112643 SQLCIPHER_PRIVATE void sqlcipher3CloseSavepoints(sqlcipher3 *db){
112644   while( db->pSavepoint ){
112645     Savepoint *pTmp = db->pSavepoint;
112646     db->pSavepoint = pTmp->pNext;
112647     sqlcipher3DbFree(db, pTmp);
112648   }
112649   db->nSavepoint = 0;
112650   db->nStatement = 0;
112651   db->isTransactionSavepoint = 0;
112652 }
112653
112654 /*
112655 ** Invoke the destructor function associated with FuncDef p, if any. Except,
112656 ** if this is not the last copy of the function, do not invoke it. Multiple
112657 ** copies of a single function are created when create_function() is called
112658 ** with SQLCIPHER_ANY as the encoding.
112659 */
112660 static void functionDestroy(sqlcipher3 *db, FuncDef *p){
112661   FuncDestructor *pDestructor = p->pDestructor;
112662   if( pDestructor ){
112663     pDestructor->nRef--;
112664     if( pDestructor->nRef==0 ){
112665       pDestructor->xDestroy(pDestructor->pUserData);
112666       sqlcipher3DbFree(db, pDestructor);
112667     }
112668   }
112669 }
112670
112671 /*
112672 ** Close an existing SQLite database
112673 */
112674 SQLCIPHER_API int sqlcipher3_close(sqlcipher3 *db){
112675   HashElem *i;                    /* Hash table iterator */
112676   int j;
112677
112678   if( !db ){
112679     return SQLCIPHER_OK;
112680   }
112681   if( !sqlcipher3SafetyCheckSickOrOk(db) ){
112682     return SQLCIPHER_MISUSE_BKPT;
112683   }
112684   sqlcipher3_mutex_enter(db->mutex);
112685
112686   /* Force xDestroy calls on all virtual tables */
112687   sqlcipher3ResetInternalSchema(db, -1);
112688
112689   /* If a transaction is open, the ResetInternalSchema() call above
112690   ** will not have called the xDisconnect() method on any virtual
112691   ** tables in the db->aVTrans[] array. The following sqlcipher3VtabRollback()
112692   ** call will do so. We need to do this before the check for active
112693   ** SQL statements below, as the v-table implementation may be storing
112694   ** some prepared statements internally.
112695   */
112696   sqlcipher3VtabRollback(db);
112697
112698   /* If there are any outstanding VMs, return SQLCIPHER_BUSY. */
112699   if( db->pVdbe ){
112700     sqlcipher3Error(db, SQLCIPHER_BUSY, 
112701         "unable to close due to unfinalised statements");
112702     sqlcipher3_mutex_leave(db->mutex);
112703     return SQLCIPHER_BUSY;
112704   }
112705   assert( sqlcipher3SafetyCheckSickOrOk(db) );
112706
112707   for(j=0; j<db->nDb; j++){
112708     Btree *pBt = db->aDb[j].pBt;
112709     if( pBt && sqlcipher3BtreeIsInBackup(pBt) ){
112710       sqlcipher3Error(db, SQLCIPHER_BUSY, 
112711           "unable to close due to unfinished backup operation");
112712       sqlcipher3_mutex_leave(db->mutex);
112713       return SQLCIPHER_BUSY;
112714     }
112715   }
112716
112717   /* Free any outstanding Savepoint structures. */
112718   sqlcipher3CloseSavepoints(db);
112719
112720   for(j=0; j<db->nDb; j++){
112721     struct Db *pDb = &db->aDb[j];
112722     if( pDb->pBt ){
112723       sqlcipher3BtreeClose(pDb->pBt);
112724       pDb->pBt = 0;
112725       if( j!=1 ){
112726         pDb->pSchema = 0;
112727       }
112728     }
112729   }
112730   sqlcipher3ResetInternalSchema(db, -1);
112731
112732   /* Tell the code in notify.c that the connection no longer holds any
112733   ** locks and does not require any further unlock-notify callbacks.
112734   */
112735   sqlcipher3ConnectionClosed(db);
112736
112737   assert( db->nDb<=2 );
112738   assert( db->aDb==db->aDbStatic );
112739   for(j=0; j<ArraySize(db->aFunc.a); j++){
112740     FuncDef *pNext, *pHash, *p;
112741     for(p=db->aFunc.a[j]; p; p=pHash){
112742       pHash = p->pHash;
112743       while( p ){
112744         functionDestroy(db, p);
112745         pNext = p->pNext;
112746         sqlcipher3DbFree(db, p);
112747         p = pNext;
112748       }
112749     }
112750   }
112751   for(i=sqlcipherHashFirst(&db->aCollSeq); i; i=sqlcipherHashNext(i)){
112752     CollSeq *pColl = (CollSeq *)sqlcipherHashData(i);
112753     /* Invoke any destructors registered for collation sequence user data. */
112754     for(j=0; j<3; j++){
112755       if( pColl[j].xDel ){
112756         pColl[j].xDel(pColl[j].pUser);
112757       }
112758     }
112759     sqlcipher3DbFree(db, pColl);
112760   }
112761   sqlcipher3HashClear(&db->aCollSeq);
112762 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
112763   for(i=sqlcipherHashFirst(&db->aModule); i; i=sqlcipherHashNext(i)){
112764     Module *pMod = (Module *)sqlcipherHashData(i);
112765     if( pMod->xDestroy ){
112766       pMod->xDestroy(pMod->pAux);
112767     }
112768     sqlcipher3DbFree(db, pMod);
112769   }
112770   sqlcipher3HashClear(&db->aModule);
112771 #endif
112772
112773   sqlcipher3Error(db, SQLCIPHER_OK, 0); /* Deallocates any cached error strings. */
112774   if( db->pErr ){
112775     sqlcipher3ValueFree(db->pErr);
112776   }
112777   sqlcipher3CloseExtensions(db);
112778
112779   db->magic = SQLCIPHER_MAGIC_ERROR;
112780
112781   /* The temp-database schema is allocated differently from the other schema
112782   ** objects (using sqlcipherMalloc() directly, instead of sqlcipher3BtreeSchema()).
112783   ** So it needs to be freed here. Todo: Why not roll the temp schema into
112784   ** the same sqlcipherMalloc() as the one that allocates the database 
112785   ** structure?
112786   */
112787   sqlcipher3DbFree(db, db->aDb[1].pSchema);
112788   sqlcipher3_mutex_leave(db->mutex);
112789   db->magic = SQLCIPHER_MAGIC_CLOSED;
112790   sqlcipher3_mutex_free(db->mutex);
112791   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
112792   if( db->lookaside.bMalloced ){
112793     sqlcipher3_free(db->lookaside.pStart);
112794   }
112795   sqlcipher3_free(db);
112796   return SQLCIPHER_OK;
112797 }
112798
112799 /*
112800 ** Rollback all database files.
112801 */
112802 SQLCIPHER_PRIVATE void sqlcipher3RollbackAll(sqlcipher3 *db){
112803   int i;
112804   int inTrans = 0;
112805   assert( sqlcipher3_mutex_held(db->mutex) );
112806   sqlcipher3BeginBenignMalloc();
112807   for(i=0; i<db->nDb; i++){
112808     if( db->aDb[i].pBt ){
112809       if( sqlcipher3BtreeIsInTrans(db->aDb[i].pBt) ){
112810         inTrans = 1;
112811       }
112812       sqlcipher3BtreeRollback(db->aDb[i].pBt);
112813       db->aDb[i].inTrans = 0;
112814     }
112815   }
112816   sqlcipher3VtabRollback(db);
112817   sqlcipher3EndBenignMalloc();
112818
112819   if( db->flags&SQLCIPHER_InternChanges ){
112820     sqlcipher3ExpirePreparedStatements(db);
112821     sqlcipher3ResetInternalSchema(db, -1);
112822   }
112823
112824   /* Any deferred constraint violations have now been resolved. */
112825   db->nDeferredCons = 0;
112826
112827   /* If one has been configured, invoke the rollback-hook callback */
112828   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
112829     db->xRollbackCallback(db->pRollbackArg);
112830   }
112831 }
112832
112833 /*
112834 ** Return a static string that describes the kind of error specified in the
112835 ** argument.
112836 */
112837 SQLCIPHER_PRIVATE const char *sqlcipher3ErrStr(int rc){
112838   static const char* const aMsg[] = {
112839     /* SQLCIPHER_OK          */ "not an error",
112840     /* SQLCIPHER_ERROR       */ "SQL logic error or missing database",
112841     /* SQLCIPHER_INTERNAL    */ 0,
112842     /* SQLCIPHER_PERM        */ "access permission denied",
112843     /* SQLCIPHER_ABORT       */ "callback requested query abort",
112844     /* SQLCIPHER_BUSY        */ "database is locked",
112845     /* SQLCIPHER_LOCKED      */ "database table is locked",
112846     /* SQLCIPHER_NOMEM       */ "out of memory",
112847     /* SQLCIPHER_READONLY    */ "attempt to write a readonly database",
112848     /* SQLCIPHER_INTERRUPT   */ "interrupted",
112849     /* SQLCIPHER_IOERR       */ "disk I/O error",
112850     /* SQLCIPHER_CORRUPT     */ "database disk image is malformed",
112851     /* SQLCIPHER_NOTFOUND    */ "unknown operation",
112852     /* SQLCIPHER_FULL        */ "database or disk is full",
112853     /* SQLCIPHER_CANTOPEN    */ "unable to open database file",
112854     /* SQLCIPHER_PROTOCOL    */ "locking protocol",
112855     /* SQLCIPHER_EMPTY       */ "table contains no data",
112856     /* SQLCIPHER_SCHEMA      */ "database schema has changed",
112857     /* SQLCIPHER_TOOBIG      */ "string or blob too big",
112858     /* SQLCIPHER_CONSTRAINT  */ "constraint failed",
112859     /* SQLCIPHER_MISMATCH    */ "datatype mismatch",
112860     /* SQLCIPHER_MISUSE      */ "library routine called out of sequence",
112861     /* SQLCIPHER_NOLFS       */ "large file support is disabled",
112862     /* SQLCIPHER_AUTH        */ "authorization denied",
112863     /* SQLCIPHER_FORMAT      */ "auxiliary database format error",
112864     /* SQLCIPHER_RANGE       */ "bind or column index out of range",
112865     /* SQLCIPHER_NOTADB      */ "file is encrypted or is not a database",
112866   };
112867   rc &= 0xff;
112868   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
112869     return aMsg[rc];
112870   }else{
112871     return "unknown error";
112872   }
112873 }
112874
112875 /*
112876 ** This routine implements a busy callback that sleeps and tries
112877 ** again until a timeout value is reached.  The timeout value is
112878 ** an integer number of milliseconds passed in as the first
112879 ** argument.
112880 */
112881 static int sqlcipherDefaultBusyCallback(
112882  void *ptr,               /* Database connection */
112883  int count                /* Number of times table has been busy */
112884 ){
112885 #if SQLCIPHER_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
112886   static const u8 delays[] =
112887      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
112888   static const u8 totals[] =
112889      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
112890 # define NDELAY ArraySize(delays)
112891   sqlcipher3 *db = (sqlcipher3 *)ptr;
112892   int timeout = db->busyTimeout;
112893   int delay, prior;
112894
112895   assert( count>=0 );
112896   if( count < NDELAY ){
112897     delay = delays[count];
112898     prior = totals[count];
112899   }else{
112900     delay = delays[NDELAY-1];
112901     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
112902   }
112903   if( prior + delay > timeout ){
112904     delay = timeout - prior;
112905     if( delay<=0 ) return 0;
112906   }
112907   sqlcipher3OsSleep(db->pVfs, delay*1000);
112908   return 1;
112909 #else
112910   sqlcipher3 *db = (sqlcipher3 *)ptr;
112911   int timeout = ((sqlcipher3 *)ptr)->busyTimeout;
112912   if( (count+1)*1000 > timeout ){
112913     return 0;
112914   }
112915   sqlcipher3OsSleep(db->pVfs, 1000000);
112916   return 1;
112917 #endif
112918 }
112919
112920 /*
112921 ** Invoke the given busy handler.
112922 **
112923 ** This routine is called when an operation failed with a lock.
112924 ** If this routine returns non-zero, the lock is retried.  If it
112925 ** returns 0, the operation aborts with an SQLCIPHER_BUSY error.
112926 */
112927 SQLCIPHER_PRIVATE int sqlcipher3InvokeBusyHandler(BusyHandler *p){
112928   int rc;
112929   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
112930   rc = p->xFunc(p->pArg, p->nBusy);
112931   if( rc==0 ){
112932     p->nBusy = -1;
112933   }else{
112934     p->nBusy++;
112935   }
112936   return rc; 
112937 }
112938
112939 /*
112940 ** This routine sets the busy callback for an Sqlite database to the
112941 ** given callback function with the given argument.
112942 */
112943 SQLCIPHER_API int sqlcipher3_busy_handler(
112944   sqlcipher3 *db,
112945   int (*xBusy)(void*,int),
112946   void *pArg
112947 ){
112948   sqlcipher3_mutex_enter(db->mutex);
112949   db->busyHandler.xFunc = xBusy;
112950   db->busyHandler.pArg = pArg;
112951   db->busyHandler.nBusy = 0;
112952   sqlcipher3_mutex_leave(db->mutex);
112953   return SQLCIPHER_OK;
112954 }
112955
112956 #ifndef SQLCIPHER_OMIT_PROGRESS_CALLBACK
112957 /*
112958 ** This routine sets the progress callback for an Sqlite database to the
112959 ** given callback function with the given argument. The progress callback will
112960 ** be invoked every nOps opcodes.
112961 */
112962 SQLCIPHER_API void sqlcipher3_progress_handler(
112963   sqlcipher3 *db, 
112964   int nOps,
112965   int (*xProgress)(void*), 
112966   void *pArg
112967 ){
112968   sqlcipher3_mutex_enter(db->mutex);
112969   if( nOps>0 ){
112970     db->xProgress = xProgress;
112971     db->nProgressOps = nOps;
112972     db->pProgressArg = pArg;
112973   }else{
112974     db->xProgress = 0;
112975     db->nProgressOps = 0;
112976     db->pProgressArg = 0;
112977   }
112978   sqlcipher3_mutex_leave(db->mutex);
112979 }
112980 #endif
112981
112982
112983 /*
112984 ** This routine installs a default busy handler that waits for the
112985 ** specified number of milliseconds before returning 0.
112986 */
112987 SQLCIPHER_API int sqlcipher3_busy_timeout(sqlcipher3 *db, int ms){
112988   if( ms>0 ){
112989     db->busyTimeout = ms;
112990     sqlcipher3_busy_handler(db, sqlcipherDefaultBusyCallback, (void*)db);
112991   }else{
112992     sqlcipher3_busy_handler(db, 0, 0);
112993   }
112994   return SQLCIPHER_OK;
112995 }
112996
112997 /*
112998 ** Cause any pending operation to stop at its earliest opportunity.
112999 */
113000 SQLCIPHER_API void sqlcipher3_interrupt(sqlcipher3 *db){
113001   db->u1.isInterrupted = 1;
113002 }
113003
113004
113005 /*
113006 ** This function is exactly the same as sqlcipher3_create_function(), except
113007 ** that it is designed to be called by internal code. The difference is
113008 ** that if a malloc() fails in sqlcipher3_create_function(), an error code
113009 ** is returned and the mallocFailed flag cleared. 
113010 */
113011 SQLCIPHER_PRIVATE int sqlcipher3CreateFunc(
113012   sqlcipher3 *db,
113013   const char *zFunctionName,
113014   int nArg,
113015   int enc,
113016   void *pUserData,
113017   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value **),
113018   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value **),
113019   void (*xFinal)(sqlcipher3_context*),
113020   FuncDestructor *pDestructor
113021 ){
113022   FuncDef *p;
113023   int nName;
113024
113025   assert( sqlcipher3_mutex_held(db->mutex) );
113026   if( zFunctionName==0 ||
113027       (xFunc && (xFinal || xStep)) || 
113028       (!xFunc && (xFinal && !xStep)) ||
113029       (!xFunc && (!xFinal && xStep)) ||
113030       (nArg<-1 || nArg>SQLCIPHER_MAX_FUNCTION_ARG) ||
113031       (255<(nName = sqlcipher3Strlen30( zFunctionName))) ){
113032     return SQLCIPHER_MISUSE_BKPT;
113033   }
113034   
113035 #ifndef SQLCIPHER_OMIT_UTF16
113036   /* If SQLCIPHER_UTF16 is specified as the encoding type, transform this
113037   ** to one of SQLCIPHER_UTF16LE or SQLCIPHER_UTF16BE using the
113038   ** SQLCIPHER_UTF16NATIVE macro. SQLCIPHER_UTF16 is not used internally.
113039   **
113040   ** If SQLCIPHER_ANY is specified, add three versions of the function
113041   ** to the hash table.
113042   */
113043   if( enc==SQLCIPHER_UTF16 ){
113044     enc = SQLCIPHER_UTF16NATIVE;
113045   }else if( enc==SQLCIPHER_ANY ){
113046     int rc;
113047     rc = sqlcipher3CreateFunc(db, zFunctionName, nArg, SQLCIPHER_UTF8,
113048          pUserData, xFunc, xStep, xFinal, pDestructor);
113049     if( rc==SQLCIPHER_OK ){
113050       rc = sqlcipher3CreateFunc(db, zFunctionName, nArg, SQLCIPHER_UTF16LE,
113051           pUserData, xFunc, xStep, xFinal, pDestructor);
113052     }
113053     if( rc!=SQLCIPHER_OK ){
113054       return rc;
113055     }
113056     enc = SQLCIPHER_UTF16BE;
113057   }
113058 #else
113059   enc = SQLCIPHER_UTF8;
113060 #endif
113061   
113062   /* Check if an existing function is being overridden or deleted. If so,
113063   ** and there are active VMs, then return SQLCIPHER_BUSY. If a function
113064   ** is being overridden/deleted but there are no active VMs, allow the
113065   ** operation to continue but invalidate all precompiled statements.
113066   */
113067   p = sqlcipher3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
113068   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
113069     if( db->activeVdbeCnt ){
113070       sqlcipher3Error(db, SQLCIPHER_BUSY, 
113071         "unable to delete/modify user-function due to active statements");
113072       assert( !db->mallocFailed );
113073       return SQLCIPHER_BUSY;
113074     }else{
113075       sqlcipher3ExpirePreparedStatements(db);
113076     }
113077   }
113078
113079   p = sqlcipher3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
113080   assert(p || db->mallocFailed);
113081   if( !p ){
113082     return SQLCIPHER_NOMEM;
113083   }
113084
113085   /* If an older version of the function with a configured destructor is
113086   ** being replaced invoke the destructor function here. */
113087   functionDestroy(db, p);
113088
113089   if( pDestructor ){
113090     pDestructor->nRef++;
113091   }
113092   p->pDestructor = pDestructor;
113093   p->flags = 0;
113094   p->xFunc = xFunc;
113095   p->xStep = xStep;
113096   p->xFinalize = xFinal;
113097   p->pUserData = pUserData;
113098   p->nArg = (u16)nArg;
113099   return SQLCIPHER_OK;
113100 }
113101
113102 /*
113103 ** Create new user functions.
113104 */
113105 SQLCIPHER_API int sqlcipher3_create_function(
113106   sqlcipher3 *db,
113107   const char *zFunc,
113108   int nArg,
113109   int enc,
113110   void *p,
113111   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value **),
113112   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value **),
113113   void (*xFinal)(sqlcipher3_context*)
113114 ){
113115   return sqlcipher3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
113116                                     xFinal, 0);
113117 }
113118
113119 SQLCIPHER_API int sqlcipher3_create_function_v2(
113120   sqlcipher3 *db,
113121   const char *zFunc,
113122   int nArg,
113123   int enc,
113124   void *p,
113125   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value **),
113126   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value **),
113127   void (*xFinal)(sqlcipher3_context*),
113128   void (*xDestroy)(void *)
113129 ){
113130   int rc = SQLCIPHER_ERROR;
113131   FuncDestructor *pArg = 0;
113132   sqlcipher3_mutex_enter(db->mutex);
113133   if( xDestroy ){
113134     pArg = (FuncDestructor *)sqlcipher3DbMallocZero(db, sizeof(FuncDestructor));
113135     if( !pArg ){
113136       xDestroy(p);
113137       goto out;
113138     }
113139     pArg->xDestroy = xDestroy;
113140     pArg->pUserData = p;
113141   }
113142   rc = sqlcipher3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
113143   if( pArg && pArg->nRef==0 ){
113144     assert( rc!=SQLCIPHER_OK );
113145     xDestroy(p);
113146     sqlcipher3DbFree(db, pArg);
113147   }
113148
113149  out:
113150   rc = sqlcipher3ApiExit(db, rc);
113151   sqlcipher3_mutex_leave(db->mutex);
113152   return rc;
113153 }
113154
113155 #ifndef SQLCIPHER_OMIT_UTF16
113156 SQLCIPHER_API int sqlcipher3_create_function16(
113157   sqlcipher3 *db,
113158   const void *zFunctionName,
113159   int nArg,
113160   int eTextRep,
113161   void *p,
113162   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
113163   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
113164   void (*xFinal)(sqlcipher3_context*)
113165 ){
113166   int rc;
113167   char *zFunc8;
113168   sqlcipher3_mutex_enter(db->mutex);
113169   assert( !db->mallocFailed );
113170   zFunc8 = sqlcipher3Utf16to8(db, zFunctionName, -1, SQLCIPHER_UTF16NATIVE);
113171   rc = sqlcipher3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
113172   sqlcipher3DbFree(db, zFunc8);
113173   rc = sqlcipher3ApiExit(db, rc);
113174   sqlcipher3_mutex_leave(db->mutex);
113175   return rc;
113176 }
113177 #endif
113178
113179
113180 /*
113181 ** Declare that a function has been overloaded by a virtual table.
113182 **
113183 ** If the function already exists as a regular global function, then
113184 ** this routine is a no-op.  If the function does not exist, then create
113185 ** a new one that always throws a run-time error.  
113186 **
113187 ** When virtual tables intend to provide an overloaded function, they
113188 ** should call this routine to make sure the global function exists.
113189 ** A global function must exist in order for name resolution to work
113190 ** properly.
113191 */
113192 SQLCIPHER_API int sqlcipher3_overload_function(
113193   sqlcipher3 *db,
113194   const char *zName,
113195   int nArg
113196 ){
113197   int nName = sqlcipher3Strlen30(zName);
113198   int rc = SQLCIPHER_OK;
113199   sqlcipher3_mutex_enter(db->mutex);
113200   if( sqlcipher3FindFunction(db, zName, nName, nArg, SQLCIPHER_UTF8, 0)==0 ){
113201     rc = sqlcipher3CreateFunc(db, zName, nArg, SQLCIPHER_UTF8,
113202                            0, sqlcipher3InvalidFunction, 0, 0, 0);
113203   }
113204   rc = sqlcipher3ApiExit(db, rc);
113205   sqlcipher3_mutex_leave(db->mutex);
113206   return rc;
113207 }
113208
113209 #ifndef SQLCIPHER_OMIT_TRACE
113210 /*
113211 ** Register a trace function.  The pArg from the previously registered trace
113212 ** is returned.  
113213 **
113214 ** A NULL trace function means that no tracing is executes.  A non-NULL
113215 ** trace is a pointer to a function that is invoked at the start of each
113216 ** SQL statement.
113217 */
113218 SQLCIPHER_API void *sqlcipher3_trace(sqlcipher3 *db, void (*xTrace)(void*,const char*), void *pArg){
113219   void *pOld;
113220   sqlcipher3_mutex_enter(db->mutex);
113221   pOld = db->pTraceArg;
113222   db->xTrace = xTrace;
113223   db->pTraceArg = pArg;
113224   sqlcipher3_mutex_leave(db->mutex);
113225   return pOld;
113226 }
113227 /*
113228 ** Register a profile function.  The pArg from the previously registered 
113229 ** profile function is returned.  
113230 **
113231 ** A NULL profile function means that no profiling is executes.  A non-NULL
113232 ** profile is a pointer to a function that is invoked at the conclusion of
113233 ** each SQL statement that is run.
113234 */
113235 SQLCIPHER_API void *sqlcipher3_profile(
113236   sqlcipher3 *db,
113237   void (*xProfile)(void*,const char*,sqlcipher_uint64),
113238   void *pArg
113239 ){
113240   void *pOld;
113241   sqlcipher3_mutex_enter(db->mutex);
113242   pOld = db->pProfileArg;
113243   db->xProfile = xProfile;
113244   db->pProfileArg = pArg;
113245   sqlcipher3_mutex_leave(db->mutex);
113246   return pOld;
113247 }
113248 #endif /* SQLCIPHER_OMIT_TRACE */
113249
113250 /*** EXPERIMENTAL ***
113251 **
113252 ** Register a function to be invoked when a transaction comments.
113253 ** If the invoked function returns non-zero, then the commit becomes a
113254 ** rollback.
113255 */
113256 SQLCIPHER_API void *sqlcipher3_commit_hook(
113257   sqlcipher3 *db,              /* Attach the hook to this database */
113258   int (*xCallback)(void*),  /* Function to invoke on each commit */
113259   void *pArg                /* Argument to the function */
113260 ){
113261   void *pOld;
113262   sqlcipher3_mutex_enter(db->mutex);
113263   pOld = db->pCommitArg;
113264   db->xCommitCallback = xCallback;
113265   db->pCommitArg = pArg;
113266   sqlcipher3_mutex_leave(db->mutex);
113267   return pOld;
113268 }
113269
113270 /*
113271 ** Register a callback to be invoked each time a row is updated,
113272 ** inserted or deleted using this database connection.
113273 */
113274 SQLCIPHER_API void *sqlcipher3_update_hook(
113275   sqlcipher3 *db,              /* Attach the hook to this database */
113276   void (*xCallback)(void*,int,char const *,char const *,sqlcipher_int64),
113277   void *pArg                /* Argument to the function */
113278 ){
113279   void *pRet;
113280   sqlcipher3_mutex_enter(db->mutex);
113281   pRet = db->pUpdateArg;
113282   db->xUpdateCallback = xCallback;
113283   db->pUpdateArg = pArg;
113284   sqlcipher3_mutex_leave(db->mutex);
113285   return pRet;
113286 }
113287
113288 /*
113289 ** Register a callback to be invoked each time a transaction is rolled
113290 ** back by this database connection.
113291 */
113292 SQLCIPHER_API void *sqlcipher3_rollback_hook(
113293   sqlcipher3 *db,              /* Attach the hook to this database */
113294   void (*xCallback)(void*), /* Callback function */
113295   void *pArg                /* Argument to the function */
113296 ){
113297   void *pRet;
113298   sqlcipher3_mutex_enter(db->mutex);
113299   pRet = db->pRollbackArg;
113300   db->xRollbackCallback = xCallback;
113301   db->pRollbackArg = pArg;
113302   sqlcipher3_mutex_leave(db->mutex);
113303   return pRet;
113304 }
113305
113306 #ifndef SQLCIPHER_OMIT_WAL
113307 /*
113308 ** The sqlcipher3_wal_hook() callback registered by sqlcipher3_wal_autocheckpoint().
113309 ** Invoke sqlcipher3_wal_checkpoint if the number of frames in the log file
113310 ** is greater than sqlcipher3.pWalArg cast to an integer (the value configured by
113311 ** wal_autocheckpoint()).
113312 */ 
113313 SQLCIPHER_PRIVATE int sqlcipher3WalDefaultHook(
113314   void *pClientData,     /* Argument */
113315   sqlcipher3 *db,           /* Connection */
113316   const char *zDb,       /* Database */
113317   int nFrame             /* Size of WAL */
113318 ){
113319   if( nFrame>=SQLCIPHER_PTR_TO_INT(pClientData) ){
113320     sqlcipher3BeginBenignMalloc();
113321     sqlcipher3_wal_checkpoint(db, zDb);
113322     sqlcipher3EndBenignMalloc();
113323   }
113324   return SQLCIPHER_OK;
113325 }
113326 #endif /* SQLCIPHER_OMIT_WAL */
113327
113328 /*
113329 ** Configure an sqlcipher3_wal_hook() callback to automatically checkpoint
113330 ** a database after committing a transaction if there are nFrame or
113331 ** more frames in the log file. Passing zero or a negative value as the
113332 ** nFrame parameter disables automatic checkpoints entirely.
113333 **
113334 ** The callback registered by this function replaces any existing callback
113335 ** registered using sqlcipher3_wal_hook(). Likewise, registering a callback
113336 ** using sqlcipher3_wal_hook() disables the automatic checkpoint mechanism
113337 ** configured by this function.
113338 */
113339 SQLCIPHER_API int sqlcipher3_wal_autocheckpoint(sqlcipher3 *db, int nFrame){
113340 #ifdef SQLCIPHER_OMIT_WAL
113341   UNUSED_PARAMETER(db);
113342   UNUSED_PARAMETER(nFrame);
113343 #else
113344   if( nFrame>0 ){
113345     sqlcipher3_wal_hook(db, sqlcipher3WalDefaultHook, SQLCIPHER_INT_TO_PTR(nFrame));
113346   }else{
113347     sqlcipher3_wal_hook(db, 0, 0);
113348   }
113349 #endif
113350   return SQLCIPHER_OK;
113351 }
113352
113353 /*
113354 ** Register a callback to be invoked each time a transaction is written
113355 ** into the write-ahead-log by this database connection.
113356 */
113357 SQLCIPHER_API void *sqlcipher3_wal_hook(
113358   sqlcipher3 *db,                    /* Attach the hook to this db handle */
113359   int(*xCallback)(void *, sqlcipher3*, const char*, int),
113360   void *pArg                      /* First argument passed to xCallback() */
113361 ){
113362 #ifndef SQLCIPHER_OMIT_WAL
113363   void *pRet;
113364   sqlcipher3_mutex_enter(db->mutex);
113365   pRet = db->pWalArg;
113366   db->xWalCallback = xCallback;
113367   db->pWalArg = pArg;
113368   sqlcipher3_mutex_leave(db->mutex);
113369   return pRet;
113370 #else
113371   return 0;
113372 #endif
113373 }
113374
113375 /*
113376 ** Checkpoint database zDb.
113377 */
113378 SQLCIPHER_API int sqlcipher3_wal_checkpoint_v2(
113379   sqlcipher3 *db,                    /* Database handle */
113380   const char *zDb,                /* Name of attached database (or NULL) */
113381   int eMode,                      /* SQLCIPHER_CHECKPOINT_* value */
113382   int *pnLog,                     /* OUT: Size of WAL log in frames */
113383   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
113384 ){
113385 #ifdef SQLCIPHER_OMIT_WAL
113386   return SQLCIPHER_OK;
113387 #else
113388   int rc;                         /* Return code */
113389   int iDb = SQLCIPHER_MAX_ATTACHED;  /* sqlcipher3.aDb[] index of db to checkpoint */
113390
113391   /* Initialize the output variables to -1 in case an error occurs. */
113392   if( pnLog ) *pnLog = -1;
113393   if( pnCkpt ) *pnCkpt = -1;
113394
113395   assert( SQLCIPHER_CHECKPOINT_FULL>SQLCIPHER_CHECKPOINT_PASSIVE );
113396   assert( SQLCIPHER_CHECKPOINT_FULL<SQLCIPHER_CHECKPOINT_RESTART );
113397   assert( SQLCIPHER_CHECKPOINT_PASSIVE+2==SQLCIPHER_CHECKPOINT_RESTART );
113398   if( eMode<SQLCIPHER_CHECKPOINT_PASSIVE || eMode>SQLCIPHER_CHECKPOINT_RESTART ){
113399     return SQLCIPHER_MISUSE;
113400   }
113401
113402   sqlcipher3_mutex_enter(db->mutex);
113403   if( zDb && zDb[0] ){
113404     iDb = sqlcipher3FindDbName(db, zDb);
113405   }
113406   if( iDb<0 ){
113407     rc = SQLCIPHER_ERROR;
113408     sqlcipher3Error(db, SQLCIPHER_ERROR, "unknown database: %s", zDb);
113409   }else{
113410     rc = sqlcipher3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
113411     sqlcipher3Error(db, rc, 0);
113412   }
113413   rc = sqlcipher3ApiExit(db, rc);
113414   sqlcipher3_mutex_leave(db->mutex);
113415   return rc;
113416 #endif
113417 }
113418
113419
113420 /*
113421 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
113422 ** to contains a zero-length string, all attached databases are 
113423 ** checkpointed.
113424 */
113425 SQLCIPHER_API int sqlcipher3_wal_checkpoint(sqlcipher3 *db, const char *zDb){
113426   return sqlcipher3_wal_checkpoint_v2(db, zDb, SQLCIPHER_CHECKPOINT_PASSIVE, 0, 0);
113427 }
113428
113429 #ifndef SQLCIPHER_OMIT_WAL
113430 /*
113431 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
113432 ** not currently open in WAL mode.
113433 **
113434 ** If a transaction is open on the database being checkpointed, this 
113435 ** function returns SQLCIPHER_LOCKED and a checkpoint is not attempted. If 
113436 ** an error occurs while running the checkpoint, an SQLite error code is 
113437 ** returned (i.e. SQLCIPHER_IOERR). Otherwise, SQLCIPHER_OK.
113438 **
113439 ** The mutex on database handle db should be held by the caller. The mutex
113440 ** associated with the specific b-tree being checkpointed is taken by
113441 ** this function while the checkpoint is running.
113442 **
113443 ** If iDb is passed SQLCIPHER_MAX_ATTACHED, then all attached databases are
113444 ** checkpointed. If an error is encountered it is returned immediately -
113445 ** no attempt is made to checkpoint any remaining databases.
113446 **
113447 ** Parameter eMode is one of SQLCIPHER_CHECKPOINT_PASSIVE, FULL or RESTART.
113448 */
113449 SQLCIPHER_PRIVATE int sqlcipher3Checkpoint(sqlcipher3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
113450   int rc = SQLCIPHER_OK;             /* Return code */
113451   int i;                          /* Used to iterate through attached dbs */
113452   int bBusy = 0;                  /* True if SQLCIPHER_BUSY has been encountered */
113453
113454   assert( sqlcipher3_mutex_held(db->mutex) );
113455   assert( !pnLog || *pnLog==-1 );
113456   assert( !pnCkpt || *pnCkpt==-1 );
113457
113458   for(i=0; i<db->nDb && rc==SQLCIPHER_OK; i++){
113459     if( i==iDb || iDb==SQLCIPHER_MAX_ATTACHED ){
113460       rc = sqlcipher3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
113461       pnLog = 0;
113462       pnCkpt = 0;
113463       if( rc==SQLCIPHER_BUSY ){
113464         bBusy = 1;
113465         rc = SQLCIPHER_OK;
113466       }
113467     }
113468   }
113469
113470   return (rc==SQLCIPHER_OK && bBusy) ? SQLCIPHER_BUSY : rc;
113471 }
113472 #endif /* SQLCIPHER_OMIT_WAL */
113473
113474 /*
113475 ** This function returns true if main-memory should be used instead of
113476 ** a temporary file for transient pager files and statement journals.
113477 ** The value returned depends on the value of db->temp_store (runtime
113478 ** parameter) and the compile time value of SQLCIPHER_TEMP_STORE. The
113479 ** following table describes the relationship between these two values
113480 ** and this functions return value.
113481 **
113482 **   SQLCIPHER_TEMP_STORE     db->temp_store     Location of temporary database
113483 **   -----------------     --------------     ------------------------------
113484 **   0                     any                file      (return 0)
113485 **   1                     1                  file      (return 0)
113486 **   1                     2                  memory    (return 1)
113487 **   1                     0                  file      (return 0)
113488 **   2                     1                  file      (return 0)
113489 **   2                     2                  memory    (return 1)
113490 **   2                     0                  memory    (return 1)
113491 **   3                     any                memory    (return 1)
113492 */
113493 SQLCIPHER_PRIVATE int sqlcipher3TempInMemory(const sqlcipher3 *db){
113494 #if SQLCIPHER_TEMP_STORE==1
113495   return ( db->temp_store==2 );
113496 #endif
113497 #if SQLCIPHER_TEMP_STORE==2
113498   return ( db->temp_store!=1 );
113499 #endif
113500 #if SQLCIPHER_TEMP_STORE==3
113501   return 1;
113502 #endif
113503 #if SQLCIPHER_TEMP_STORE<1 || SQLCIPHER_TEMP_STORE>3
113504   return 0;
113505 #endif
113506 }
113507
113508 /*
113509 ** Return UTF-8 encoded English language explanation of the most recent
113510 ** error.
113511 */
113512 SQLCIPHER_API const char *sqlcipher3_errmsg(sqlcipher3 *db){
113513   const char *z;
113514   if( !db ){
113515     return sqlcipher3ErrStr(SQLCIPHER_NOMEM);
113516   }
113517   if( !sqlcipher3SafetyCheckSickOrOk(db) ){
113518     return sqlcipher3ErrStr(SQLCIPHER_MISUSE_BKPT);
113519   }
113520   sqlcipher3_mutex_enter(db->mutex);
113521   if( db->mallocFailed ){
113522     z = sqlcipher3ErrStr(SQLCIPHER_NOMEM);
113523   }else{
113524     z = (char*)sqlcipher3_value_text(db->pErr);
113525     assert( !db->mallocFailed );
113526     if( z==0 ){
113527       z = sqlcipher3ErrStr(db->errCode);
113528     }
113529   }
113530   sqlcipher3_mutex_leave(db->mutex);
113531   return z;
113532 }
113533
113534 #ifndef SQLCIPHER_OMIT_UTF16
113535 /*
113536 ** Return UTF-16 encoded English language explanation of the most recent
113537 ** error.
113538 */
113539 SQLCIPHER_API const void *sqlcipher3_errmsg16(sqlcipher3 *db){
113540   static const u16 outOfMem[] = {
113541     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
113542   };
113543   static const u16 misuse[] = {
113544     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
113545     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
113546     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
113547     'o', 'u', 't', ' ', 
113548     'o', 'f', ' ', 
113549     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
113550   };
113551
113552   const void *z;
113553   if( !db ){
113554     return (void *)outOfMem;
113555   }
113556   if( !sqlcipher3SafetyCheckSickOrOk(db) ){
113557     return (void *)misuse;
113558   }
113559   sqlcipher3_mutex_enter(db->mutex);
113560   if( db->mallocFailed ){
113561     z = (void *)outOfMem;
113562   }else{
113563     z = sqlcipher3_value_text16(db->pErr);
113564     if( z==0 ){
113565       sqlcipher3ValueSetStr(db->pErr, -1, sqlcipher3ErrStr(db->errCode),
113566            SQLCIPHER_UTF8, SQLCIPHER_STATIC);
113567       z = sqlcipher3_value_text16(db->pErr);
113568     }
113569     /* A malloc() may have failed within the call to sqlcipher3_value_text16()
113570     ** above. If this is the case, then the db->mallocFailed flag needs to
113571     ** be cleared before returning. Do this directly, instead of via
113572     ** sqlcipher3ApiExit(), to avoid setting the database handle error message.
113573     */
113574     db->mallocFailed = 0;
113575   }
113576   sqlcipher3_mutex_leave(db->mutex);
113577   return z;
113578 }
113579 #endif /* SQLCIPHER_OMIT_UTF16 */
113580
113581 /*
113582 ** Return the most recent error code generated by an SQLite routine. If NULL is
113583 ** passed to this function, we assume a malloc() failed during sqlcipher3_open().
113584 */
113585 SQLCIPHER_API int sqlcipher3_errcode(sqlcipher3 *db){
113586   if( db && !sqlcipher3SafetyCheckSickOrOk(db) ){
113587     return SQLCIPHER_MISUSE_BKPT;
113588   }
113589   if( !db || db->mallocFailed ){
113590     return SQLCIPHER_NOMEM;
113591   }
113592   return db->errCode & db->errMask;
113593 }
113594 SQLCIPHER_API int sqlcipher3_extended_errcode(sqlcipher3 *db){
113595   if( db && !sqlcipher3SafetyCheckSickOrOk(db) ){
113596     return SQLCIPHER_MISUSE_BKPT;
113597   }
113598   if( !db || db->mallocFailed ){
113599     return SQLCIPHER_NOMEM;
113600   }
113601   return db->errCode;
113602 }
113603
113604 /*
113605 ** Create a new collating function for database "db".  The name is zName
113606 ** and the encoding is enc.
113607 */
113608 static int createCollation(
113609   sqlcipher3* db,
113610   const char *zName, 
113611   u8 enc,
113612   u8 collType,
113613   void* pCtx,
113614   int(*xCompare)(void*,int,const void*,int,const void*),
113615   void(*xDel)(void*)
113616 ){
113617   CollSeq *pColl;
113618   int enc2;
113619   int nName = sqlcipher3Strlen30(zName);
113620   
113621   assert( sqlcipher3_mutex_held(db->mutex) );
113622
113623   /* If SQLCIPHER_UTF16 is specified as the encoding type, transform this
113624   ** to one of SQLCIPHER_UTF16LE or SQLCIPHER_UTF16BE using the
113625   ** SQLCIPHER_UTF16NATIVE macro. SQLCIPHER_UTF16 is not used internally.
113626   */
113627   enc2 = enc;
113628   testcase( enc2==SQLCIPHER_UTF16 );
113629   testcase( enc2==SQLCIPHER_UTF16_ALIGNED );
113630   if( enc2==SQLCIPHER_UTF16 || enc2==SQLCIPHER_UTF16_ALIGNED ){
113631     enc2 = SQLCIPHER_UTF16NATIVE;
113632   }
113633   if( enc2<SQLCIPHER_UTF8 || enc2>SQLCIPHER_UTF16BE ){
113634     return SQLCIPHER_MISUSE_BKPT;
113635   }
113636
113637   /* Check if this call is removing or replacing an existing collation 
113638   ** sequence. If so, and there are active VMs, return busy. If there
113639   ** are no active VMs, invalidate any pre-compiled statements.
113640   */
113641   pColl = sqlcipher3FindCollSeq(db, (u8)enc2, zName, 0);
113642   if( pColl && pColl->xCmp ){
113643     if( db->activeVdbeCnt ){
113644       sqlcipher3Error(db, SQLCIPHER_BUSY, 
113645         "unable to delete/modify collation sequence due to active statements");
113646       return SQLCIPHER_BUSY;
113647     }
113648     sqlcipher3ExpirePreparedStatements(db);
113649
113650     /* If collation sequence pColl was created directly by a call to
113651     ** sqlcipher3_create_collation, and not generated by synthCollSeq(),
113652     ** then any copies made by synthCollSeq() need to be invalidated.
113653     ** Also, collation destructor - CollSeq.xDel() - function may need
113654     ** to be called.
113655     */ 
113656     if( (pColl->enc & ~SQLCIPHER_UTF16_ALIGNED)==enc2 ){
113657       CollSeq *aColl = sqlcipher3HashFind(&db->aCollSeq, zName, nName);
113658       int j;
113659       for(j=0; j<3; j++){
113660         CollSeq *p = &aColl[j];
113661         if( p->enc==pColl->enc ){
113662           if( p->xDel ){
113663             p->xDel(p->pUser);
113664           }
113665           p->xCmp = 0;
113666         }
113667       }
113668     }
113669   }
113670
113671   pColl = sqlcipher3FindCollSeq(db, (u8)enc2, zName, 1);
113672   if( pColl==0 ) return SQLCIPHER_NOMEM;
113673   pColl->xCmp = xCompare;
113674   pColl->pUser = pCtx;
113675   pColl->xDel = xDel;
113676   pColl->enc = (u8)(enc2 | (enc & SQLCIPHER_UTF16_ALIGNED));
113677   pColl->type = collType;
113678   sqlcipher3Error(db, SQLCIPHER_OK, 0);
113679   return SQLCIPHER_OK;
113680 }
113681
113682
113683 /*
113684 ** This array defines hard upper bounds on limit values.  The
113685 ** initializer must be kept in sync with the SQLCIPHER_LIMIT_*
113686 ** #defines in sqlcipher3.h.
113687 */
113688 static const int aHardLimit[] = {
113689   SQLCIPHER_MAX_LENGTH,
113690   SQLCIPHER_MAX_SQL_LENGTH,
113691   SQLCIPHER_MAX_COLUMN,
113692   SQLCIPHER_MAX_EXPR_DEPTH,
113693   SQLCIPHER_MAX_COMPOUND_SELECT,
113694   SQLCIPHER_MAX_VDBE_OP,
113695   SQLCIPHER_MAX_FUNCTION_ARG,
113696   SQLCIPHER_MAX_ATTACHED,
113697   SQLCIPHER_MAX_LIKE_PATTERN_LENGTH,
113698   SQLCIPHER_MAX_VARIABLE_NUMBER,
113699   SQLCIPHER_MAX_TRIGGER_DEPTH,
113700 };
113701
113702 /*
113703 ** Make sure the hard limits are set to reasonable values
113704 */
113705 #if SQLCIPHER_MAX_LENGTH<100
113706 # error SQLCIPHER_MAX_LENGTH must be at least 100
113707 #endif
113708 #if SQLCIPHER_MAX_SQL_LENGTH<100
113709 # error SQLCIPHER_MAX_SQL_LENGTH must be at least 100
113710 #endif
113711 #if SQLCIPHER_MAX_SQL_LENGTH>SQLCIPHER_MAX_LENGTH
113712 # error SQLCIPHER_MAX_SQL_LENGTH must not be greater than SQLCIPHER_MAX_LENGTH
113713 #endif
113714 #if SQLCIPHER_MAX_COMPOUND_SELECT<2
113715 # error SQLCIPHER_MAX_COMPOUND_SELECT must be at least 2
113716 #endif
113717 #if SQLCIPHER_MAX_VDBE_OP<40
113718 # error SQLCIPHER_MAX_VDBE_OP must be at least 40
113719 #endif
113720 #if SQLCIPHER_MAX_FUNCTION_ARG<0 || SQLCIPHER_MAX_FUNCTION_ARG>1000
113721 # error SQLCIPHER_MAX_FUNCTION_ARG must be between 0 and 1000
113722 #endif
113723 #if SQLCIPHER_MAX_ATTACHED<0 || SQLCIPHER_MAX_ATTACHED>62
113724 # error SQLCIPHER_MAX_ATTACHED must be between 0 and 62
113725 #endif
113726 #if SQLCIPHER_MAX_LIKE_PATTERN_LENGTH<1
113727 # error SQLCIPHER_MAX_LIKE_PATTERN_LENGTH must be at least 1
113728 #endif
113729 #if SQLCIPHER_MAX_COLUMN>32767
113730 # error SQLCIPHER_MAX_COLUMN must not exceed 32767
113731 #endif
113732 #if SQLCIPHER_MAX_TRIGGER_DEPTH<1
113733 # error SQLCIPHER_MAX_TRIGGER_DEPTH must be at least 1
113734 #endif
113735
113736
113737 /*
113738 ** Change the value of a limit.  Report the old value.
113739 ** If an invalid limit index is supplied, report -1.
113740 ** Make no changes but still report the old value if the
113741 ** new limit is negative.
113742 **
113743 ** A new lower limit does not shrink existing constructs.
113744 ** It merely prevents new constructs that exceed the limit
113745 ** from forming.
113746 */
113747 SQLCIPHER_API int sqlcipher3_limit(sqlcipher3 *db, int limitId, int newLimit){
113748   int oldLimit;
113749
113750
113751   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLCIPHER_LIMIT_NAME
113752   ** there is a hard upper bound set at compile-time by a C preprocessor
113753   ** macro called SQLCIPHER_MAX_NAME. (The "_LIMIT_" in the name is changed to
113754   ** "_MAX_".)
113755   */
113756   assert( aHardLimit[SQLCIPHER_LIMIT_LENGTH]==SQLCIPHER_MAX_LENGTH );
113757   assert( aHardLimit[SQLCIPHER_LIMIT_SQL_LENGTH]==SQLCIPHER_MAX_SQL_LENGTH );
113758   assert( aHardLimit[SQLCIPHER_LIMIT_COLUMN]==SQLCIPHER_MAX_COLUMN );
113759   assert( aHardLimit[SQLCIPHER_LIMIT_EXPR_DEPTH]==SQLCIPHER_MAX_EXPR_DEPTH );
113760   assert( aHardLimit[SQLCIPHER_LIMIT_COMPOUND_SELECT]==SQLCIPHER_MAX_COMPOUND_SELECT);
113761   assert( aHardLimit[SQLCIPHER_LIMIT_VDBE_OP]==SQLCIPHER_MAX_VDBE_OP );
113762   assert( aHardLimit[SQLCIPHER_LIMIT_FUNCTION_ARG]==SQLCIPHER_MAX_FUNCTION_ARG );
113763   assert( aHardLimit[SQLCIPHER_LIMIT_ATTACHED]==SQLCIPHER_MAX_ATTACHED );
113764   assert( aHardLimit[SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH]==
113765                                                SQLCIPHER_MAX_LIKE_PATTERN_LENGTH );
113766   assert( aHardLimit[SQLCIPHER_LIMIT_VARIABLE_NUMBER]==SQLCIPHER_MAX_VARIABLE_NUMBER);
113767   assert( aHardLimit[SQLCIPHER_LIMIT_TRIGGER_DEPTH]==SQLCIPHER_MAX_TRIGGER_DEPTH );
113768   assert( SQLCIPHER_LIMIT_TRIGGER_DEPTH==(SQLCIPHER_N_LIMIT-1) );
113769
113770
113771   if( limitId<0 || limitId>=SQLCIPHER_N_LIMIT ){
113772     return -1;
113773   }
113774   oldLimit = db->aLimit[limitId];
113775   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
113776     if( newLimit>aHardLimit[limitId] ){
113777       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
113778     }
113779     db->aLimit[limitId] = newLimit;
113780   }
113781   return oldLimit;                     /* IMP: R-53341-35419 */
113782 }
113783
113784 /*
113785 ** This function is used to parse both URIs and non-URI filenames passed by the
113786 ** user to API functions sqlcipher3_open() or sqlcipher3_open_v2(), and for database
113787 ** URIs specified as part of ATTACH statements.
113788 **
113789 ** The first argument to this function is the name of the VFS to use (or
113790 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
113791 ** query parameter. The second argument contains the URI (or non-URI filename)
113792 ** itself. When this function is called the *pFlags variable should contain
113793 ** the default flags to open the database handle with. The value stored in
113794 ** *pFlags may be updated before returning if the URI filename contains 
113795 ** "cache=xxx" or "mode=xxx" query parameters.
113796 **
113797 ** If successful, SQLCIPHER_OK is returned. In this case *ppVfs is set to point to
113798 ** the VFS that should be used to open the database file. *pzFile is set to
113799 ** point to a buffer containing the name of the file to open. It is the 
113800 ** responsibility of the caller to eventually call sqlcipher3_free() to release
113801 ** this buffer.
113802 **
113803 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
113804 ** may be set to point to a buffer containing an English language error 
113805 ** message. It is the responsibility of the caller to eventually release
113806 ** this buffer by calling sqlcipher3_free().
113807 */
113808 SQLCIPHER_PRIVATE int sqlcipher3ParseUri(
113809   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
113810   const char *zUri,               /* Nul-terminated URI to parse */
113811   unsigned int *pFlags,           /* IN/OUT: SQLCIPHER_OPEN_XXX flags */
113812   sqlcipher3_vfs **ppVfs,            /* OUT: VFS to use */ 
113813   char **pzFile,                  /* OUT: Filename component of URI */
113814   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLCIPHER_OK) */
113815 ){
113816   int rc = SQLCIPHER_OK;
113817   unsigned int flags = *pFlags;
113818   const char *zVfs = zDefaultVfs;
113819   char *zFile;
113820   char c;
113821   int nUri = sqlcipher3Strlen30(zUri);
113822
113823   assert( *pzErrMsg==0 );
113824
113825   if( ((flags & SQLCIPHER_OPEN_URI) || sqlcipher3GlobalConfig.bOpenUri) 
113826    && nUri>=5 && memcmp(zUri, "file:", 5)==0 
113827   ){
113828     char *zOpt;
113829     int eState;                   /* Parser state when parsing URI */
113830     int iIn;                      /* Input character index */
113831     int iOut = 0;                 /* Output character index */
113832     int nByte = nUri+2;           /* Bytes of space to allocate */
113833
113834     /* Make sure the SQLCIPHER_OPEN_URI flag is set to indicate to the VFS xOpen 
113835     ** method that there may be extra parameters following the file-name.  */
113836     flags |= SQLCIPHER_OPEN_URI;
113837
113838     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
113839     zFile = sqlcipher3_malloc(nByte);
113840     if( !zFile ) return SQLCIPHER_NOMEM;
113841
113842     /* Discard the scheme and authority segments of the URI. */
113843     if( zUri[5]=='/' && zUri[6]=='/' ){
113844       iIn = 7;
113845       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
113846
113847       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
113848         *pzErrMsg = sqlcipher3_mprintf("invalid uri authority: %.*s", 
113849             iIn-7, &zUri[7]);
113850         rc = SQLCIPHER_ERROR;
113851         goto parse_uri_out;
113852       }
113853     }else{
113854       iIn = 5;
113855     }
113856
113857     /* Copy the filename and any query parameters into the zFile buffer. 
113858     ** Decode %HH escape codes along the way. 
113859     **
113860     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
113861     ** on the parsing context. As follows:
113862     **
113863     **   0: Parsing file-name.
113864     **   1: Parsing name section of a name=value query parameter.
113865     **   2: Parsing value section of a name=value query parameter.
113866     */
113867     eState = 0;
113868     while( (c = zUri[iIn])!=0 && c!='#' ){
113869       iIn++;
113870       if( c=='%' 
113871        && sqlcipher3Isxdigit(zUri[iIn]) 
113872        && sqlcipher3Isxdigit(zUri[iIn+1]) 
113873       ){
113874         int octet = (sqlcipher3HexToInt(zUri[iIn++]) << 4);
113875         octet += sqlcipher3HexToInt(zUri[iIn++]);
113876
113877         assert( octet>=0 && octet<256 );
113878         if( octet==0 ){
113879           /* This branch is taken when "%00" appears within the URI. In this
113880           ** case we ignore all text in the remainder of the path, name or
113881           ** value currently being parsed. So ignore the current character
113882           ** and skip to the next "?", "=" or "&", as appropriate. */
113883           while( (c = zUri[iIn])!=0 && c!='#' 
113884               && (eState!=0 || c!='?')
113885               && (eState!=1 || (c!='=' && c!='&'))
113886               && (eState!=2 || c!='&')
113887           ){
113888             iIn++;
113889           }
113890           continue;
113891         }
113892         c = octet;
113893       }else if( eState==1 && (c=='&' || c=='=') ){
113894         if( zFile[iOut-1]==0 ){
113895           /* An empty option name. Ignore this option altogether. */
113896           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
113897           continue;
113898         }
113899         if( c=='&' ){
113900           zFile[iOut++] = '\0';
113901         }else{
113902           eState = 2;
113903         }
113904         c = 0;
113905       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
113906         c = 0;
113907         eState = 1;
113908       }
113909       zFile[iOut++] = c;
113910     }
113911     if( eState==1 ) zFile[iOut++] = '\0';
113912     zFile[iOut++] = '\0';
113913     zFile[iOut++] = '\0';
113914
113915     /* Check if there were any options specified that should be interpreted 
113916     ** here. Options that are interpreted here include "vfs" and those that
113917     ** correspond to flags that may be passed to the sqlcipher3_open_v2()
113918     ** method. */
113919     zOpt = &zFile[sqlcipher3Strlen30(zFile)+1];
113920     while( zOpt[0] ){
113921       int nOpt = sqlcipher3Strlen30(zOpt);
113922       char *zVal = &zOpt[nOpt+1];
113923       int nVal = sqlcipher3Strlen30(zVal);
113924
113925       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
113926         zVfs = zVal;
113927       }else{
113928         struct OpenMode {
113929           const char *z;
113930           int mode;
113931         } *aMode = 0;
113932         char *zModeType = 0;
113933         int mask = 0;
113934         int limit = 0;
113935
113936         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
113937           static struct OpenMode aCacheMode[] = {
113938             { "shared",  SQLCIPHER_OPEN_SHAREDCACHE },
113939             { "private", SQLCIPHER_OPEN_PRIVATECACHE },
113940             { 0, 0 }
113941           };
113942
113943           mask = SQLCIPHER_OPEN_SHAREDCACHE|SQLCIPHER_OPEN_PRIVATECACHE;
113944           aMode = aCacheMode;
113945           limit = mask;
113946           zModeType = "cache";
113947         }
113948         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
113949           static struct OpenMode aOpenMode[] = {
113950             { "ro",  SQLCIPHER_OPEN_READONLY },
113951             { "rw",  SQLCIPHER_OPEN_READWRITE }, 
113952             { "rwc", SQLCIPHER_OPEN_READWRITE | SQLCIPHER_OPEN_CREATE },
113953             { 0, 0 }
113954           };
113955
113956           mask = SQLCIPHER_OPEN_READONLY|SQLCIPHER_OPEN_READWRITE|SQLCIPHER_OPEN_CREATE;
113957           aMode = aOpenMode;
113958           limit = mask & flags;
113959           zModeType = "access";
113960         }
113961
113962         if( aMode ){
113963           int i;
113964           int mode = 0;
113965           for(i=0; aMode[i].z; i++){
113966             const char *z = aMode[i].z;
113967             if( nVal==sqlcipher3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
113968               mode = aMode[i].mode;
113969               break;
113970             }
113971           }
113972           if( mode==0 ){
113973             *pzErrMsg = sqlcipher3_mprintf("no such %s mode: %s", zModeType, zVal);
113974             rc = SQLCIPHER_ERROR;
113975             goto parse_uri_out;
113976           }
113977           if( mode>limit ){
113978             *pzErrMsg = sqlcipher3_mprintf("%s mode not allowed: %s",
113979                                         zModeType, zVal);
113980             rc = SQLCIPHER_PERM;
113981             goto parse_uri_out;
113982           }
113983           flags = (flags & ~mask) | mode;
113984         }
113985       }
113986
113987       zOpt = &zVal[nVal+1];
113988     }
113989
113990   }else{
113991     zFile = sqlcipher3_malloc(nUri+2);
113992     if( !zFile ) return SQLCIPHER_NOMEM;
113993     memcpy(zFile, zUri, nUri);
113994     zFile[nUri] = '\0';
113995     zFile[nUri+1] = '\0';
113996   }
113997
113998   *ppVfs = sqlcipher3_vfs_find(zVfs);
113999   if( *ppVfs==0 ){
114000     *pzErrMsg = sqlcipher3_mprintf("no such vfs: %s", zVfs);
114001     rc = SQLCIPHER_ERROR;
114002   }
114003  parse_uri_out:
114004   if( rc!=SQLCIPHER_OK ){
114005     sqlcipher3_free(zFile);
114006     zFile = 0;
114007   }
114008   *pFlags = flags;
114009   *pzFile = zFile;
114010   return rc;
114011 }
114012
114013
114014 /*
114015 ** This routine does the work of opening a database on behalf of
114016 ** sqlcipher3_open() and sqlcipher3_open16(). The database filename "zFilename"  
114017 ** is UTF-8 encoded.
114018 */
114019 static int openDatabase(
114020   const char *zFilename, /* Database filename UTF-8 encoded */
114021   sqlcipher3 **ppDb,        /* OUT: Returned database handle */
114022   unsigned int flags,    /* Operational flags */
114023   const char *zVfs       /* Name of the VFS to use */
114024 ){
114025   sqlcipher3 *db;                    /* Store allocated handle here */
114026   int rc;                         /* Return code */
114027   int isThreadsafe;               /* True for threadsafe connections */
114028   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
114029   char *zErrMsg = 0;              /* Error message from sqlcipher3ParseUri() */
114030
114031   *ppDb = 0;
114032 #ifndef SQLCIPHER_OMIT_AUTOINIT
114033   rc = sqlcipher3_initialize();
114034   if( rc ) return rc;
114035 #endif
114036
114037   /* Only allow sensible combinations of bits in the flags argument.  
114038   ** Throw an error if any non-sense combination is used.  If we
114039   ** do not block illegal combinations here, it could trigger
114040   ** assert() statements in deeper layers.  Sensible combinations
114041   ** are:
114042   **
114043   **  1:  SQLCIPHER_OPEN_READONLY
114044   **  2:  SQLCIPHER_OPEN_READWRITE
114045   **  6:  SQLCIPHER_OPEN_READWRITE | SQLCIPHER_OPEN_CREATE
114046   */
114047   assert( SQLCIPHER_OPEN_READONLY  == 0x01 );
114048   assert( SQLCIPHER_OPEN_READWRITE == 0x02 );
114049   assert( SQLCIPHER_OPEN_CREATE    == 0x04 );
114050   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
114051   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
114052   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
114053   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLCIPHER_MISUSE_BKPT;
114054
114055   if( sqlcipher3GlobalConfig.bCoreMutex==0 ){
114056     isThreadsafe = 0;
114057   }else if( flags & SQLCIPHER_OPEN_NOMUTEX ){
114058     isThreadsafe = 0;
114059   }else if( flags & SQLCIPHER_OPEN_FULLMUTEX ){
114060     isThreadsafe = 1;
114061   }else{
114062     isThreadsafe = sqlcipher3GlobalConfig.bFullMutex;
114063   }
114064   if( flags & SQLCIPHER_OPEN_PRIVATECACHE ){
114065     flags &= ~SQLCIPHER_OPEN_SHAREDCACHE;
114066   }else if( sqlcipher3GlobalConfig.sharedCacheEnabled ){
114067     flags |= SQLCIPHER_OPEN_SHAREDCACHE;
114068   }
114069
114070   /* Remove harmful bits from the flags parameter
114071   **
114072   ** The SQLCIPHER_OPEN_NOMUTEX and SQLCIPHER_OPEN_FULLMUTEX flags were
114073   ** dealt with in the previous code block.  Besides these, the only
114074   ** valid input flags for sqlcipher3_open_v2() are SQLCIPHER_OPEN_READONLY,
114075   ** SQLCIPHER_OPEN_READWRITE, SQLCIPHER_OPEN_CREATE, SQLCIPHER_OPEN_SHAREDCACHE,
114076   ** SQLCIPHER_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
114077   ** off all other flags.
114078   */
114079   flags &=  ~( SQLCIPHER_OPEN_DELETEONCLOSE |
114080                SQLCIPHER_OPEN_EXCLUSIVE |
114081                SQLCIPHER_OPEN_MAIN_DB |
114082                SQLCIPHER_OPEN_TEMP_DB | 
114083                SQLCIPHER_OPEN_TRANSIENT_DB | 
114084                SQLCIPHER_OPEN_MAIN_JOURNAL | 
114085                SQLCIPHER_OPEN_TEMP_JOURNAL | 
114086                SQLCIPHER_OPEN_SUBJOURNAL | 
114087                SQLCIPHER_OPEN_MASTER_JOURNAL |
114088                SQLCIPHER_OPEN_NOMUTEX |
114089                SQLCIPHER_OPEN_FULLMUTEX |
114090                SQLCIPHER_OPEN_WAL
114091              );
114092
114093   /* Allocate the sqlcipher data structure */
114094   db = sqlcipher3MallocZero( sizeof(sqlcipher3) );
114095   if( db==0 ) goto opendb_out;
114096   if( isThreadsafe ){
114097     db->mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_RECURSIVE);
114098     if( db->mutex==0 ){
114099       sqlcipher3_free(db);
114100       db = 0;
114101       goto opendb_out;
114102     }
114103   }
114104   sqlcipher3_mutex_enter(db->mutex);
114105   db->errMask = 0xff;
114106   db->nDb = 2;
114107   db->magic = SQLCIPHER_MAGIC_BUSY;
114108   db->aDb = db->aDbStatic;
114109
114110   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
114111   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
114112   db->autoCommit = 1;
114113   db->nextAutovac = -1;
114114   db->nextPagesize = 0;
114115   db->flags |= SQLCIPHER_ShortColNames | SQLCIPHER_AutoIndex | SQLCIPHER_EnableTrigger
114116 #if SQLCIPHER_DEFAULT_FILE_FORMAT<4
114117                  | SQLCIPHER_LegacyFileFmt
114118 #endif
114119 #ifdef SQLCIPHER_ENABLE_LOAD_EXTENSION
114120                  | SQLCIPHER_LoadExtension
114121 #endif
114122 #if SQLCIPHER_DEFAULT_RECURSIVE_TRIGGERS
114123                  | SQLCIPHER_RecTriggers
114124 #endif
114125 #if defined(SQLCIPHER_DEFAULT_FOREIGN_KEYS) && SQLCIPHER_DEFAULT_FOREIGN_KEYS
114126                  | SQLCIPHER_ForeignKeys
114127 #endif
114128       ;
114129   sqlcipher3HashInit(&db->aCollSeq);
114130 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
114131   sqlcipher3HashInit(&db->aModule);
114132 #endif
114133
114134   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
114135   ** and UTF-16, so add a version for each to avoid any unnecessary
114136   ** conversions. The only error that can occur here is a malloc() failure.
114137   */
114138   createCollation(db, "BINARY", SQLCIPHER_UTF8, SQLCIPHER_COLL_BINARY, 0,
114139                   binCollFunc, 0);
114140   createCollation(db, "BINARY", SQLCIPHER_UTF16BE, SQLCIPHER_COLL_BINARY, 0,
114141                   binCollFunc, 0);
114142   createCollation(db, "BINARY", SQLCIPHER_UTF16LE, SQLCIPHER_COLL_BINARY, 0,
114143                   binCollFunc, 0);
114144   createCollation(db, "RTRIM", SQLCIPHER_UTF8, SQLCIPHER_COLL_USER, (void*)1,
114145                   binCollFunc, 0);
114146   if( db->mallocFailed ){
114147     goto opendb_out;
114148   }
114149   db->pDfltColl = sqlcipher3FindCollSeq(db, SQLCIPHER_UTF8, "BINARY", 0);
114150   assert( db->pDfltColl!=0 );
114151
114152   /* Also add a UTF-8 case-insensitive collation sequence. */
114153   createCollation(db, "NOCASE", SQLCIPHER_UTF8, SQLCIPHER_COLL_NOCASE, 0,
114154                   nocaseCollatingFunc, 0);
114155
114156   /* Parse the filename/URI argument. */
114157   db->openFlags = flags;
114158   rc = sqlcipher3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
114159   if( rc!=SQLCIPHER_OK ){
114160     if( rc==SQLCIPHER_NOMEM ) db->mallocFailed = 1;
114161     sqlcipher3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
114162     sqlcipher3_free(zErrMsg);
114163     goto opendb_out;
114164   }
114165
114166   /* Open the backend database driver */
114167   rc = sqlcipher3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
114168                         flags | SQLCIPHER_OPEN_MAIN_DB);
114169   if( rc!=SQLCIPHER_OK ){
114170     if( rc==SQLCIPHER_IOERR_NOMEM ){
114171       rc = SQLCIPHER_NOMEM;
114172     }
114173     sqlcipher3Error(db, rc, 0);
114174     goto opendb_out;
114175   }
114176   db->aDb[0].pSchema = sqlcipher3SchemaGet(db, db->aDb[0].pBt);
114177   db->aDb[1].pSchema = sqlcipher3SchemaGet(db, 0);
114178
114179
114180   /* The default safety_level for the main database is 'full'; for the temp
114181   ** database it is 'NONE'. This matches the pager layer defaults.  
114182   */
114183   db->aDb[0].zName = "main";
114184   db->aDb[0].safety_level = 3;
114185   db->aDb[1].zName = "temp";
114186   db->aDb[1].safety_level = 1;
114187
114188   db->magic = SQLCIPHER_MAGIC_OPEN;
114189   if( db->mallocFailed ){
114190     goto opendb_out;
114191   }
114192
114193   /* Register all built-in functions, but do not attempt to read the
114194   ** database schema yet. This is delayed until the first time the database
114195   ** is accessed.
114196   */
114197   sqlcipher3Error(db, SQLCIPHER_OK, 0);
114198   sqlcipher3RegisterBuiltinFunctions(db);
114199
114200   /* Load automatic extensions - extensions that have been registered
114201   ** using the sqlcipher3_automatic_extension() API.
114202   */
114203   sqlcipher3AutoLoadExtensions(db);
114204   rc = sqlcipher3_errcode(db);
114205   if( rc!=SQLCIPHER_OK ){
114206     goto opendb_out;
114207   }
114208
114209 #ifdef SQLCIPHER_ENABLE_FTS1
114210   if( !db->mallocFailed ){
114211     extern int sqlcipher3Fts1Init(sqlcipher3*);
114212     rc = sqlcipher3Fts1Init(db);
114213   }
114214 #endif
114215
114216 #ifdef SQLCIPHER_ENABLE_FTS2
114217   if( !db->mallocFailed && rc==SQLCIPHER_OK ){
114218     extern int sqlcipher3Fts2Init(sqlcipher3*);
114219     rc = sqlcipher3Fts2Init(db);
114220   }
114221 #endif
114222
114223 #ifdef SQLCIPHER_ENABLE_FTS3
114224   if( !db->mallocFailed && rc==SQLCIPHER_OK ){
114225     rc = sqlcipher3Fts3Init(db);
114226   }
114227 #endif
114228
114229 #ifdef SQLCIPHER_ENABLE_ICU
114230   if( !db->mallocFailed && rc==SQLCIPHER_OK ){
114231     rc = sqlcipher3IcuInit(db);
114232   }
114233 #endif
114234
114235 #ifdef SQLCIPHER_ENABLE_RTREE
114236   if( !db->mallocFailed && rc==SQLCIPHER_OK){
114237     rc = sqlcipher3RtreeInit(db);
114238   }
114239 #endif
114240
114241   sqlcipher3Error(db, rc, 0);
114242
114243   /* -DSQLCIPHER_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
114244   ** mode.  -DSQLCIPHER_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
114245   ** mode.  Doing nothing at all also makes NORMAL the default.
114246   */
114247 #ifdef SQLCIPHER_DEFAULT_LOCKING_MODE
114248   db->dfltLockMode = SQLCIPHER_DEFAULT_LOCKING_MODE;
114249   sqlcipher3PagerLockingMode(sqlcipher3BtreePager(db->aDb[0].pBt),
114250                           SQLCIPHER_DEFAULT_LOCKING_MODE);
114251 #endif
114252
114253   /* Enable the lookaside-malloc subsystem */
114254   setupLookaside(db, 0, sqlcipher3GlobalConfig.szLookaside,
114255                         sqlcipher3GlobalConfig.nLookaside);
114256
114257   sqlcipher3_wal_autocheckpoint(db, SQLCIPHER_DEFAULT_WAL_AUTOCHECKPOINT);
114258
114259 opendb_out:
114260   sqlcipher3_free(zOpen);
114261   if( db ){
114262     assert( db->mutex!=0 || isThreadsafe==0 || sqlcipher3GlobalConfig.bFullMutex==0 );
114263     sqlcipher3_mutex_leave(db->mutex);
114264   }
114265   rc = sqlcipher3_errcode(db);
114266   assert( db!=0 || rc==SQLCIPHER_NOMEM );
114267   if( rc==SQLCIPHER_NOMEM ){
114268     sqlcipher3_close(db);
114269     db = 0;
114270   }else if( rc!=SQLCIPHER_OK ){
114271     db->magic = SQLCIPHER_MAGIC_SICK;
114272   }
114273   *ppDb = db;
114274   return sqlcipher3ApiExit(0, rc);
114275 }
114276
114277 /*
114278 ** Open a new database handle.
114279 */
114280 SQLCIPHER_API int sqlcipher3_open(
114281   const char *zFilename, 
114282   sqlcipher3 **ppDb 
114283 ){
114284   return openDatabase(zFilename, ppDb,
114285                       SQLCIPHER_OPEN_READWRITE | SQLCIPHER_OPEN_CREATE, 0);
114286 }
114287 SQLCIPHER_API int sqlcipher3_open_v2(
114288   const char *filename,   /* Database filename (UTF-8) */
114289   sqlcipher3 **ppDb,         /* OUT: SQLite db handle */
114290   int flags,              /* Flags */
114291   const char *zVfs        /* Name of VFS module to use */
114292 ){
114293   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
114294 }
114295
114296 #ifndef SQLCIPHER_OMIT_UTF16
114297 /*
114298 ** Open a new database handle.
114299 */
114300 SQLCIPHER_API int sqlcipher3_open16(
114301   const void *zFilename, 
114302   sqlcipher3 **ppDb
114303 ){
114304   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
114305   sqlcipher3_value *pVal;
114306   int rc;
114307
114308   assert( zFilename );
114309   assert( ppDb );
114310   *ppDb = 0;
114311 #ifndef SQLCIPHER_OMIT_AUTOINIT
114312   rc = sqlcipher3_initialize();
114313   if( rc ) return rc;
114314 #endif
114315   pVal = sqlcipher3ValueNew(0);
114316   sqlcipher3ValueSetStr(pVal, -1, zFilename, SQLCIPHER_UTF16NATIVE, SQLCIPHER_STATIC);
114317   zFilename8 = sqlcipher3ValueText(pVal, SQLCIPHER_UTF8);
114318   if( zFilename8 ){
114319     rc = openDatabase(zFilename8, ppDb,
114320                       SQLCIPHER_OPEN_READWRITE | SQLCIPHER_OPEN_CREATE, 0);
114321     assert( *ppDb || rc==SQLCIPHER_NOMEM );
114322     if( rc==SQLCIPHER_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
114323       ENC(*ppDb) = SQLCIPHER_UTF16NATIVE;
114324     }
114325   }else{
114326     rc = SQLCIPHER_NOMEM;
114327   }
114328   sqlcipher3ValueFree(pVal);
114329
114330   return sqlcipher3ApiExit(0, rc);
114331 }
114332 #endif /* SQLCIPHER_OMIT_UTF16 */
114333
114334 /*
114335 ** Register a new collation sequence with the database handle db.
114336 */
114337 SQLCIPHER_API int sqlcipher3_create_collation(
114338   sqlcipher3* db, 
114339   const char *zName, 
114340   int enc, 
114341   void* pCtx,
114342   int(*xCompare)(void*,int,const void*,int,const void*)
114343 ){
114344   int rc;
114345   sqlcipher3_mutex_enter(db->mutex);
114346   assert( !db->mallocFailed );
114347   rc = createCollation(db, zName, (u8)enc, SQLCIPHER_COLL_USER, pCtx, xCompare, 0);
114348   rc = sqlcipher3ApiExit(db, rc);
114349   sqlcipher3_mutex_leave(db->mutex);
114350   return rc;
114351 }
114352
114353 /*
114354 ** Register a new collation sequence with the database handle db.
114355 */
114356 SQLCIPHER_API int sqlcipher3_create_collation_v2(
114357   sqlcipher3* db, 
114358   const char *zName, 
114359   int enc, 
114360   void* pCtx,
114361   int(*xCompare)(void*,int,const void*,int,const void*),
114362   void(*xDel)(void*)
114363 ){
114364   int rc;
114365   sqlcipher3_mutex_enter(db->mutex);
114366   assert( !db->mallocFailed );
114367   rc = createCollation(db, zName, (u8)enc, SQLCIPHER_COLL_USER, pCtx, xCompare, xDel);
114368   rc = sqlcipher3ApiExit(db, rc);
114369   sqlcipher3_mutex_leave(db->mutex);
114370   return rc;
114371 }
114372
114373 #ifndef SQLCIPHER_OMIT_UTF16
114374 /*
114375 ** Register a new collation sequence with the database handle db.
114376 */
114377 SQLCIPHER_API int sqlcipher3_create_collation16(
114378   sqlcipher3* db, 
114379   const void *zName,
114380   int enc, 
114381   void* pCtx,
114382   int(*xCompare)(void*,int,const void*,int,const void*)
114383 ){
114384   int rc = SQLCIPHER_OK;
114385   char *zName8;
114386   sqlcipher3_mutex_enter(db->mutex);
114387   assert( !db->mallocFailed );
114388   zName8 = sqlcipher3Utf16to8(db, zName, -1, SQLCIPHER_UTF16NATIVE);
114389   if( zName8 ){
114390     rc = createCollation(db, zName8, (u8)enc, SQLCIPHER_COLL_USER, pCtx, xCompare, 0);
114391     sqlcipher3DbFree(db, zName8);
114392   }
114393   rc = sqlcipher3ApiExit(db, rc);
114394   sqlcipher3_mutex_leave(db->mutex);
114395   return rc;
114396 }
114397 #endif /* SQLCIPHER_OMIT_UTF16 */
114398
114399 /*
114400 ** Register a collation sequence factory callback with the database handle
114401 ** db. Replace any previously installed collation sequence factory.
114402 */
114403 SQLCIPHER_API int sqlcipher3_collation_needed(
114404   sqlcipher3 *db, 
114405   void *pCollNeededArg, 
114406   void(*xCollNeeded)(void*,sqlcipher3*,int eTextRep,const char*)
114407 ){
114408   sqlcipher3_mutex_enter(db->mutex);
114409   db->xCollNeeded = xCollNeeded;
114410   db->xCollNeeded16 = 0;
114411   db->pCollNeededArg = pCollNeededArg;
114412   sqlcipher3_mutex_leave(db->mutex);
114413   return SQLCIPHER_OK;
114414 }
114415
114416 #ifndef SQLCIPHER_OMIT_UTF16
114417 /*
114418 ** Register a collation sequence factory callback with the database handle
114419 ** db. Replace any previously installed collation sequence factory.
114420 */
114421 SQLCIPHER_API int sqlcipher3_collation_needed16(
114422   sqlcipher3 *db, 
114423   void *pCollNeededArg, 
114424   void(*xCollNeeded16)(void*,sqlcipher3*,int eTextRep,const void*)
114425 ){
114426   sqlcipher3_mutex_enter(db->mutex);
114427   db->xCollNeeded = 0;
114428   db->xCollNeeded16 = xCollNeeded16;
114429   db->pCollNeededArg = pCollNeededArg;
114430   sqlcipher3_mutex_leave(db->mutex);
114431   return SQLCIPHER_OK;
114432 }
114433 #endif /* SQLCIPHER_OMIT_UTF16 */
114434
114435 #ifndef SQLCIPHER_OMIT_DEPRECATED
114436 /*
114437 ** This function is now an anachronism. It used to be used to recover from a
114438 ** malloc() failure, but SQLite now does this automatically.
114439 */
114440 SQLCIPHER_API int sqlcipher3_global_recover(void){
114441   return SQLCIPHER_OK;
114442 }
114443 #endif
114444
114445 /*
114446 ** Test to see whether or not the database connection is in autocommit
114447 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
114448 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
114449 ** by the next COMMIT or ROLLBACK.
114450 **
114451 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
114452 */
114453 SQLCIPHER_API int sqlcipher3_get_autocommit(sqlcipher3 *db){
114454   return db->autoCommit;
114455 }
114456
114457 /*
114458 ** The following routines are subtitutes for constants SQLCIPHER_CORRUPT,
114459 ** SQLCIPHER_MISUSE, SQLCIPHER_CANTOPEN, SQLCIPHER_IOERR and possibly other error
114460 ** constants.  They server two purposes:
114461 **
114462 **   1.  Serve as a convenient place to set a breakpoint in a debugger
114463 **       to detect when version error conditions occurs.
114464 **
114465 **   2.  Invoke sqlcipher3_log() to provide the source code location where
114466 **       a low-level error is first detected.
114467 */
114468 SQLCIPHER_PRIVATE int sqlcipher3CorruptError(int lineno){
114469   testcase( sqlcipher3GlobalConfig.xLog!=0 );
114470   sqlcipher3_log(SQLCIPHER_CORRUPT,
114471               "database corruption at line %d of [%.10s]",
114472               lineno, 20+sqlcipher3_sourceid());
114473   return SQLCIPHER_CORRUPT;
114474 }
114475 SQLCIPHER_PRIVATE int sqlcipher3MisuseError(int lineno){
114476   testcase( sqlcipher3GlobalConfig.xLog!=0 );
114477   sqlcipher3_log(SQLCIPHER_MISUSE, 
114478               "misuse at line %d of [%.10s]",
114479               lineno, 20+sqlcipher3_sourceid());
114480   return SQLCIPHER_MISUSE;
114481 }
114482 SQLCIPHER_PRIVATE int sqlcipher3CantopenError(int lineno){
114483   testcase( sqlcipher3GlobalConfig.xLog!=0 );
114484   sqlcipher3_log(SQLCIPHER_CANTOPEN, 
114485               "cannot open file at line %d of [%.10s]",
114486               lineno, 20+sqlcipher3_sourceid());
114487   return SQLCIPHER_CANTOPEN;
114488 }
114489
114490
114491 #ifndef SQLCIPHER_OMIT_DEPRECATED
114492 /*
114493 ** This is a convenience routine that makes sure that all thread-specific
114494 ** data for this thread has been deallocated.
114495 **
114496 ** SQLite no longer uses thread-specific data so this routine is now a
114497 ** no-op.  It is retained for historical compatibility.
114498 */
114499 SQLCIPHER_API void sqlcipher3_thread_cleanup(void){
114500 }
114501 #endif
114502
114503 /*
114504 ** Return meta information about a specific column of a database table.
114505 ** See comment in sqlcipher3.h (sqlcipher.h.in) for details.
114506 */
114507 #ifdef SQLCIPHER_ENABLE_COLUMN_METADATA
114508 SQLCIPHER_API int sqlcipher3_table_column_metadata(
114509   sqlcipher3 *db,                /* Connection handle */
114510   const char *zDbName,        /* Database name or NULL */
114511   const char *zTableName,     /* Table name */
114512   const char *zColumnName,    /* Column name */
114513   char const **pzDataType,    /* OUTPUT: Declared data type */
114514   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
114515   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
114516   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
114517   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
114518 ){
114519   int rc;
114520   char *zErrMsg = 0;
114521   Table *pTab = 0;
114522   Column *pCol = 0;
114523   int iCol;
114524
114525   char const *zDataType = 0;
114526   char const *zCollSeq = 0;
114527   int notnull = 0;
114528   int primarykey = 0;
114529   int autoinc = 0;
114530
114531   /* Ensure the database schema has been loaded */
114532   sqlcipher3_mutex_enter(db->mutex);
114533   sqlcipher3BtreeEnterAll(db);
114534   rc = sqlcipher3Init(db, &zErrMsg);
114535   if( SQLCIPHER_OK!=rc ){
114536     goto error_out;
114537   }
114538
114539   /* Locate the table in question */
114540   pTab = sqlcipher3FindTable(db, zTableName, zDbName);
114541   if( !pTab || pTab->pSelect ){
114542     pTab = 0;
114543     goto error_out;
114544   }
114545
114546   /* Find the column for which info is requested */
114547   if( sqlcipher3IsRowid(zColumnName) ){
114548     iCol = pTab->iPKey;
114549     if( iCol>=0 ){
114550       pCol = &pTab->aCol[iCol];
114551     }
114552   }else{
114553     for(iCol=0; iCol<pTab->nCol; iCol++){
114554       pCol = &pTab->aCol[iCol];
114555       if( 0==sqlcipher3StrICmp(pCol->zName, zColumnName) ){
114556         break;
114557       }
114558     }
114559     if( iCol==pTab->nCol ){
114560       pTab = 0;
114561       goto error_out;
114562     }
114563   }
114564
114565   /* The following block stores the meta information that will be returned
114566   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
114567   ** and autoinc. At this point there are two possibilities:
114568   ** 
114569   **     1. The specified column name was rowid", "oid" or "_rowid_" 
114570   **        and there is no explicitly declared IPK column. 
114571   **
114572   **     2. The table is not a view and the column name identified an 
114573   **        explicitly declared column. Copy meta information from *pCol.
114574   */ 
114575   if( pCol ){
114576     zDataType = pCol->zType;
114577     zCollSeq = pCol->zColl;
114578     notnull = pCol->notNull!=0;
114579     primarykey  = pCol->isPrimKey!=0;
114580     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
114581   }else{
114582     zDataType = "INTEGER";
114583     primarykey = 1;
114584   }
114585   if( !zCollSeq ){
114586     zCollSeq = "BINARY";
114587   }
114588
114589 error_out:
114590   sqlcipher3BtreeLeaveAll(db);
114591
114592   /* Whether the function call succeeded or failed, set the output parameters
114593   ** to whatever their local counterparts contain. If an error did occur,
114594   ** this has the effect of zeroing all output parameters.
114595   */
114596   if( pzDataType ) *pzDataType = zDataType;
114597   if( pzCollSeq ) *pzCollSeq = zCollSeq;
114598   if( pNotNull ) *pNotNull = notnull;
114599   if( pPrimaryKey ) *pPrimaryKey = primarykey;
114600   if( pAutoinc ) *pAutoinc = autoinc;
114601
114602   if( SQLCIPHER_OK==rc && !pTab ){
114603     sqlcipher3DbFree(db, zErrMsg);
114604     zErrMsg = sqlcipher3MPrintf(db, "no such table column: %s.%s", zTableName,
114605         zColumnName);
114606     rc = SQLCIPHER_ERROR;
114607   }
114608   sqlcipher3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
114609   sqlcipher3DbFree(db, zErrMsg);
114610   rc = sqlcipher3ApiExit(db, rc);
114611   sqlcipher3_mutex_leave(db->mutex);
114612   return rc;
114613 }
114614 #endif
114615
114616 /*
114617 ** Sleep for a little while.  Return the amount of time slept.
114618 */
114619 SQLCIPHER_API int sqlcipher3_sleep(int ms){
114620   sqlcipher3_vfs *pVfs;
114621   int rc;
114622   pVfs = sqlcipher3_vfs_find(0);
114623   if( pVfs==0 ) return 0;
114624
114625   /* This function works in milliseconds, but the underlying OsSleep() 
114626   ** API uses microseconds. Hence the 1000's.
114627   */
114628   rc = (sqlcipher3OsSleep(pVfs, 1000*ms)/1000);
114629   return rc;
114630 }
114631
114632 /*
114633 ** Enable or disable the extended result codes.
114634 */
114635 SQLCIPHER_API int sqlcipher3_extended_result_codes(sqlcipher3 *db, int onoff){
114636   sqlcipher3_mutex_enter(db->mutex);
114637   db->errMask = onoff ? 0xffffffff : 0xff;
114638   sqlcipher3_mutex_leave(db->mutex);
114639   return SQLCIPHER_OK;
114640 }
114641
114642 /*
114643 ** Invoke the xFileControl method on a particular database.
114644 */
114645 SQLCIPHER_API int sqlcipher3_file_control(sqlcipher3 *db, const char *zDbName, int op, void *pArg){
114646   int rc = SQLCIPHER_ERROR;
114647   int iDb;
114648   sqlcipher3_mutex_enter(db->mutex);
114649   if( zDbName==0 ){
114650     iDb = 0;
114651   }else{
114652     for(iDb=0; iDb<db->nDb; iDb++){
114653       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
114654     }
114655   }
114656   if( iDb<db->nDb ){
114657     Btree *pBtree = db->aDb[iDb].pBt;
114658     if( pBtree ){
114659       Pager *pPager;
114660       sqlcipher3_file *fd;
114661       sqlcipher3BtreeEnter(pBtree);
114662       pPager = sqlcipher3BtreePager(pBtree);
114663       assert( pPager!=0 );
114664       fd = sqlcipher3PagerFile(pPager);
114665       assert( fd!=0 );
114666       if( op==SQLCIPHER_FCNTL_FILE_POINTER ){
114667         *(sqlcipher3_file**)pArg = fd;
114668         rc = SQLCIPHER_OK;
114669       }else if( fd->pMethods ){
114670         rc = sqlcipher3OsFileControl(fd, op, pArg);
114671       }else{
114672         rc = SQLCIPHER_NOTFOUND;
114673       }
114674       sqlcipher3BtreeLeave(pBtree);
114675     }
114676   }
114677   sqlcipher3_mutex_leave(db->mutex);
114678   return rc;   
114679 }
114680
114681 /*
114682 ** Interface to the testing logic.
114683 */
114684 SQLCIPHER_API int sqlcipher3_test_control(int op, ...){
114685   int rc = 0;
114686 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
114687   va_list ap;
114688   va_start(ap, op);
114689   switch( op ){
114690
114691     /*
114692     ** Save the current state of the PRNG.
114693     */
114694     case SQLCIPHER_TESTCTRL_PRNG_SAVE: {
114695       sqlcipher3PrngSaveState();
114696       break;
114697     }
114698
114699     /*
114700     ** Restore the state of the PRNG to the last state saved using
114701     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
114702     ** this verb acts like PRNG_RESET.
114703     */
114704     case SQLCIPHER_TESTCTRL_PRNG_RESTORE: {
114705       sqlcipher3PrngRestoreState();
114706       break;
114707     }
114708
114709     /*
114710     ** Reset the PRNG back to its uninitialized state.  The next call
114711     ** to sqlcipher3_randomness() will reseed the PRNG using a single call
114712     ** to the xRandomness method of the default VFS.
114713     */
114714     case SQLCIPHER_TESTCTRL_PRNG_RESET: {
114715       sqlcipher3PrngResetState();
114716       break;
114717     }
114718
114719     /*
114720     **  sqlcipher3_test_control(BITVEC_TEST, size, program)
114721     **
114722     ** Run a test against a Bitvec object of size.  The program argument
114723     ** is an array of integers that defines the test.  Return -1 on a
114724     ** memory allocation error, 0 on success, or non-zero for an error.
114725     ** See the sqlcipher3BitvecBuiltinTest() for additional information.
114726     */
114727     case SQLCIPHER_TESTCTRL_BITVEC_TEST: {
114728       int sz = va_arg(ap, int);
114729       int *aProg = va_arg(ap, int*);
114730       rc = sqlcipher3BitvecBuiltinTest(sz, aProg);
114731       break;
114732     }
114733
114734     /*
114735     **  sqlcipher3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
114736     **
114737     ** Register hooks to call to indicate which malloc() failures 
114738     ** are benign.
114739     */
114740     case SQLCIPHER_TESTCTRL_BENIGN_MALLOC_HOOKS: {
114741       typedef void (*void_function)(void);
114742       void_function xBenignBegin;
114743       void_function xBenignEnd;
114744       xBenignBegin = va_arg(ap, void_function);
114745       xBenignEnd = va_arg(ap, void_function);
114746       sqlcipher3BenignMallocHooks(xBenignBegin, xBenignEnd);
114747       break;
114748     }
114749
114750     /*
114751     **  sqlcipher3_test_control(SQLCIPHER_TESTCTRL_PENDING_BYTE, unsigned int X)
114752     **
114753     ** Set the PENDING byte to the value in the argument, if X>0.
114754     ** Make no changes if X==0.  Return the value of the pending byte
114755     ** as it existing before this routine was called.
114756     **
114757     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
114758     ** an incompatible database file format.  Changing the PENDING byte
114759     ** while any database connection is open results in undefined and
114760     ** dileterious behavior.
114761     */
114762     case SQLCIPHER_TESTCTRL_PENDING_BYTE: {
114763       rc = PENDING_BYTE;
114764 #ifndef SQLCIPHER_OMIT_WSD
114765       {
114766         unsigned int newVal = va_arg(ap, unsigned int);
114767         if( newVal ) sqlcipher3PendingByte = newVal;
114768       }
114769 #endif
114770       break;
114771     }
114772
114773     /*
114774     **  sqlcipher3_test_control(SQLCIPHER_TESTCTRL_ASSERT, int X)
114775     **
114776     ** This action provides a run-time test to see whether or not
114777     ** assert() was enabled at compile-time.  If X is true and assert()
114778     ** is enabled, then the return value is true.  If X is true and
114779     ** assert() is disabled, then the return value is zero.  If X is
114780     ** false and assert() is enabled, then the assertion fires and the
114781     ** process aborts.  If X is false and assert() is disabled, then the
114782     ** return value is zero.
114783     */
114784     case SQLCIPHER_TESTCTRL_ASSERT: {
114785       volatile int x = 0;
114786       assert( (x = va_arg(ap,int))!=0 );
114787       rc = x;
114788       break;
114789     }
114790
114791
114792     /*
114793     **  sqlcipher3_test_control(SQLCIPHER_TESTCTRL_ALWAYS, int X)
114794     **
114795     ** This action provides a run-time test to see how the ALWAYS and
114796     ** NEVER macros were defined at compile-time.
114797     **
114798     ** The return value is ALWAYS(X).  
114799     **
114800     ** The recommended test is X==2.  If the return value is 2, that means
114801     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
114802     ** default setting.  If the return value is 1, then ALWAYS() is either
114803     ** hard-coded to true or else it asserts if its argument is false.
114804     ** The first behavior (hard-coded to true) is the case if
114805     ** SQLCIPHER_TESTCTRL_ASSERT shows that assert() is disabled and the second
114806     ** behavior (assert if the argument to ALWAYS() is false) is the case if
114807     ** SQLCIPHER_TESTCTRL_ASSERT shows that assert() is enabled.
114808     **
114809     ** The run-time test procedure might look something like this:
114810     **
114811     **    if( sqlcipher3_test_control(SQLCIPHER_TESTCTRL_ALWAYS, 2)==2 ){
114812     **      // ALWAYS() and NEVER() are no-op pass-through macros
114813     **    }else if( sqlcipher3_test_control(SQLCIPHER_TESTCTRL_ASSERT, 1) ){
114814     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
114815     **    }else{
114816     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
114817     **    }
114818     */
114819     case SQLCIPHER_TESTCTRL_ALWAYS: {
114820       int x = va_arg(ap,int);
114821       rc = ALWAYS(x);
114822       break;
114823     }
114824
114825     /*   sqlcipher3_test_control(SQLCIPHER_TESTCTRL_RESERVE, sqlcipher3 *db, int N)
114826     **
114827     ** Set the nReserve size to N for the main database on the database
114828     ** connection db.
114829     */
114830     case SQLCIPHER_TESTCTRL_RESERVE: {
114831       sqlcipher3 *db = va_arg(ap, sqlcipher3*);
114832       int x = va_arg(ap,int);
114833       sqlcipher3_mutex_enter(db->mutex);
114834       sqlcipher3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
114835       sqlcipher3_mutex_leave(db->mutex);
114836       break;
114837     }
114838
114839     /*  sqlcipher3_test_control(SQLCIPHER_TESTCTRL_OPTIMIZATIONS, sqlcipher3 *db, int N)
114840     **
114841     ** Enable or disable various optimizations for testing purposes.  The 
114842     ** argument N is a bitmask of optimizations to be disabled.  For normal
114843     ** operation N should be 0.  The idea is that a test program (like the
114844     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
114845     ** with various optimizations disabled to verify that the same answer
114846     ** is obtained in every case.
114847     */
114848     case SQLCIPHER_TESTCTRL_OPTIMIZATIONS: {
114849       sqlcipher3 *db = va_arg(ap, sqlcipher3*);
114850       int x = va_arg(ap,int);
114851       db->flags = (x & SQLCIPHER_OptMask) | (db->flags & ~SQLCIPHER_OptMask);
114852       break;
114853     }
114854
114855 #ifdef SQLCIPHER_N_KEYWORD
114856     /* sqlcipher3_test_control(SQLCIPHER_TESTCTRL_ISKEYWORD, const char *zWord)
114857     **
114858     ** If zWord is a keyword recognized by the parser, then return the
114859     ** number of keywords.  Or if zWord is not a keyword, return 0.
114860     ** 
114861     ** This test feature is only available in the amalgamation since
114862     ** the SQLCIPHER_N_KEYWORD macro is not defined in this file if SQLite
114863     ** is built using separate source files.
114864     */
114865     case SQLCIPHER_TESTCTRL_ISKEYWORD: {
114866       const char *zWord = va_arg(ap, const char*);
114867       int n = sqlcipher3Strlen30(zWord);
114868       rc = (sqlcipher3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLCIPHER_N_KEYWORD : 0;
114869       break;
114870     }
114871 #endif 
114872
114873     /* sqlcipher3_test_control(SQLCIPHER_TESTCTRL_PGHDRSZ)
114874     **
114875     ** Return the size of a pcache header in bytes.
114876     */
114877     case SQLCIPHER_TESTCTRL_PGHDRSZ: {
114878       rc = sizeof(PgHdr);
114879       break;
114880     }
114881
114882     /* sqlcipher3_test_control(SQLCIPHER_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
114883     **
114884     ** Pass pFree into sqlcipher3ScratchFree(). 
114885     ** If sz>0 then allocate a scratch buffer into pNew.  
114886     */
114887     case SQLCIPHER_TESTCTRL_SCRATCHMALLOC: {
114888       void *pFree, **ppNew;
114889       int sz;
114890       sz = va_arg(ap, int);
114891       ppNew = va_arg(ap, void**);
114892       pFree = va_arg(ap, void*);
114893       if( sz ) *ppNew = sqlcipher3ScratchMalloc(sz);
114894       sqlcipher3ScratchFree(pFree);
114895       break;
114896     }
114897
114898     /*   sqlcipher3_test_control(SQLCIPHER_TESTCTRL_LOCALTIME_FAULT, int onoff);
114899     **
114900     ** If parameter onoff is non-zero, configure the wrappers so that all
114901     ** subsequent calls to localtime() and variants fail. If onoff is zero,
114902     ** undo this setting.
114903     */
114904     case SQLCIPHER_TESTCTRL_LOCALTIME_FAULT: {
114905       sqlcipher3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
114906       break;
114907     }
114908
114909   }
114910   va_end(ap);
114911 #endif /* SQLCIPHER_OMIT_BUILTIN_TEST */
114912   return rc;
114913 }
114914
114915 /*
114916 ** This is a utility routine, useful to VFS implementations, that checks
114917 ** to see if a database file was a URI that contained a specific query 
114918 ** parameter, and if so obtains the value of the query parameter.
114919 **
114920 ** The zFilename argument is the filename pointer passed into the xOpen()
114921 ** method of a VFS implementation.  The zParam argument is the name of the
114922 ** query parameter we seek.  This routine returns the value of the zParam
114923 ** parameter if it exists.  If the parameter does not exist, this routine
114924 ** returns a NULL pointer.
114925 */
114926 SQLCIPHER_API const char *sqlcipher3_uri_parameter(const char *zFilename, const char *zParam){
114927   zFilename += sqlcipher3Strlen30(zFilename) + 1;
114928   while( zFilename[0] ){
114929     int x = strcmp(zFilename, zParam);
114930     zFilename += sqlcipher3Strlen30(zFilename) + 1;
114931     if( x==0 ) return zFilename;
114932     zFilename += sqlcipher3Strlen30(zFilename) + 1;
114933   }
114934   return 0;
114935 }
114936
114937 /************** End of main.c ************************************************/
114938 /************** Begin file notify.c ******************************************/
114939 /*
114940 ** 2009 March 3
114941 **
114942 ** The author disclaims copyright to this source code.  In place of
114943 ** a legal notice, here is a blessing:
114944 **
114945 **    May you do good and not evil.
114946 **    May you find forgiveness for yourself and forgive others.
114947 **    May you share freely, never taking more than you give.
114948 **
114949 *************************************************************************
114950 **
114951 ** This file contains the implementation of the sqlcipher3_unlock_notify()
114952 ** API method and its associated functionality.
114953 */
114954
114955 /* Omit this entire file if SQLCIPHER_ENABLE_UNLOCK_NOTIFY is not defined. */
114956 #ifdef SQLCIPHER_ENABLE_UNLOCK_NOTIFY
114957
114958 /*
114959 ** Public interfaces:
114960 **
114961 **   sqlcipher3ConnectionBlocked()
114962 **   sqlcipher3ConnectionUnlocked()
114963 **   sqlcipher3ConnectionClosed()
114964 **   sqlcipher3_unlock_notify()
114965 */
114966
114967 #define assertMutexHeld() \
114968   assert( sqlcipher3_mutex_held(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER)) )
114969
114970 /*
114971 ** Head of a linked list of all sqlcipher3 objects created by this process
114972 ** for which either sqlcipher3.pBlockingConnection or sqlcipher3.pUnlockConnection
114973 ** is not NULL. This variable may only accessed while the STATIC_MASTER
114974 ** mutex is held.
114975 */
114976 static sqlcipher3 *SQLCIPHER_WSD sqlcipher3BlockedList = 0;
114977
114978 #ifndef NDEBUG
114979 /*
114980 ** This function is a complex assert() that verifies the following 
114981 ** properties of the blocked connections list:
114982 **
114983 **   1) Each entry in the list has a non-NULL value for either 
114984 **      pUnlockConnection or pBlockingConnection, or both.
114985 **
114986 **   2) All entries in the list that share a common value for 
114987 **      xUnlockNotify are grouped together.
114988 **
114989 **   3) If the argument db is not NULL, then none of the entries in the
114990 **      blocked connections list have pUnlockConnection or pBlockingConnection
114991 **      set to db. This is used when closing connection db.
114992 */
114993 static void checkListProperties(sqlcipher3 *db){
114994   sqlcipher3 *p;
114995   for(p=sqlcipher3BlockedList; p; p=p->pNextBlocked){
114996     int seen = 0;
114997     sqlcipher3 *p2;
114998
114999     /* Verify property (1) */
115000     assert( p->pUnlockConnection || p->pBlockingConnection );
115001
115002     /* Verify property (2) */
115003     for(p2=sqlcipher3BlockedList; p2!=p; p2=p2->pNextBlocked){
115004       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
115005       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
115006       assert( db==0 || p->pUnlockConnection!=db );
115007       assert( db==0 || p->pBlockingConnection!=db );
115008     }
115009   }
115010 }
115011 #else
115012 # define checkListProperties(x)
115013 #endif
115014
115015 /*
115016 ** Remove connection db from the blocked connections list. If connection
115017 ** db is not currently a part of the list, this function is a no-op.
115018 */
115019 static void removeFromBlockedList(sqlcipher3 *db){
115020   sqlcipher3 **pp;
115021   assertMutexHeld();
115022   for(pp=&sqlcipher3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
115023     if( *pp==db ){
115024       *pp = (*pp)->pNextBlocked;
115025       break;
115026     }
115027   }
115028 }
115029
115030 /*
115031 ** Add connection db to the blocked connections list. It is assumed
115032 ** that it is not already a part of the list.
115033 */
115034 static void addToBlockedList(sqlcipher3 *db){
115035   sqlcipher3 **pp;
115036   assertMutexHeld();
115037   for(
115038     pp=&sqlcipher3BlockedList; 
115039     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
115040     pp=&(*pp)->pNextBlocked
115041   );
115042   db->pNextBlocked = *pp;
115043   *pp = db;
115044 }
115045
115046 /*
115047 ** Obtain the STATIC_MASTER mutex.
115048 */
115049 static void enterMutex(void){
115050   sqlcipher3_mutex_enter(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
115051   checkListProperties(0);
115052 }
115053
115054 /*
115055 ** Release the STATIC_MASTER mutex.
115056 */
115057 static void leaveMutex(void){
115058   assertMutexHeld();
115059   checkListProperties(0);
115060   sqlcipher3_mutex_leave(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
115061 }
115062
115063 /*
115064 ** Register an unlock-notify callback.
115065 **
115066 ** This is called after connection "db" has attempted some operation
115067 ** but has received an SQLCIPHER_LOCKED error because another connection
115068 ** (call it pOther) in the same process was busy using the same shared
115069 ** cache.  pOther is found by looking at db->pBlockingConnection.
115070 **
115071 ** If there is no blocking connection, the callback is invoked immediately,
115072 ** before this routine returns.
115073 **
115074 ** If pOther is already blocked on db, then report SQLCIPHER_LOCKED, to indicate
115075 ** a deadlock.
115076 **
115077 ** Otherwise, make arrangements to invoke xNotify when pOther drops
115078 ** its locks.
115079 **
115080 ** Each call to this routine overrides any prior callbacks registered
115081 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
115082 ** cancelled.
115083 */
115084 SQLCIPHER_API int sqlcipher3_unlock_notify(
115085   sqlcipher3 *db,
115086   void (*xNotify)(void **, int),
115087   void *pArg
115088 ){
115089   int rc = SQLCIPHER_OK;
115090
115091   sqlcipher3_mutex_enter(db->mutex);
115092   enterMutex();
115093
115094   if( xNotify==0 ){
115095     removeFromBlockedList(db);
115096     db->pBlockingConnection = 0;
115097     db->pUnlockConnection = 0;
115098     db->xUnlockNotify = 0;
115099     db->pUnlockArg = 0;
115100   }else if( 0==db->pBlockingConnection ){
115101     /* The blocking transaction has been concluded. Or there never was a 
115102     ** blocking transaction. In either case, invoke the notify callback
115103     ** immediately. 
115104     */
115105     xNotify(&pArg, 1);
115106   }else{
115107     sqlcipher3 *p;
115108
115109     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
115110     if( p ){
115111       rc = SQLCIPHER_LOCKED;              /* Deadlock detected. */
115112     }else{
115113       db->pUnlockConnection = db->pBlockingConnection;
115114       db->xUnlockNotify = xNotify;
115115       db->pUnlockArg = pArg;
115116       removeFromBlockedList(db);
115117       addToBlockedList(db);
115118     }
115119   }
115120
115121   leaveMutex();
115122   assert( !db->mallocFailed );
115123   sqlcipher3Error(db, rc, (rc?"database is deadlocked":0));
115124   sqlcipher3_mutex_leave(db->mutex);
115125   return rc;
115126 }
115127
115128 /*
115129 ** This function is called while stepping or preparing a statement 
115130 ** associated with connection db. The operation will return SQLCIPHER_LOCKED
115131 ** to the user because it requires a lock that will not be available
115132 ** until connection pBlocker concludes its current transaction.
115133 */
115134 SQLCIPHER_PRIVATE void sqlcipher3ConnectionBlocked(sqlcipher3 *db, sqlcipher3 *pBlocker){
115135   enterMutex();
115136   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
115137     addToBlockedList(db);
115138   }
115139   db->pBlockingConnection = pBlocker;
115140   leaveMutex();
115141 }
115142
115143 /*
115144 ** This function is called when
115145 ** the transaction opened by database db has just finished. Locks held 
115146 ** by database connection db have been released.
115147 **
115148 ** This function loops through each entry in the blocked connections
115149 ** list and does the following:
115150 **
115151 **   1) If the sqlcipher3.pBlockingConnection member of a list entry is
115152 **      set to db, then set pBlockingConnection=0.
115153 **
115154 **   2) If the sqlcipher3.pUnlockConnection member of a list entry is
115155 **      set to db, then invoke the configured unlock-notify callback and
115156 **      set pUnlockConnection=0.
115157 **
115158 **   3) If the two steps above mean that pBlockingConnection==0 and
115159 **      pUnlockConnection==0, remove the entry from the blocked connections
115160 **      list.
115161 */
115162 SQLCIPHER_PRIVATE void sqlcipher3ConnectionUnlocked(sqlcipher3 *db){
115163   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
115164   int nArg = 0;                            /* Number of entries in aArg[] */
115165   sqlcipher3 **pp;                            /* Iterator variable */
115166   void **aArg;               /* Arguments to the unlock callback */
115167   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
115168   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
115169
115170   aArg = aStatic;
115171   enterMutex();         /* Enter STATIC_MASTER mutex */
115172
115173   /* This loop runs once for each entry in the blocked-connections list. */
115174   for(pp=&sqlcipher3BlockedList; *pp; /* no-op */ ){
115175     sqlcipher3 *p = *pp;
115176
115177     /* Step 1. */
115178     if( p->pBlockingConnection==db ){
115179       p->pBlockingConnection = 0;
115180     }
115181
115182     /* Step 2. */
115183     if( p->pUnlockConnection==db ){
115184       assert( p->xUnlockNotify );
115185       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
115186         xUnlockNotify(aArg, nArg);
115187         nArg = 0;
115188       }
115189
115190       sqlcipher3BeginBenignMalloc();
115191       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
115192       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
115193       if( (!aDyn && nArg==(int)ArraySize(aStatic))
115194        || (aDyn && nArg==(int)(sqlcipher3MallocSize(aDyn)/sizeof(void*)))
115195       ){
115196         /* The aArg[] array needs to grow. */
115197         void **pNew = (void **)sqlcipher3Malloc(nArg*sizeof(void *)*2);
115198         if( pNew ){
115199           memcpy(pNew, aArg, nArg*sizeof(void *));
115200           sqlcipher3_free(aDyn);
115201           aDyn = aArg = pNew;
115202         }else{
115203           /* This occurs when the array of context pointers that need to
115204           ** be passed to the unlock-notify callback is larger than the
115205           ** aStatic[] array allocated on the stack and the attempt to 
115206           ** allocate a larger array from the heap has failed.
115207           **
115208           ** This is a difficult situation to handle. Returning an error
115209           ** code to the caller is insufficient, as even if an error code
115210           ** is returned the transaction on connection db will still be
115211           ** closed and the unlock-notify callbacks on blocked connections
115212           ** will go unissued. This might cause the application to wait
115213           ** indefinitely for an unlock-notify callback that will never 
115214           ** arrive.
115215           **
115216           ** Instead, invoke the unlock-notify callback with the context
115217           ** array already accumulated. We can then clear the array and
115218           ** begin accumulating any further context pointers without 
115219           ** requiring any dynamic allocation. This is sub-optimal because
115220           ** it means that instead of one callback with a large array of
115221           ** context pointers the application will receive two or more
115222           ** callbacks with smaller arrays of context pointers, which will
115223           ** reduce the applications ability to prioritize multiple 
115224           ** connections. But it is the best that can be done under the
115225           ** circumstances.
115226           */
115227           xUnlockNotify(aArg, nArg);
115228           nArg = 0;
115229         }
115230       }
115231       sqlcipher3EndBenignMalloc();
115232
115233       aArg[nArg++] = p->pUnlockArg;
115234       xUnlockNotify = p->xUnlockNotify;
115235       p->pUnlockConnection = 0;
115236       p->xUnlockNotify = 0;
115237       p->pUnlockArg = 0;
115238     }
115239
115240     /* Step 3. */
115241     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
115242       /* Remove connection p from the blocked connections list. */
115243       *pp = p->pNextBlocked;
115244       p->pNextBlocked = 0;
115245     }else{
115246       pp = &p->pNextBlocked;
115247     }
115248   }
115249
115250   if( nArg!=0 ){
115251     xUnlockNotify(aArg, nArg);
115252   }
115253   sqlcipher3_free(aDyn);
115254   leaveMutex();         /* Leave STATIC_MASTER mutex */
115255 }
115256
115257 /*
115258 ** This is called when the database connection passed as an argument is 
115259 ** being closed. The connection is removed from the blocked list.
115260 */
115261 SQLCIPHER_PRIVATE void sqlcipher3ConnectionClosed(sqlcipher3 *db){
115262   sqlcipher3ConnectionUnlocked(db);
115263   enterMutex();
115264   removeFromBlockedList(db);
115265   checkListProperties(db);
115266   leaveMutex();
115267 }
115268 #endif
115269
115270 /************** End of notify.c **********************************************/
115271 /************** Begin file fts3.c ********************************************/
115272 /*
115273 ** 2006 Oct 10
115274 **
115275 ** The author disclaims copyright to this source code.  In place of
115276 ** a legal notice, here is a blessing:
115277 **
115278 **    May you do good and not evil.
115279 **    May you find forgiveness for yourself and forgive others.
115280 **    May you share freely, never taking more than you give.
115281 **
115282 ******************************************************************************
115283 **
115284 ** This is an SQLite module implementing full-text search.
115285 */
115286
115287 /*
115288 ** The code in this file is only compiled if:
115289 **
115290 **     * The FTS3 module is being built as an extension
115291 **       (in which case SQLCIPHER_CORE is not defined), or
115292 **
115293 **     * The FTS3 module is being built into the core of
115294 **       SQLite (in which case SQLCIPHER_ENABLE_FTS3 is defined).
115295 */
115296
115297 /* The full-text index is stored in a series of b+tree (-like)
115298 ** structures called segments which map terms to doclists.  The
115299 ** structures are like b+trees in layout, but are constructed from the
115300 ** bottom up in optimal fashion and are not updatable.  Since trees
115301 ** are built from the bottom up, things will be described from the
115302 ** bottom up.
115303 **
115304 **
115305 **** Varints ****
115306 ** The basic unit of encoding is a variable-length integer called a
115307 ** varint.  We encode variable-length integers in little-endian order
115308 ** using seven bits * per byte as follows:
115309 **
115310 ** KEY:
115311 **         A = 0xxxxxxx    7 bits of data and one flag bit
115312 **         B = 1xxxxxxx    7 bits of data and one flag bit
115313 **
115314 **  7 bits - A
115315 ** 14 bits - BA
115316 ** 21 bits - BBA
115317 ** and so on.
115318 **
115319 ** This is similar in concept to how sqlcipher encodes "varints" but
115320 ** the encoding is not the same.  SQLite varints are big-endian
115321 ** are are limited to 9 bytes in length whereas FTS3 varints are
115322 ** little-endian and can be up to 10 bytes in length (in theory).
115323 **
115324 ** Example encodings:
115325 **
115326 **     1:    0x01
115327 **   127:    0x7f
115328 **   128:    0x81 0x00
115329 **
115330 **
115331 **** Document lists ****
115332 ** A doclist (document list) holds a docid-sorted list of hits for a
115333 ** given term.  Doclists hold docids and associated token positions.
115334 ** A docid is the unique integer identifier for a single document.
115335 ** A position is the index of a word within the document.  The first 
115336 ** word of the document has a position of 0.
115337 **
115338 ** FTS3 used to optionally store character offsets using a compile-time
115339 ** option.  But that functionality is no longer supported.
115340 **
115341 ** A doclist is stored like this:
115342 **
115343 ** array {
115344 **   varint docid;
115345 **   array {                (position list for column 0)
115346 **     varint position;     (2 more than the delta from previous position)
115347 **   }
115348 **   array {
115349 **     varint POS_COLUMN;   (marks start of position list for new column)
115350 **     varint column;       (index of new column)
115351 **     array {
115352 **       varint position;   (2 more than the delta from previous position)
115353 **     }
115354 **   }
115355 **   varint POS_END;        (marks end of positions for this document.
115356 ** }
115357 **
115358 ** Here, array { X } means zero or more occurrences of X, adjacent in
115359 ** memory.  A "position" is an index of a token in the token stream
115360 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
115361 ** in the same logical place as the position element, and act as sentinals
115362 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
115363 ** The positions numbers are not stored literally but rather as two more
115364 ** than the difference from the prior position, or the just the position plus
115365 ** 2 for the first position.  Example:
115366 **
115367 **   label:       A B C D E  F  G H   I  J K
115368 **   value:     123 5 9 1 1 14 35 0 234 72 0
115369 **
115370 ** The 123 value is the first docid.  For column zero in this document
115371 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
115372 ** at D signals the start of a new column; the 1 at E indicates that the
115373 ** new column is column number 1.  There are two positions at 12 and 45
115374 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
115375 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
115376 ** terminates with the 0 at K.
115377 **
115378 ** A "position-list" is the list of positions for multiple columns for
115379 ** a single docid.  A "column-list" is the set of positions for a single
115380 ** column.  Hence, a position-list consists of one or more column-lists,
115381 ** a document record consists of a docid followed by a position-list and
115382 ** a doclist consists of one or more document records.
115383 **
115384 ** A bare doclist omits the position information, becoming an 
115385 ** array of varint-encoded docids.
115386 **
115387 **** Segment leaf nodes ****
115388 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
115389 ** nodes are written using LeafWriter, and read using LeafReader (to
115390 ** iterate through a single leaf node's data) and LeavesReader (to
115391 ** iterate through a segment's entire leaf layer).  Leaf nodes have
115392 ** the format:
115393 **
115394 ** varint iHeight;             (height from leaf level, always 0)
115395 ** varint nTerm;               (length of first term)
115396 ** char pTerm[nTerm];          (content of first term)
115397 ** varint nDoclist;            (length of term's associated doclist)
115398 ** char pDoclist[nDoclist];    (content of doclist)
115399 ** array {
115400 **                             (further terms are delta-encoded)
115401 **   varint nPrefix;           (length of prefix shared with previous term)
115402 **   varint nSuffix;           (length of unshared suffix)
115403 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
115404 **   varint nDoclist;          (length of term's associated doclist)
115405 **   char pDoclist[nDoclist];  (content of doclist)
115406 ** }
115407 **
115408 ** Here, array { X } means zero or more occurrences of X, adjacent in
115409 ** memory.
115410 **
115411 ** Leaf nodes are broken into blocks which are stored contiguously in
115412 ** the %_segments table in sorted order.  This means that when the end
115413 ** of a node is reached, the next term is in the node with the next
115414 ** greater node id.
115415 **
115416 ** New data is spilled to a new leaf node when the current node
115417 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
115418 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
115419 ** node (a leaf node with a single term and doclist).  The goal of
115420 ** these settings is to pack together groups of small doclists while
115421 ** making it efficient to directly access large doclists.  The
115422 ** assumption is that large doclists represent terms which are more
115423 ** likely to be query targets.
115424 **
115425 ** TODO(shess) It may be useful for blocking decisions to be more
115426 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
115427 ** node rather than splitting into 2k and .5k nodes.  My intuition is
115428 ** that this might extend through 2x or 4x the pagesize.
115429 **
115430 **
115431 **** Segment interior nodes ****
115432 ** Segment interior nodes store blockids for subtree nodes and terms
115433 ** to describe what data is stored by the each subtree.  Interior
115434 ** nodes are written using InteriorWriter, and read using
115435 ** InteriorReader.  InteriorWriters are created as needed when
115436 ** SegmentWriter creates new leaf nodes, or when an interior node
115437 ** itself grows too big and must be split.  The format of interior
115438 ** nodes:
115439 **
115440 ** varint iHeight;           (height from leaf level, always >0)
115441 ** varint iBlockid;          (block id of node's leftmost subtree)
115442 ** optional {
115443 **   varint nTerm;           (length of first term)
115444 **   char pTerm[nTerm];      (content of first term)
115445 **   array {
115446 **                                (further terms are delta-encoded)
115447 **     varint nPrefix;            (length of shared prefix with previous term)
115448 **     varint nSuffix;            (length of unshared suffix)
115449 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
115450 **   }
115451 ** }
115452 **
115453 ** Here, optional { X } means an optional element, while array { X }
115454 ** means zero or more occurrences of X, adjacent in memory.
115455 **
115456 ** An interior node encodes n terms separating n+1 subtrees.  The
115457 ** subtree blocks are contiguous, so only the first subtree's blockid
115458 ** is encoded.  The subtree at iBlockid will contain all terms less
115459 ** than the first term encoded (or all terms if no term is encoded).
115460 ** Otherwise, for terms greater than or equal to pTerm[i] but less
115461 ** than pTerm[i+1], the subtree for that term will be rooted at
115462 ** iBlockid+i.  Interior nodes only store enough term data to
115463 ** distinguish adjacent children (if the rightmost term of the left
115464 ** child is "something", and the leftmost term of the right child is
115465 ** "wicked", only "w" is stored).
115466 **
115467 ** New data is spilled to a new interior node at the same height when
115468 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
115469 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
115470 ** interior nodes and making the tree too skinny.  The interior nodes
115471 ** at a given height are naturally tracked by interior nodes at
115472 ** height+1, and so on.
115473 **
115474 **
115475 **** Segment directory ****
115476 ** The segment directory in table %_segdir stores meta-information for
115477 ** merging and deleting segments, and also the root node of the
115478 ** segment's tree.
115479 **
115480 ** The root node is the top node of the segment's tree after encoding
115481 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
115482 ** This could be either a leaf node or an interior node.  If the top
115483 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
115484 ** and a new root interior node is generated (which should always fit
115485 ** within ROOT_MAX because it only needs space for 2 varints, the
115486 ** height and the blockid of the previous root).
115487 **
115488 ** The meta-information in the segment directory is:
115489 **   level               - segment level (see below)
115490 **   idx                 - index within level
115491 **                       - (level,idx uniquely identify a segment)
115492 **   start_block         - first leaf node
115493 **   leaves_end_block    - last leaf node
115494 **   end_block           - last block (including interior nodes)
115495 **   root                - contents of root node
115496 **
115497 ** If the root node is a leaf node, then start_block,
115498 ** leaves_end_block, and end_block are all 0.
115499 **
115500 **
115501 **** Segment merging ****
115502 ** To amortize update costs, segments are grouped into levels and
115503 ** merged in batches.  Each increase in level represents exponentially
115504 ** more documents.
115505 **
115506 ** New documents (actually, document updates) are tokenized and
115507 ** written individually (using LeafWriter) to a level 0 segment, with
115508 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
115509 ** level 0 segments are merged into a single level 1 segment.  Level 1
115510 ** is populated like level 0, and eventually MERGE_COUNT level 1
115511 ** segments are merged to a single level 2 segment (representing
115512 ** MERGE_COUNT^2 updates), and so on.
115513 **
115514 ** A segment merge traverses all segments at a given level in
115515 ** parallel, performing a straightforward sorted merge.  Since segment
115516 ** leaf nodes are written in to the %_segments table in order, this
115517 ** merge traverses the underlying sqlcipher disk structures efficiently.
115518 ** After the merge, all segment blocks from the merged level are
115519 ** deleted.
115520 **
115521 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
115522 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
115523 ** very similar performance numbers to 16 on insertion, though they're
115524 ** a tiny bit slower (perhaps due to more overhead in merge-time
115525 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
115526 ** 16, 2 about 66% slower than 16.
115527 **
115528 ** At query time, high MERGE_COUNT increases the number of segments
115529 ** which need to be scanned and merged.  For instance, with 100k docs
115530 ** inserted:
115531 **
115532 **    MERGE_COUNT   segments
115533 **       16           25
115534 **        8           12
115535 **        4           10
115536 **        2            6
115537 **
115538 ** This appears to have only a moderate impact on queries for very
115539 ** frequent terms (which are somewhat dominated by segment merge
115540 ** costs), and infrequent and non-existent terms still seem to be fast
115541 ** even with many segments.
115542 **
115543 ** TODO(shess) That said, it would be nice to have a better query-side
115544 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
115545 ** optimizations to things like doclist merging will swing the sweet
115546 ** spot around.
115547 **
115548 **
115549 **
115550 **** Handling of deletions and updates ****
115551 ** Since we're using a segmented structure, with no docid-oriented
115552 ** index into the term index, we clearly cannot simply update the term
115553 ** index when a document is deleted or updated.  For deletions, we
115554 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
115555 ** we simply write the new doclist.  Segment merges overwrite older
115556 ** data for a particular docid with newer data, so deletes or updates
115557 ** will eventually overtake the earlier data and knock it out.  The
115558 ** query logic likewise merges doclists so that newer data knocks out
115559 ** older data.
115560 **
115561 ** TODO(shess) Provide a VACUUM type operation to clear out all
115562 ** deletions and duplications.  This would basically be a forced merge
115563 ** into a single segment.
115564 */
115565
115566 /************** Include fts3Int.h in the middle of fts3.c ********************/
115567 /************** Begin file fts3Int.h *****************************************/
115568 /*
115569 ** 2009 Nov 12
115570 **
115571 ** The author disclaims copyright to this source code.  In place of
115572 ** a legal notice, here is a blessing:
115573 **
115574 **    May you do good and not evil.
115575 **    May you find forgiveness for yourself and forgive others.
115576 **    May you share freely, never taking more than you give.
115577 **
115578 ******************************************************************************
115579 **
115580 */
115581 #ifndef _FTSINT_H
115582 #define _FTSINT_H
115583
115584 #if !defined(NDEBUG) && !defined(SQLCIPHER_DEBUG) 
115585 # define NDEBUG 1
115586 #endif
115587
115588 /*
115589 ** FTS4 is really an extension for FTS3.  It is enabled using the
115590 ** SQLCIPHER_ENABLE_FTS3 macro.  But to avoid confusion we also all
115591 ** the SQLCIPHER_ENABLE_FTS4 macro to serve as an alisse for SQLCIPHER_ENABLE_FTS3.
115592 */
115593 #if defined(SQLCIPHER_ENABLE_FTS4) && !defined(SQLCIPHER_ENABLE_FTS3)
115594 # define SQLCIPHER_ENABLE_FTS3
115595 #endif
115596
115597 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
115598
115599 /* If not building as part of the core, include sqlcipher3ext.h. */
115600 #ifndef SQLCIPHER_CORE
115601 SQLCIPHER_API extern const sqlcipher3_api_routines *sqlcipher3_api;
115602 #endif
115603
115604 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
115605 /************** Begin file fts3_tokenizer.h **********************************/
115606 /*
115607 ** 2006 July 10
115608 **
115609 ** The author disclaims copyright to this source code.
115610 **
115611 *************************************************************************
115612 ** Defines the interface to tokenizers used by fulltext-search.  There
115613 ** are three basic components:
115614 **
115615 ** sqlcipher3_tokenizer_module is a singleton defining the tokenizer
115616 ** interface functions.  This is essentially the class structure for
115617 ** tokenizers.
115618 **
115619 ** sqlcipher3_tokenizer is used to define a particular tokenizer, perhaps
115620 ** including customization information defined at creation time.
115621 **
115622 ** sqlcipher3_tokenizer_cursor is generated by a tokenizer to generate
115623 ** tokens from a particular input.
115624 */
115625 #ifndef _FTS3_TOKENIZER_H_
115626 #define _FTS3_TOKENIZER_H_
115627
115628 /* TODO(shess) Only used for SQLCIPHER_OK and SQLCIPHER_DONE at this time.
115629 ** If tokenizers are to be allowed to call sqlcipher3_*() functions, then
115630 ** we will need a way to register the API consistently.
115631 */
115632
115633 /*
115634 ** Structures used by the tokenizer interface. When a new tokenizer
115635 ** implementation is registered, the caller provides a pointer to
115636 ** an sqlcipher3_tokenizer_module containing pointers to the callback
115637 ** functions that make up an implementation.
115638 **
115639 ** When an fts3 table is created, it passes any arguments passed to
115640 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
115641 ** sqlcipher3_tokenizer_module.xCreate() function of the requested tokenizer
115642 ** implementation. The xCreate() function in turn returns an 
115643 ** sqlcipher3_tokenizer structure representing the specific tokenizer to
115644 ** be used for the fts3 table (customized by the tokenizer clause arguments).
115645 **
115646 ** To tokenize an input buffer, the sqlcipher3_tokenizer_module.xOpen()
115647 ** method is called. It returns an sqlcipher3_tokenizer_cursor object
115648 ** that may be used to tokenize a specific input buffer based on
115649 ** the tokenization rules supplied by a specific sqlcipher3_tokenizer
115650 ** object.
115651 */
115652 typedef struct sqlcipher3_tokenizer_module sqlcipher3_tokenizer_module;
115653 typedef struct sqlcipher3_tokenizer sqlcipher3_tokenizer;
115654 typedef struct sqlcipher3_tokenizer_cursor sqlcipher3_tokenizer_cursor;
115655
115656 struct sqlcipher3_tokenizer_module {
115657
115658   /*
115659   ** Structure version. Should always be set to 0.
115660   */
115661   int iVersion;
115662
115663   /*
115664   ** Create a new tokenizer. The values in the argv[] array are the
115665   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
115666   ** TABLE statement that created the fts3 table. For example, if
115667   ** the following SQL is executed:
115668   **
115669   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
115670   **
115671   ** then argc is set to 2, and the argv[] array contains pointers
115672   ** to the strings "arg1" and "arg2".
115673   **
115674   ** This method should return either SQLCIPHER_OK (0), or an SQLite error 
115675   ** code. If SQLCIPHER_OK is returned, then *ppTokenizer should be set
115676   ** to point at the newly created tokenizer structure. The generic
115677   ** sqlcipher3_tokenizer.pModule variable should not be initialised by
115678   ** this callback. The caller will do so.
115679   */
115680   int (*xCreate)(
115681     int argc,                           /* Size of argv array */
115682     const char *const*argv,             /* Tokenizer argument strings */
115683     sqlcipher3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
115684   );
115685
115686   /*
115687   ** Destroy an existing tokenizer. The fts3 module calls this method
115688   ** exactly once for each successful call to xCreate().
115689   */
115690   int (*xDestroy)(sqlcipher3_tokenizer *pTokenizer);
115691
115692   /*
115693   ** Create a tokenizer cursor to tokenize an input buffer. The caller
115694   ** is responsible for ensuring that the input buffer remains valid
115695   ** until the cursor is closed (using the xClose() method). 
115696   */
115697   int (*xOpen)(
115698     sqlcipher3_tokenizer *pTokenizer,       /* Tokenizer object */
115699     const char *pInput, int nBytes,      /* Input buffer */
115700     sqlcipher3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
115701   );
115702
115703   /*
115704   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
115705   ** method exactly once for each successful call to xOpen().
115706   */
115707   int (*xClose)(sqlcipher3_tokenizer_cursor *pCursor);
115708
115709   /*
115710   ** Retrieve the next token from the tokenizer cursor pCursor. This
115711   ** method should either return SQLCIPHER_OK and set the values of the
115712   ** "OUT" variables identified below, or SQLCIPHER_DONE to indicate that
115713   ** the end of the buffer has been reached, or an SQLite error code.
115714   **
115715   ** *ppToken should be set to point at a buffer containing the 
115716   ** normalized version of the token (i.e. after any case-folding and/or
115717   ** stemming has been performed). *pnBytes should be set to the length
115718   ** of this buffer in bytes. The input text that generated the token is
115719   ** identified by the byte offsets returned in *piStartOffset and
115720   ** *piEndOffset. *piStartOffset should be set to the index of the first
115721   ** byte of the token in the input buffer. *piEndOffset should be set
115722   ** to the index of the first byte just past the end of the token in
115723   ** the input buffer.
115724   **
115725   ** The buffer *ppToken is set to point at is managed by the tokenizer
115726   ** implementation. It is only required to be valid until the next call
115727   ** to xNext() or xClose(). 
115728   */
115729   /* TODO(shess) current implementation requires pInput to be
115730   ** nul-terminated.  This should either be fixed, or pInput/nBytes
115731   ** should be converted to zInput.
115732   */
115733   int (*xNext)(
115734     sqlcipher3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
115735     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
115736     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
115737     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
115738     int *piPosition      /* OUT: Number of tokens returned before this one */
115739   );
115740 };
115741
115742 struct sqlcipher3_tokenizer {
115743   const sqlcipher3_tokenizer_module *pModule;  /* The module for this tokenizer */
115744   /* Tokenizer implementations will typically add additional fields */
115745 };
115746
115747 struct sqlcipher3_tokenizer_cursor {
115748   sqlcipher3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
115749   /* Tokenizer implementations will typically add additional fields */
115750 };
115751
115752 int fts3_global_term_cnt(int iTerm, int iCol);
115753 int fts3_term_cnt(int iTerm, int iCol);
115754
115755
115756 #endif /* _FTS3_TOKENIZER_H_ */
115757
115758 /************** End of fts3_tokenizer.h **************************************/
115759 /************** Continuing where we left off in fts3Int.h ********************/
115760 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
115761 /************** Begin file fts3_hash.h ***************************************/
115762 /*
115763 ** 2001 September 22
115764 **
115765 ** The author disclaims copyright to this source code.  In place of
115766 ** a legal notice, here is a blessing:
115767 **
115768 **    May you do good and not evil.
115769 **    May you find forgiveness for yourself and forgive others.
115770 **    May you share freely, never taking more than you give.
115771 **
115772 *************************************************************************
115773 ** This is the header file for the generic hash-table implemenation
115774 ** used in SQLite.  We've modified it slightly to serve as a standalone
115775 ** hash table implementation for the full-text indexing module.
115776 **
115777 */
115778 #ifndef _FTS3_HASH_H_
115779 #define _FTS3_HASH_H_
115780
115781 /* Forward declarations of structures. */
115782 typedef struct Fts3Hash Fts3Hash;
115783 typedef struct Fts3HashElem Fts3HashElem;
115784
115785 /* A complete hash table is an instance of the following structure.
115786 ** The internals of this structure are intended to be opaque -- client
115787 ** code should not attempt to access or modify the fields of this structure
115788 ** directly.  Change this structure only by using the routines below.
115789 ** However, many of the "procedures" and "functions" for modifying and
115790 ** accessing this structure are really macros, so we can't really make
115791 ** this structure opaque.
115792 */
115793 struct Fts3Hash {
115794   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
115795   char copyKey;           /* True if copy of key made on insert */
115796   int count;              /* Number of entries in this table */
115797   Fts3HashElem *first;    /* The first element of the array */
115798   int htsize;             /* Number of buckets in the hash table */
115799   struct _fts3ht {        /* the hash table */
115800     int count;               /* Number of entries with this hash */
115801     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
115802   } *ht;
115803 };
115804
115805 /* Each element in the hash table is an instance of the following 
115806 ** structure.  All elements are stored on a single doubly-linked list.
115807 **
115808 ** Again, this structure is intended to be opaque, but it can't really
115809 ** be opaque because it is used by macros.
115810 */
115811 struct Fts3HashElem {
115812   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
115813   void *data;                /* Data associated with this element */
115814   void *pKey; int nKey;      /* Key associated with this element */
115815 };
115816
115817 /*
115818 ** There are 2 different modes of operation for a hash table:
115819 **
115820 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
115821 **                           (including the null-terminator, if any).  Case
115822 **                           is respected in comparisons.
115823 **
115824 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
115825 **                           memcmp() is used to compare keys.
115826 **
115827 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
115828 */
115829 #define FTS3_HASH_STRING    1
115830 #define FTS3_HASH_BINARY    2
115831
115832 /*
115833 ** Access routines.  To delete, insert a NULL pointer.
115834 */
115835 SQLCIPHER_PRIVATE void sqlcipher3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
115836 SQLCIPHER_PRIVATE void *sqlcipher3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
115837 SQLCIPHER_PRIVATE void *sqlcipher3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
115838 SQLCIPHER_PRIVATE void sqlcipher3Fts3HashClear(Fts3Hash*);
115839 SQLCIPHER_PRIVATE Fts3HashElem *sqlcipher3Fts3HashFindElem(const Fts3Hash *, const void *, int);
115840
115841 /*
115842 ** Shorthand for the functions above
115843 */
115844 #define fts3HashInit     sqlcipher3Fts3HashInit
115845 #define fts3HashInsert   sqlcipher3Fts3HashInsert
115846 #define fts3HashFind     sqlcipher3Fts3HashFind
115847 #define fts3HashClear    sqlcipher3Fts3HashClear
115848 #define fts3HashFindElem sqlcipher3Fts3HashFindElem
115849
115850 /*
115851 ** Macros for looping over all elements of a hash table.  The idiom is
115852 ** like this:
115853 **
115854 **   Fts3Hash h;
115855 **   Fts3HashElem *p;
115856 **   ...
115857 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
115858 **     SomeStructure *pData = fts3HashData(p);
115859 **     // do something with pData
115860 **   }
115861 */
115862 #define fts3HashFirst(H)  ((H)->first)
115863 #define fts3HashNext(E)   ((E)->next)
115864 #define fts3HashData(E)   ((E)->data)
115865 #define fts3HashKey(E)    ((E)->pKey)
115866 #define fts3HashKeysize(E) ((E)->nKey)
115867
115868 /*
115869 ** Number of entries in a hash table
115870 */
115871 #define fts3HashCount(H)  ((H)->count)
115872
115873 #endif /* _FTS3_HASH_H_ */
115874
115875 /************** End of fts3_hash.h *******************************************/
115876 /************** Continuing where we left off in fts3Int.h ********************/
115877
115878 /*
115879 ** This constant controls how often segments are merged. Once there are
115880 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
115881 ** segment of level N+1.
115882 */
115883 #define FTS3_MERGE_COUNT 16
115884
115885 /*
115886 ** This is the maximum amount of data (in bytes) to store in the 
115887 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
115888 ** populated as documents are inserted/updated/deleted in a transaction
115889 ** and used to create a new segment when the transaction is committed.
115890 ** However if this limit is reached midway through a transaction, a new 
115891 ** segment is created and the hash table cleared immediately.
115892 */
115893 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
115894
115895 /*
115896 ** Macro to return the number of elements in an array. SQLite has a
115897 ** similar macro called ArraySize(). Use a different name to avoid
115898 ** a collision when building an amalgamation with built-in FTS3.
115899 */
115900 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
115901
115902
115903 #ifndef MIN
115904 # define MIN(x,y) ((x)<(y)?(x):(y))
115905 #endif
115906
115907 /*
115908 ** Maximum length of a varint encoded integer. The varint format is different
115909 ** from that used by SQLite, so the maximum length is 10, not 9.
115910 */
115911 #define FTS3_VARINT_MAX 10
115912
115913 /*
115914 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
115915 ** in the document set and zero or more prefix indexes. All indexes are stored
115916 ** as one or more b+-trees in the %_segments and %_segdir tables. 
115917 **
115918 ** It is possible to determine which index a b+-tree belongs to based on the
115919 ** value stored in the "%_segdir.level" column. Given this value L, the index
115920 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
115921 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
115922 ** between 1024 and 2047 to index 1, and so on.
115923 **
115924 ** It is considered impossible for an index to use more than 1024 levels. In 
115925 ** theory though this may happen, but only after at least 
115926 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
115927 */
115928 #define FTS3_SEGDIR_MAXLEVEL      1024
115929 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
115930
115931 /*
115932 ** The testcase() macro is only used by the amalgamation.  If undefined,
115933 ** make it a no-op.
115934 */
115935 #ifndef testcase
115936 # define testcase(X)
115937 #endif
115938
115939 /*
115940 ** Terminator values for position-lists and column-lists.
115941 */
115942 #define POS_COLUMN  (1)     /* Column-list terminator */
115943 #define POS_END     (0)     /* Position-list terminator */ 
115944
115945 /*
115946 ** This section provides definitions to allow the
115947 ** FTS3 extension to be compiled outside of the 
115948 ** amalgamation.
115949 */
115950 #ifndef SQLCIPHER_AMALGAMATION
115951 /*
115952 ** Macros indicating that conditional expressions are always true or
115953 ** false.
115954 */
115955 #ifdef SQLCIPHER_COVERAGE_TEST
115956 # define ALWAYS(x) (1)
115957 # define NEVER(X)  (0)
115958 #else
115959 # define ALWAYS(x) (x)
115960 # define NEVER(X)  (x)
115961 #endif
115962
115963 /*
115964 ** Internal types used by SQLite.
115965 */
115966 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
115967 typedef short int i16;            /* 2-byte (or larger) signed integer */
115968 typedef unsigned int u32;         /* 4-byte unsigned integer */
115969 typedef sqlcipher3_uint64 u64;       /* 8-byte unsigned integer */
115970
115971 /*
115972 ** Macro used to suppress compiler warnings for unused parameters.
115973 */
115974 #define UNUSED_PARAMETER(x) (void)(x)
115975
115976 /*
115977 ** Activate assert() only if SQLCIPHER_TEST is enabled.
115978 */
115979 #if !defined(NDEBUG) && !defined(SQLCIPHER_DEBUG) 
115980 # define NDEBUG 1
115981 #endif
115982
115983 /*
115984 ** The TESTONLY macro is used to enclose variable declarations or
115985 ** other bits of code that are needed to support the arguments
115986 ** within testcase() and assert() macros.
115987 */
115988 #if defined(SQLCIPHER_DEBUG) || defined(SQLCIPHER_COVERAGE_TEST)
115989 # define TESTONLY(X)  X
115990 #else
115991 # define TESTONLY(X)
115992 #endif
115993
115994 #endif /* SQLCIPHER_AMALGAMATION */
115995
115996 #ifdef SQLCIPHER_DEBUG
115997 SQLCIPHER_PRIVATE int sqlcipher3Fts3Corrupt(void);
115998 # define FTS_CORRUPT_VTAB sqlcipher3Fts3Corrupt()
115999 #else
116000 # define FTS_CORRUPT_VTAB SQLCIPHER_CORRUPT_VTAB
116001 #endif
116002
116003 typedef struct Fts3Table Fts3Table;
116004 typedef struct Fts3Cursor Fts3Cursor;
116005 typedef struct Fts3Expr Fts3Expr;
116006 typedef struct Fts3Phrase Fts3Phrase;
116007 typedef struct Fts3PhraseToken Fts3PhraseToken;
116008
116009 typedef struct Fts3Doclist Fts3Doclist;
116010 typedef struct Fts3SegFilter Fts3SegFilter;
116011 typedef struct Fts3DeferredToken Fts3DeferredToken;
116012 typedef struct Fts3SegReader Fts3SegReader;
116013 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
116014
116015 /*
116016 ** A connection to a fulltext index is an instance of the following
116017 ** structure. The xCreate and xConnect methods create an instance
116018 ** of this structure and xDestroy and xDisconnect free that instance.
116019 ** All other methods receive a pointer to the structure as one of their
116020 ** arguments.
116021 */
116022 struct Fts3Table {
116023   sqlcipher3_vtab base;              /* Base class used by SQLite core */
116024   sqlcipher3 *db;                    /* The database connection */
116025   const char *zDb;                /* logical database name */
116026   const char *zName;              /* virtual table name */
116027   int nColumn;                    /* number of named columns in virtual table */
116028   char **azColumn;                /* column names.  malloced */
116029   sqlcipher3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
116030   char *zContentTbl;              /* content=xxx option, or NULL */
116031
116032   /* Precompiled statements used by the implementation. Each of these 
116033   ** statements is run and reset within a single virtual table API call. 
116034   */
116035   sqlcipher3_stmt *aStmt[27];
116036
116037   char *zReadExprlist;
116038   char *zWriteExprlist;
116039
116040   int nNodeSize;                  /* Soft limit for node size */
116041   u8 bHasStat;                    /* True if %_stat table exists */
116042   u8 bHasDocsize;                 /* True if %_docsize table exists */
116043   u8 bDescIdx;                    /* True if doclists are in reverse order */
116044   int nPgsz;                      /* Page size for host database */
116045   char *zSegmentsTbl;             /* Name of %_segments table */
116046   sqlcipher3_blob *pSegments;        /* Blob handle open on %_segments table */
116047
116048   /* TODO: Fix the first paragraph of this comment.
116049   **
116050   ** The following hash table is used to buffer pending index updates during
116051   ** transactions. Variable nPendingData estimates the memory size of the 
116052   ** pending data, including hash table overhead, but not malloc overhead. 
116053   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed 
116054   ** automatically. Variable iPrevDocid is the docid of the most recently
116055   ** inserted record.
116056   **
116057   ** A single FTS4 table may have multiple full-text indexes. For each index
116058   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
116059   ** terms that appear in the document set. Each subsequent index in aIndex[]
116060   ** is an index of prefixes of a specific length.
116061   */
116062   int nIndex;                     /* Size of aIndex[] */
116063   struct Fts3Index {
116064     int nPrefix;                  /* Prefix length (0 for main terms index) */
116065     Fts3Hash hPending;            /* Pending terms table for this index */
116066   } *aIndex;
116067   int nMaxPendingData;            /* Max pending data before flush to disk */
116068   int nPendingData;               /* Current bytes of pending data */
116069   sqlcipher_int64 iPrevDocid;        /* Docid of most recently inserted document */
116070
116071 #if defined(SQLCIPHER_DEBUG) || defined(SQLCIPHER_COVERAGE_TEST)
116072   /* State variables used for validating that the transaction control
116073   ** methods of the virtual table are called at appropriate times.  These
116074   ** values do not contribution to the FTS computation; they are used for
116075   ** verifying the SQLite core.
116076   */
116077   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
116078   int mxSavepoint;       /* Largest valid xSavepoint integer */
116079 #endif
116080 };
116081
116082 /*
116083 ** When the core wants to read from the virtual table, it creates a
116084 ** virtual table cursor (an instance of the following structure) using
116085 ** the xOpen method. Cursors are destroyed using the xClose method.
116086 */
116087 struct Fts3Cursor {
116088   sqlcipher3_vtab_cursor base;       /* Base class used by SQLite core */
116089   i16 eSearch;                    /* Search strategy (see below) */
116090   u8 isEof;                       /* True if at End Of Results */
116091   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
116092   sqlcipher3_stmt *pStmt;            /* Prepared statement in use by the cursor */
116093   Fts3Expr *pExpr;                /* Parsed MATCH query string */
116094   int nPhrase;                    /* Number of matchable phrases in query */
116095   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
116096   sqlcipher3_int64 iPrevId;          /* Previous id read from aDoclist */
116097   char *pNextId;                  /* Pointer into the body of aDoclist */
116098   char *aDoclist;                 /* List of docids for full-text queries */
116099   int nDoclist;                   /* Size of buffer at aDoclist */
116100   u8 bDesc;                       /* True to sort in descending order */
116101   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
116102   int nRowAvg;                    /* Average size of database rows, in pages */
116103   sqlcipher3_int64 nDoc;             /* Documents in table */
116104
116105   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
116106   u32 *aMatchinfo;                /* Information about most recent match */
116107   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
116108   char *zMatchinfo;               /* Matchinfo specification */
116109 };
116110
116111 #define FTS3_EVAL_FILTER    0
116112 #define FTS3_EVAL_NEXT      1
116113 #define FTS3_EVAL_MATCHINFO 2
116114
116115 /*
116116 ** The Fts3Cursor.eSearch member is always set to one of the following.
116117 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
116118 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
116119 ** of the column to be searched.  For example, in
116120 **
116121 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
116122 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
116123 ** 
116124 ** Because the LHS of the MATCH operator is 2nd column "b",
116125 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
116126 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
116127 ** indicating that all columns should be searched,
116128 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
116129 */
116130 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
116131 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
116132 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
116133
116134
116135 struct Fts3Doclist {
116136   char *aAll;                    /* Array containing doclist (or NULL) */
116137   int nAll;                      /* Size of a[] in bytes */
116138   char *pNextDocid;              /* Pointer to next docid */
116139
116140   sqlcipher3_int64 iDocid;          /* Current docid (if pList!=0) */
116141   int bFreeList;                 /* True if pList should be sqlcipher3_free()d */
116142   char *pList;                   /* Pointer to position list following iDocid */
116143   int nList;                     /* Length of position list */
116144 };
116145
116146 /*
116147 ** A "phrase" is a sequence of one or more tokens that must match in
116148 ** sequence.  A single token is the base case and the most common case.
116149 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
116150 ** nToken will be the number of tokens in the string.
116151 */
116152 struct Fts3PhraseToken {
116153   char *z;                        /* Text of the token */
116154   int n;                          /* Number of bytes in buffer z */
116155   int isPrefix;                   /* True if token ends with a "*" character */
116156   int bFirst;                     /* True if token must appear at position 0 */
116157
116158   /* Variables above this point are populated when the expression is
116159   ** parsed (by code in fts3_expr.c). Below this point the variables are
116160   ** used when evaluating the expression. */
116161   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
116162   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
116163 };
116164
116165 struct Fts3Phrase {
116166   /* Cache of doclist for this phrase. */
116167   Fts3Doclist doclist;
116168   int bIncr;                 /* True if doclist is loaded incrementally */
116169   int iDoclistToken;
116170
116171   /* Variables below this point are populated by fts3_expr.c when parsing 
116172   ** a MATCH expression. Everything above is part of the evaluation phase. 
116173   */
116174   int nToken;                /* Number of tokens in the phrase */
116175   int iColumn;               /* Index of column this phrase must match */
116176   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
116177 };
116178
116179 /*
116180 ** A tree of these objects forms the RHS of a MATCH operator.
116181 **
116182 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
116183 ** points to a malloced buffer, size nDoclist bytes, containing the results 
116184 ** of this phrase query in FTS3 doclist format. As usual, the initial 
116185 ** "Length" field found in doclists stored on disk is omitted from this 
116186 ** buffer.
116187 **
116188 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
116189 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
116190 ** where nCol is the number of columns in the queried FTS table. The array
116191 ** is populated as follows:
116192 **
116193 **   aMI[iCol*3 + 0] = Undefined
116194 **   aMI[iCol*3 + 1] = Number of occurrences
116195 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
116196 **
116197 ** The aMI array is allocated using sqlcipher3_malloc(). It should be freed 
116198 ** when the expression node is.
116199 */
116200 struct Fts3Expr {
116201   int eType;                 /* One of the FTSQUERY_XXX values defined below */
116202   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
116203   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
116204   Fts3Expr *pLeft;           /* Left operand */
116205   Fts3Expr *pRight;          /* Right operand */
116206   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
116207
116208   /* The following are used by the fts3_eval.c module. */
116209   sqlcipher3_int64 iDocid;      /* Current docid */
116210   u8 bEof;                   /* True this expression is at EOF already */
116211   u8 bStart;                 /* True if iDocid is valid */
116212   u8 bDeferred;              /* True if this expression is entirely deferred */
116213
116214   u32 *aMI;
116215 };
116216
116217 /*
116218 ** Candidate values for Fts3Query.eType. Note that the order of the first
116219 ** four values is in order of precedence when parsing expressions. For 
116220 ** example, the following:
116221 **
116222 **   "a OR b AND c NOT d NEAR e"
116223 **
116224 ** is equivalent to:
116225 **
116226 **   "a OR (b AND (c NOT (d NEAR e)))"
116227 */
116228 #define FTSQUERY_NEAR   1
116229 #define FTSQUERY_NOT    2
116230 #define FTSQUERY_AND    3
116231 #define FTSQUERY_OR     4
116232 #define FTSQUERY_PHRASE 5
116233
116234
116235 /* fts3_write.c */
116236 SQLCIPHER_PRIVATE int sqlcipher3Fts3UpdateMethod(sqlcipher3_vtab*,int,sqlcipher3_value**,sqlcipher3_int64*);
116237 SQLCIPHER_PRIVATE int sqlcipher3Fts3PendingTermsFlush(Fts3Table *);
116238 SQLCIPHER_PRIVATE void sqlcipher3Fts3PendingTermsClear(Fts3Table *);
116239 SQLCIPHER_PRIVATE int sqlcipher3Fts3Optimize(Fts3Table *);
116240 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderNew(int, sqlcipher3_int64,
116241   sqlcipher3_int64, sqlcipher3_int64, const char *, int, Fts3SegReader**);
116242 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderPending(
116243   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
116244 SQLCIPHER_PRIVATE void sqlcipher3Fts3SegReaderFree(Fts3SegReader *);
116245 SQLCIPHER_PRIVATE int sqlcipher3Fts3AllSegdirs(Fts3Table*, int, int, sqlcipher3_stmt **);
116246 SQLCIPHER_PRIVATE int sqlcipher3Fts3ReadLock(Fts3Table *);
116247 SQLCIPHER_PRIVATE int sqlcipher3Fts3ReadBlock(Fts3Table*, sqlcipher3_int64, char **, int*, int*);
116248
116249 SQLCIPHER_PRIVATE int sqlcipher3Fts3SelectDoctotal(Fts3Table *, sqlcipher3_stmt **);
116250 SQLCIPHER_PRIVATE int sqlcipher3Fts3SelectDocsize(Fts3Table *, sqlcipher3_int64, sqlcipher3_stmt **);
116251
116252 SQLCIPHER_PRIVATE void sqlcipher3Fts3FreeDeferredTokens(Fts3Cursor *);
116253 SQLCIPHER_PRIVATE int sqlcipher3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
116254 SQLCIPHER_PRIVATE int sqlcipher3Fts3CacheDeferredDoclists(Fts3Cursor *);
116255 SQLCIPHER_PRIVATE void sqlcipher3Fts3FreeDeferredDoclists(Fts3Cursor *);
116256 SQLCIPHER_PRIVATE void sqlcipher3Fts3SegmentsClose(Fts3Table *);
116257
116258 /* Special values interpreted by sqlcipher3SegReaderCursor() */
116259 #define FTS3_SEGCURSOR_PENDING        -1
116260 #define FTS3_SEGCURSOR_ALL            -2
116261
116262 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
116263 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
116264 SQLCIPHER_PRIVATE void sqlcipher3Fts3SegReaderFinish(Fts3MultiSegReader *);
116265
116266 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderCursor(
116267     Fts3Table *, int, int, const char *, int, int, int, Fts3MultiSegReader *);
116268
116269 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
116270 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
116271 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
116272 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
116273 #define FTS3_SEGMENT_PREFIX        0x00000008
116274 #define FTS3_SEGMENT_SCAN          0x00000010
116275 #define FTS3_SEGMENT_FIRST         0x00000020
116276
116277 /* Type passed as 4th argument to SegmentReaderIterate() */
116278 struct Fts3SegFilter {
116279   const char *zTerm;
116280   int nTerm;
116281   int iCol;
116282   int flags;
116283 };
116284
116285 struct Fts3MultiSegReader {
116286   /* Used internally by sqlcipher3Fts3SegReaderXXX() calls */
116287   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
116288   int nSegment;                   /* Size of apSegment array */
116289   int nAdvance;                   /* How many seg-readers to advance */
116290   Fts3SegFilter *pFilter;         /* Pointer to filter object */
116291   char *aBuffer;                  /* Buffer to merge doclists in */
116292   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
116293
116294   int iColFilter;                 /* If >=0, filter for this column */
116295   int bRestart;
116296
116297   /* Used by fts3.c only. */
116298   int nCost;                      /* Cost of running iterator */
116299   int bLookup;                    /* True if a lookup of a single entry. */
116300
116301   /* Output values. Valid only after Fts3SegReaderStep() returns SQLCIPHER_ROW. */
116302   char *zTerm;                    /* Pointer to term buffer */
116303   int nTerm;                      /* Size of zTerm in bytes */
116304   char *aDoclist;                 /* Pointer to doclist buffer */
116305   int nDoclist;                   /* Size of aDoclist[] in bytes */
116306 };
116307
116308 /* fts3.c */
116309 SQLCIPHER_PRIVATE int sqlcipher3Fts3PutVarint(char *, sqlcipher3_int64);
116310 SQLCIPHER_PRIVATE int sqlcipher3Fts3GetVarint(const char *, sqlcipher_int64 *);
116311 SQLCIPHER_PRIVATE int sqlcipher3Fts3GetVarint32(const char *, int *);
116312 SQLCIPHER_PRIVATE int sqlcipher3Fts3VarintLen(sqlcipher3_uint64);
116313 SQLCIPHER_PRIVATE void sqlcipher3Fts3Dequote(char *);
116314 SQLCIPHER_PRIVATE void sqlcipher3Fts3DoclistPrev(int,char*,int,char**,sqlcipher3_int64*,int*,u8*);
116315 SQLCIPHER_PRIVATE int sqlcipher3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
116316 SQLCIPHER_PRIVATE int sqlcipher3Fts3FirstFilter(sqlcipher3_int64, char *, int, char *);
116317
116318 /* fts3_tokenizer.c */
116319 SQLCIPHER_PRIVATE const char *sqlcipher3Fts3NextToken(const char *, int *);
116320 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitHashTable(sqlcipher3 *, Fts3Hash *, const char *);
116321 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
116322     sqlcipher3_tokenizer **, char **
116323 );
116324 SQLCIPHER_PRIVATE int sqlcipher3Fts3IsIdChar(char);
116325
116326 /* fts3_snippet.c */
116327 SQLCIPHER_PRIVATE void sqlcipher3Fts3Offsets(sqlcipher3_context*, Fts3Cursor*);
116328 SQLCIPHER_PRIVATE void sqlcipher3Fts3Snippet(sqlcipher3_context *, Fts3Cursor *, const char *,
116329   const char *, const char *, int, int
116330 );
116331 SQLCIPHER_PRIVATE void sqlcipher3Fts3Matchinfo(sqlcipher3_context *, Fts3Cursor *, const char *);
116332
116333 /* fts3_expr.c */
116334 SQLCIPHER_PRIVATE int sqlcipher3Fts3ExprParse(sqlcipher3_tokenizer *, 
116335   char **, int, int, int, const char *, int, Fts3Expr **
116336 );
116337 SQLCIPHER_PRIVATE void sqlcipher3Fts3ExprFree(Fts3Expr *);
116338 #ifdef SQLCIPHER_TEST
116339 SQLCIPHER_PRIVATE int sqlcipher3Fts3ExprInitTestInterface(sqlcipher3 *db);
116340 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitTerm(sqlcipher3 *db);
116341 #endif
116342
116343 /* fts3_aux.c */
116344 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitAux(sqlcipher3 *db);
116345
116346 SQLCIPHER_PRIVATE void sqlcipher3Fts3EvalPhraseCleanup(Fts3Phrase *);
116347
116348 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrIncrStart(
116349     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
116350 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrIncrNext(
116351     Fts3Table *, Fts3MultiSegReader *, sqlcipher3_int64 *, char **, int *);
116352 SQLCIPHER_PRIVATE char *sqlcipher3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol); 
116353 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
116354 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
116355
116356 SQLCIPHER_PRIVATE int sqlcipher3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
116357
116358 #endif /* !SQLCIPHER_CORE || SQLCIPHER_ENABLE_FTS3 */
116359 #endif /* _FTSINT_H */
116360
116361 /************** End of fts3Int.h *********************************************/
116362 /************** Continuing where we left off in fts3.c ***********************/
116363 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
116364
116365 #if defined(SQLCIPHER_ENABLE_FTS3) && !defined(SQLCIPHER_CORE)
116366 # define SQLCIPHER_CORE 1
116367 #endif
116368
116369 /* #include <assert.h> */
116370 /* #include <stdlib.h> */
116371 /* #include <stddef.h> */
116372 /* #include <stdio.h> */
116373 /* #include <string.h> */
116374 /* #include <stdarg.h> */
116375
116376 #ifndef SQLCIPHER_CORE 
116377   SQLCIPHER_EXTENSION_INIT1
116378 #endif
116379
116380 static int fts3EvalNext(Fts3Cursor *pCsr);
116381 static int fts3EvalStart(Fts3Cursor *pCsr);
116382 static int fts3TermSegReaderCursor(
116383     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
116384
116385 /* 
116386 ** Write a 64-bit variable-length integer to memory starting at p[0].
116387 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
116388 ** The number of bytes written is returned.
116389 */
116390 SQLCIPHER_PRIVATE int sqlcipher3Fts3PutVarint(char *p, sqlcipher_int64 v){
116391   unsigned char *q = (unsigned char *) p;
116392   sqlcipher_uint64 vu = v;
116393   do{
116394     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
116395     vu >>= 7;
116396   }while( vu!=0 );
116397   q[-1] &= 0x7f;  /* turn off high bit in final byte */
116398   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
116399   return (int) (q - (unsigned char *)p);
116400 }
116401
116402 /* 
116403 ** Read a 64-bit variable-length integer from memory starting at p[0].
116404 ** Return the number of bytes read, or 0 on error.
116405 ** The value is stored in *v.
116406 */
116407 SQLCIPHER_PRIVATE int sqlcipher3Fts3GetVarint(const char *p, sqlcipher_int64 *v){
116408   const unsigned char *q = (const unsigned char *) p;
116409   sqlcipher_uint64 x = 0, y = 1;
116410   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
116411     x += y * (*q++ & 0x7f);
116412     y <<= 7;
116413   }
116414   x += y * (*q++);
116415   *v = (sqlcipher_int64) x;
116416   return (int) (q - (unsigned char *)p);
116417 }
116418
116419 /*
116420 ** Similar to sqlcipher3Fts3GetVarint(), except that the output is truncated to a
116421 ** 32-bit integer before it is returned.
116422 */
116423 SQLCIPHER_PRIVATE int sqlcipher3Fts3GetVarint32(const char *p, int *pi){
116424  sqlcipher_int64 i;
116425  int ret = sqlcipher3Fts3GetVarint(p, &i);
116426  *pi = (int) i;
116427  return ret;
116428 }
116429
116430 /*
116431 ** Return the number of bytes required to encode v as a varint
116432 */
116433 SQLCIPHER_PRIVATE int sqlcipher3Fts3VarintLen(sqlcipher3_uint64 v){
116434   int i = 0;
116435   do{
116436     i++;
116437     v >>= 7;
116438   }while( v!=0 );
116439   return i;
116440 }
116441
116442 /*
116443 ** Convert an SQL-style quoted string into a normal string by removing
116444 ** the quote characters.  The conversion is done in-place.  If the
116445 ** input does not begin with a quote character, then this routine
116446 ** is a no-op.
116447 **
116448 ** Examples:
116449 **
116450 **     "abc"   becomes   abc
116451 **     'xyz'   becomes   xyz
116452 **     [pqr]   becomes   pqr
116453 **     `mno`   becomes   mno
116454 **
116455 */
116456 SQLCIPHER_PRIVATE void sqlcipher3Fts3Dequote(char *z){
116457   char quote;                     /* Quote character (if any ) */
116458
116459   quote = z[0];
116460   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
116461     int iIn = 1;                  /* Index of next byte to read from input */
116462     int iOut = 0;                 /* Index of next byte to write to output */
116463
116464     /* If the first byte was a '[', then the close-quote character is a ']' */
116465     if( quote=='[' ) quote = ']';  
116466
116467     while( ALWAYS(z[iIn]) ){
116468       if( z[iIn]==quote ){
116469         if( z[iIn+1]!=quote ) break;
116470         z[iOut++] = quote;
116471         iIn += 2;
116472       }else{
116473         z[iOut++] = z[iIn++];
116474       }
116475     }
116476     z[iOut] = '\0';
116477   }
116478 }
116479
116480 /*
116481 ** Read a single varint from the doclist at *pp and advance *pp to point
116482 ** to the first byte past the end of the varint.  Add the value of the varint
116483 ** to *pVal.
116484 */
116485 static void fts3GetDeltaVarint(char **pp, sqlcipher3_int64 *pVal){
116486   sqlcipher3_int64 iVal;
116487   *pp += sqlcipher3Fts3GetVarint(*pp, &iVal);
116488   *pVal += iVal;
116489 }
116490
116491 /*
116492 ** When this function is called, *pp points to the first byte following a
116493 ** varint that is part of a doclist (or position-list, or any other list
116494 ** of varints). This function moves *pp to point to the start of that varint,
116495 ** and sets *pVal by the varint value.
116496 **
116497 ** Argument pStart points to the first byte of the doclist that the
116498 ** varint is part of.
116499 */
116500 static void fts3GetReverseVarint(
116501   char **pp, 
116502   char *pStart, 
116503   sqlcipher3_int64 *pVal
116504 ){
116505   sqlcipher3_int64 iVal;
116506   char *p;
116507
116508   /* Pointer p now points at the first byte past the varint we are 
116509   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
116510   ** clear on character p[-1]. */
116511   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
116512   p++;
116513   *pp = p;
116514
116515   sqlcipher3Fts3GetVarint(p, &iVal);
116516   *pVal = iVal;
116517 }
116518
116519 /*
116520 ** The xDisconnect() virtual table method.
116521 */
116522 static int fts3DisconnectMethod(sqlcipher3_vtab *pVtab){
116523   Fts3Table *p = (Fts3Table *)pVtab;
116524   int i;
116525
116526   assert( p->nPendingData==0 );
116527   assert( p->pSegments==0 );
116528
116529   /* Free any prepared statements held */
116530   for(i=0; i<SizeofArray(p->aStmt); i++){
116531     sqlcipher3_finalize(p->aStmt[i]);
116532   }
116533   sqlcipher3_free(p->zSegmentsTbl);
116534   sqlcipher3_free(p->zReadExprlist);
116535   sqlcipher3_free(p->zWriteExprlist);
116536   sqlcipher3_free(p->zContentTbl);
116537
116538   /* Invoke the tokenizer destructor to free the tokenizer. */
116539   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
116540
116541   sqlcipher3_free(p);
116542   return SQLCIPHER_OK;
116543 }
116544
116545 /*
116546 ** Construct one or more SQL statements from the format string given
116547 ** and then evaluate those statements. The success code is written
116548 ** into *pRc.
116549 **
116550 ** If *pRc is initially non-zero then this routine is a no-op.
116551 */
116552 static void fts3DbExec(
116553   int *pRc,              /* Success code */
116554   sqlcipher3 *db,           /* Database in which to run SQL */
116555   const char *zFormat,   /* Format string for SQL */
116556   ...                    /* Arguments to the format string */
116557 ){
116558   va_list ap;
116559   char *zSql;
116560   if( *pRc ) return;
116561   va_start(ap, zFormat);
116562   zSql = sqlcipher3_vmprintf(zFormat, ap);
116563   va_end(ap);
116564   if( zSql==0 ){
116565     *pRc = SQLCIPHER_NOMEM;
116566   }else{
116567     *pRc = sqlcipher3_exec(db, zSql, 0, 0, 0);
116568     sqlcipher3_free(zSql);
116569   }
116570 }
116571
116572 /*
116573 ** The xDestroy() virtual table method.
116574 */
116575 static int fts3DestroyMethod(sqlcipher3_vtab *pVtab){
116576   Fts3Table *p = (Fts3Table *)pVtab;
116577   int rc = SQLCIPHER_OK;              /* Return code */
116578   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
116579   sqlcipher3 *db = p->db;             /* Database handle */
116580
116581   /* Drop the shadow tables */
116582   if( p->zContentTbl==0 ){
116583     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
116584   }
116585   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
116586   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
116587   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
116588   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
116589
116590   /* If everything has worked, invoke fts3DisconnectMethod() to free the
116591   ** memory associated with the Fts3Table structure and return SQLCIPHER_OK.
116592   ** Otherwise, return an SQLite error code.
116593   */
116594   return (rc==SQLCIPHER_OK ? fts3DisconnectMethod(pVtab) : rc);
116595 }
116596
116597
116598 /*
116599 ** Invoke sqlcipher3_declare_vtab() to declare the schema for the FTS3 table
116600 ** passed as the first argument. This is done as part of the xConnect()
116601 ** and xCreate() methods.
116602 **
116603 ** If *pRc is non-zero when this function is called, it is a no-op. 
116604 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
116605 ** before returning.
116606 */
116607 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
116608   if( *pRc==SQLCIPHER_OK ){
116609     int i;                        /* Iterator variable */
116610     int rc;                       /* Return code */
116611     char *zSql;                   /* SQL statement passed to declare_vtab() */
116612     char *zCols;                  /* List of user defined columns */
116613
116614     sqlcipher3_vtab_config(p->db, SQLCIPHER_VTAB_CONSTRAINT_SUPPORT, 1);
116615
116616     /* Create a list of user columns for the virtual table */
116617     zCols = sqlcipher3_mprintf("%Q, ", p->azColumn[0]);
116618     for(i=1; zCols && i<p->nColumn; i++){
116619       zCols = sqlcipher3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
116620     }
116621
116622     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
116623     zSql = sqlcipher3_mprintf(
116624         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
116625     );
116626     if( !zCols || !zSql ){
116627       rc = SQLCIPHER_NOMEM;
116628     }else{
116629       rc = sqlcipher3_declare_vtab(p->db, zSql);
116630     }
116631
116632     sqlcipher3_free(zSql);
116633     sqlcipher3_free(zCols);
116634     *pRc = rc;
116635   }
116636 }
116637
116638 /*
116639 ** Create the backing store tables (%_content, %_segments and %_segdir)
116640 ** required by the FTS3 table passed as the only argument. This is done
116641 ** as part of the vtab xCreate() method.
116642 **
116643 ** If the p->bHasDocsize boolean is true (indicating that this is an
116644 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
116645 ** %_stat tables required by FTS4.
116646 */
116647 static int fts3CreateTables(Fts3Table *p){
116648   int rc = SQLCIPHER_OK;             /* Return code */
116649   int i;                          /* Iterator variable */
116650   sqlcipher3 *db = p->db;            /* The database connection */
116651
116652   if( p->zContentTbl==0 ){
116653     char *zContentCols;           /* Columns of %_content table */
116654
116655     /* Create a list of user columns for the content table */
116656     zContentCols = sqlcipher3_mprintf("docid INTEGER PRIMARY KEY");
116657     for(i=0; zContentCols && i<p->nColumn; i++){
116658       char *z = p->azColumn[i];
116659       zContentCols = sqlcipher3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
116660     }
116661     if( zContentCols==0 ) rc = SQLCIPHER_NOMEM;
116662   
116663     /* Create the content table */
116664     fts3DbExec(&rc, db, 
116665        "CREATE TABLE %Q.'%q_content'(%s)",
116666        p->zDb, p->zName, zContentCols
116667     );
116668     sqlcipher3_free(zContentCols);
116669   }
116670
116671   /* Create other tables */
116672   fts3DbExec(&rc, db, 
116673       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
116674       p->zDb, p->zName
116675   );
116676   fts3DbExec(&rc, db, 
116677       "CREATE TABLE %Q.'%q_segdir'("
116678         "level INTEGER,"
116679         "idx INTEGER,"
116680         "start_block INTEGER,"
116681         "leaves_end_block INTEGER,"
116682         "end_block INTEGER,"
116683         "root BLOB,"
116684         "PRIMARY KEY(level, idx)"
116685       ");",
116686       p->zDb, p->zName
116687   );
116688   if( p->bHasDocsize ){
116689     fts3DbExec(&rc, db, 
116690         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
116691         p->zDb, p->zName
116692     );
116693   }
116694   if( p->bHasStat ){
116695     fts3DbExec(&rc, db, 
116696         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
116697         p->zDb, p->zName
116698     );
116699   }
116700   return rc;
116701 }
116702
116703 /*
116704 ** Store the current database page-size in bytes in p->nPgsz.
116705 **
116706 ** If *pRc is non-zero when this function is called, it is a no-op. 
116707 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
116708 ** before returning.
116709 */
116710 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
116711   if( *pRc==SQLCIPHER_OK ){
116712     int rc;                       /* Return code */
116713     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
116714     sqlcipher3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
116715   
116716     zSql = sqlcipher3_mprintf("PRAGMA %Q.page_size", p->zDb);
116717     if( !zSql ){
116718       rc = SQLCIPHER_NOMEM;
116719     }else{
116720       rc = sqlcipher3_prepare(p->db, zSql, -1, &pStmt, 0);
116721       if( rc==SQLCIPHER_OK ){
116722         sqlcipher3_step(pStmt);
116723         p->nPgsz = sqlcipher3_column_int(pStmt, 0);
116724         rc = sqlcipher3_finalize(pStmt);
116725       }else if( rc==SQLCIPHER_AUTH ){
116726         p->nPgsz = 1024;
116727         rc = SQLCIPHER_OK;
116728       }
116729     }
116730     assert( p->nPgsz>0 || rc!=SQLCIPHER_OK );
116731     sqlcipher3_free(zSql);
116732     *pRc = rc;
116733   }
116734 }
116735
116736 /*
116737 ** "Special" FTS4 arguments are column specifications of the following form:
116738 **
116739 **   <key> = <value>
116740 **
116741 ** There may not be whitespace surrounding the "=" character. The <value> 
116742 ** term may be quoted, but the <key> may not.
116743 */
116744 static int fts3IsSpecialColumn(
116745   const char *z, 
116746   int *pnKey,
116747   char **pzValue
116748 ){
116749   char *zValue;
116750   const char *zCsr = z;
116751
116752   while( *zCsr!='=' ){
116753     if( *zCsr=='\0' ) return 0;
116754     zCsr++;
116755   }
116756
116757   *pnKey = (int)(zCsr-z);
116758   zValue = sqlcipher3_mprintf("%s", &zCsr[1]);
116759   if( zValue ){
116760     sqlcipher3Fts3Dequote(zValue);
116761   }
116762   *pzValue = zValue;
116763   return 1;
116764 }
116765
116766 /*
116767 ** Append the output of a printf() style formatting to an existing string.
116768 */
116769 static void fts3Appendf(
116770   int *pRc,                       /* IN/OUT: Error code */
116771   char **pz,                      /* IN/OUT: Pointer to string buffer */
116772   const char *zFormat,            /* Printf format string to append */
116773   ...                             /* Arguments for printf format string */
116774 ){
116775   if( *pRc==SQLCIPHER_OK ){
116776     va_list ap;
116777     char *z;
116778     va_start(ap, zFormat);
116779     z = sqlcipher3_vmprintf(zFormat, ap);
116780     if( z && *pz ){
116781       char *z2 = sqlcipher3_mprintf("%s%s", *pz, z);
116782       sqlcipher3_free(z);
116783       z = z2;
116784     }
116785     if( z==0 ) *pRc = SQLCIPHER_NOMEM;
116786     sqlcipher3_free(*pz);
116787     *pz = z;
116788   }
116789 }
116790
116791 /*
116792 ** Return a copy of input string zInput enclosed in double-quotes (") and
116793 ** with all double quote characters escaped. For example:
116794 **
116795 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
116796 **
116797 ** The pointer returned points to memory obtained from sqlcipher3_malloc(). It
116798 ** is the callers responsibility to call sqlcipher3_free() to release this
116799 ** memory.
116800 */
116801 static char *fts3QuoteId(char const *zInput){
116802   int nRet;
116803   char *zRet;
116804   nRet = 2 + strlen(zInput)*2 + 1;
116805   zRet = sqlcipher3_malloc(nRet);
116806   if( zRet ){
116807     int i;
116808     char *z = zRet;
116809     *(z++) = '"';
116810     for(i=0; zInput[i]; i++){
116811       if( zInput[i]=='"' ) *(z++) = '"';
116812       *(z++) = zInput[i];
116813     }
116814     *(z++) = '"';
116815     *(z++) = '\0';
116816   }
116817   return zRet;
116818 }
116819
116820 /*
116821 ** Return a list of comma separated SQL expressions and a FROM clause that 
116822 ** could be used in a SELECT statement such as the following:
116823 **
116824 **     SELECT <list of expressions> FROM %_content AS x ...
116825 **
116826 ** to return the docid, followed by each column of text data in order
116827 ** from left to write. If parameter zFunc is not NULL, then instead of
116828 ** being returned directly each column of text data is passed to an SQL
116829 ** function named zFunc first. For example, if zFunc is "unzip" and the
116830 ** table has the three user-defined columns "a", "b", and "c", the following
116831 ** string is returned:
116832 **
116833 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
116834 **
116835 ** The pointer returned points to a buffer allocated by sqlcipher3_malloc(). It
116836 ** is the responsibility of the caller to eventually free it.
116837 **
116838 ** If *pRc is not SQLCIPHER_OK when this function is called, it is a no-op (and
116839 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
116840 ** by this function, NULL is returned and *pRc is set to SQLCIPHER_NOMEM. If
116841 ** no error occurs, *pRc is left unmodified.
116842 */
116843 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
116844   char *zRet = 0;
116845   char *zFree = 0;
116846   char *zFunction;
116847   int i;
116848
116849   if( p->zContentTbl==0 ){
116850     if( !zFunc ){
116851       zFunction = "";
116852     }else{
116853       zFree = zFunction = fts3QuoteId(zFunc);
116854     }
116855     fts3Appendf(pRc, &zRet, "docid");
116856     for(i=0; i<p->nColumn; i++){
116857       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
116858     }
116859     sqlcipher3_free(zFree);
116860   }else{
116861     fts3Appendf(pRc, &zRet, "rowid");
116862     for(i=0; i<p->nColumn; i++){
116863       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
116864     }
116865   }
116866   fts3Appendf(pRc, &zRet, "FROM '%q'.'%q%s' AS x", 
116867       p->zDb,
116868       (p->zContentTbl ? p->zContentTbl : p->zName),
116869       (p->zContentTbl ? "" : "_content")
116870   );
116871   return zRet;
116872 }
116873
116874 /*
116875 ** Return a list of N comma separated question marks, where N is the number
116876 ** of columns in the %_content table (one for the docid plus one for each
116877 ** user-defined text column).
116878 **
116879 ** If argument zFunc is not NULL, then all but the first question mark
116880 ** is preceded by zFunc and an open bracket, and followed by a closed
116881 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
116882 ** user-defined text columns, the following string is returned:
116883 **
116884 **     "?, zip(?), zip(?), zip(?)"
116885 **
116886 ** The pointer returned points to a buffer allocated by sqlcipher3_malloc(). It
116887 ** is the responsibility of the caller to eventually free it.
116888 **
116889 ** If *pRc is not SQLCIPHER_OK when this function is called, it is a no-op (and
116890 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
116891 ** by this function, NULL is returned and *pRc is set to SQLCIPHER_NOMEM. If
116892 ** no error occurs, *pRc is left unmodified.
116893 */
116894 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
116895   char *zRet = 0;
116896   char *zFree = 0;
116897   char *zFunction;
116898   int i;
116899
116900   if( !zFunc ){
116901     zFunction = "";
116902   }else{
116903     zFree = zFunction = fts3QuoteId(zFunc);
116904   }
116905   fts3Appendf(pRc, &zRet, "?");
116906   for(i=0; i<p->nColumn; i++){
116907     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
116908   }
116909   sqlcipher3_free(zFree);
116910   return zRet;
116911 }
116912
116913 /*
116914 ** This function interprets the string at (*pp) as a non-negative integer
116915 ** value. It reads the integer and sets *pnOut to the value read, then 
116916 ** sets *pp to point to the byte immediately following the last byte of
116917 ** the integer value.
116918 **
116919 ** Only decimal digits ('0'..'9') may be part of an integer value. 
116920 **
116921 ** If *pp does not being with a decimal digit SQLCIPHER_ERROR is returned and
116922 ** the output value undefined. Otherwise SQLCIPHER_OK is returned.
116923 **
116924 ** This function is used when parsing the "prefix=" FTS4 parameter.
116925 */
116926 static int fts3GobbleInt(const char **pp, int *pnOut){
116927   const char *p;                  /* Iterator pointer */
116928   int nInt = 0;                   /* Output value */
116929
116930   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
116931     nInt = nInt * 10 + (p[0] - '0');
116932   }
116933   if( p==*pp ) return SQLCIPHER_ERROR;
116934   *pnOut = nInt;
116935   *pp = p;
116936   return SQLCIPHER_OK;
116937 }
116938
116939 /*
116940 ** This function is called to allocate an array of Fts3Index structures
116941 ** representing the indexes maintained by the current FTS table. FTS tables
116942 ** always maintain the main "terms" index, but may also maintain one or
116943 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
116944 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
116945 **
116946 ** Argument zParam is passed the value of the "prefix=" option if one was
116947 ** specified, or NULL otherwise.
116948 **
116949 ** If no error occurs, SQLCIPHER_OK is returned and *apIndex set to point to
116950 ** the allocated array. *pnIndex is set to the number of elements in the
116951 ** array. If an error does occur, an SQLite error code is returned.
116952 **
116953 ** Regardless of whether or not an error is returned, it is the responsibility
116954 ** of the caller to call sqlcipher3_free() on the output array to free it.
116955 */
116956 static int fts3PrefixParameter(
116957   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
116958   int *pnIndex,                   /* OUT: size of *apIndex[] array */
116959   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
116960 ){
116961   struct Fts3Index *aIndex;       /* Allocated array */
116962   int nIndex = 1;                 /* Number of entries in array */
116963
116964   if( zParam && zParam[0] ){
116965     const char *p;
116966     nIndex++;
116967     for(p=zParam; *p; p++){
116968       if( *p==',' ) nIndex++;
116969     }
116970   }
116971
116972   aIndex = sqlcipher3_malloc(sizeof(struct Fts3Index) * nIndex);
116973   *apIndex = aIndex;
116974   *pnIndex = nIndex;
116975   if( !aIndex ){
116976     return SQLCIPHER_NOMEM;
116977   }
116978
116979   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
116980   if( zParam ){
116981     const char *p = zParam;
116982     int i;
116983     for(i=1; i<nIndex; i++){
116984       int nPrefix;
116985       if( fts3GobbleInt(&p, &nPrefix) ) return SQLCIPHER_ERROR;
116986       aIndex[i].nPrefix = nPrefix;
116987       p++;
116988     }
116989   }
116990
116991   return SQLCIPHER_OK;
116992 }
116993
116994 /*
116995 ** This function is called when initializing an FTS4 table that uses the
116996 ** content=xxx option. It determines the number of and names of the columns
116997 ** of the new FTS4 table.
116998 **
116999 ** The third argument passed to this function is the value passed to the
117000 ** config=xxx option (i.e. "xxx"). This function queries the database for
117001 ** a table of that name. If found, the output variables are populated
117002 ** as follows:
117003 **
117004 **   *pnCol:   Set to the number of columns table xxx has,
117005 **
117006 **   *pnStr:   Set to the total amount of space required to store a copy
117007 **             of each columns name, including the nul-terminator.
117008 **
117009 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
117010 **             the name of the corresponding column in table xxx. The array
117011 **             and its contents are allocated using a single allocation. It
117012 **             is the responsibility of the caller to free this allocation
117013 **             by eventually passing the *pazCol value to sqlcipher3_free().
117014 **
117015 ** If the table cannot be found, an error code is returned and the output
117016 ** variables are undefined. Or, if an OOM is encountered, SQLCIPHER_NOMEM is
117017 ** returned (and the output variables are undefined).
117018 */
117019 static int fts3ContentColumns(
117020   sqlcipher3 *db,                    /* Database handle */
117021   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
117022   const char *zTbl,               /* Name of content table */
117023   const char ***pazCol,           /* OUT: Malloc'd array of column names */
117024   int *pnCol,                     /* OUT: Size of array *pazCol */
117025   int *pnStr                      /* OUT: Bytes of string content */
117026 ){
117027   int rc = SQLCIPHER_OK;             /* Return code */
117028   char *zSql;                     /* "SELECT *" statement on zTbl */  
117029   sqlcipher3_stmt *pStmt = 0;        /* Compiled version of zSql */
117030
117031   zSql = sqlcipher3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
117032   if( !zSql ){
117033     rc = SQLCIPHER_NOMEM;
117034   }else{
117035     rc = sqlcipher3_prepare(db, zSql, -1, &pStmt, 0);
117036   }
117037   sqlcipher3_free(zSql);
117038
117039   if( rc==SQLCIPHER_OK ){
117040     const char **azCol;           /* Output array */
117041     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
117042     int nCol;                     /* Number of table columns */
117043     int i;                        /* Used to iterate through columns */
117044
117045     /* Loop through the returned columns. Set nStr to the number of bytes of
117046     ** space required to store a copy of each column name, including the
117047     ** nul-terminator byte.  */
117048     nCol = sqlcipher3_column_count(pStmt);
117049     for(i=0; i<nCol; i++){
117050       const char *zCol = sqlcipher3_column_name(pStmt, i);
117051       nStr += strlen(zCol) + 1;
117052     }
117053
117054     /* Allocate and populate the array to return. */
117055     azCol = (const char **)sqlcipher3_malloc(sizeof(char *) * nCol + nStr);
117056     if( azCol==0 ){
117057       rc = SQLCIPHER_NOMEM;
117058     }else{
117059       char *p = (char *)&azCol[nCol];
117060       for(i=0; i<nCol; i++){
117061         const char *zCol = sqlcipher3_column_name(pStmt, i);
117062         int n = strlen(zCol)+1;
117063         memcpy(p, zCol, n);
117064         azCol[i] = p;
117065         p += n;
117066       }
117067     }
117068     sqlcipher3_finalize(pStmt);
117069
117070     /* Set the output variables. */
117071     *pnCol = nCol;
117072     *pnStr = nStr;
117073     *pazCol = azCol;
117074   }
117075
117076   return rc;
117077 }
117078
117079 /*
117080 ** This function is the implementation of both the xConnect and xCreate
117081 ** methods of the FTS3 virtual table.
117082 **
117083 ** The argv[] array contains the following:
117084 **
117085 **   argv[0]   -> module name  ("fts3" or "fts4")
117086 **   argv[1]   -> database name
117087 **   argv[2]   -> table name
117088 **   argv[...] -> "column name" and other module argument fields.
117089 */
117090 static int fts3InitVtab(
117091   int isCreate,                   /* True for xCreate, false for xConnect */
117092   sqlcipher3 *db,                    /* The SQLite database connection */
117093   void *pAux,                     /* Hash table containing tokenizers */
117094   int argc,                       /* Number of elements in argv array */
117095   const char * const *argv,       /* xCreate/xConnect argument array */
117096   sqlcipher3_vtab **ppVTab,          /* Write the resulting vtab structure here */
117097   char **pzErr                    /* Write any error message here */
117098 ){
117099   Fts3Hash *pHash = (Fts3Hash *)pAux;
117100   Fts3Table *p = 0;               /* Pointer to allocated vtab */
117101   int rc = SQLCIPHER_OK;             /* Return code */
117102   int i;                          /* Iterator variable */
117103   int nByte;                      /* Size of allocation used for *p */
117104   int iCol;                       /* Column index */
117105   int nString = 0;                /* Bytes required to hold all column names */
117106   int nCol = 0;                   /* Number of columns in the FTS table */
117107   char *zCsr;                     /* Space for holding column names */
117108   int nDb;                        /* Bytes required to hold database name */
117109   int nName;                      /* Bytes required to hold table name */
117110   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
117111   const char **aCol;              /* Array of column names */
117112   sqlcipher3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
117113
117114   int nIndex;                     /* Size of aIndex[] array */
117115   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
117116
117117   /* The results of parsing supported FTS4 key=value options: */
117118   int bNoDocsize = 0;             /* True to omit %_docsize table */
117119   int bDescIdx = 0;               /* True to store descending indexes */
117120   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
117121   char *zCompress = 0;            /* compress=? parameter (or NULL) */
117122   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
117123   char *zContent = 0;             /* content=? parameter (or NULL) */
117124
117125   assert( strlen(argv[0])==4 );
117126   assert( (sqlcipher3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
117127        || (sqlcipher3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
117128   );
117129
117130   nDb = (int)strlen(argv[1]) + 1;
117131   nName = (int)strlen(argv[2]) + 1;
117132
117133   aCol = (const char **)sqlcipher3_malloc(sizeof(const char *) * (argc-2) );
117134   if( !aCol ) return SQLCIPHER_NOMEM;
117135   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
117136
117137   /* Loop through all of the arguments passed by the user to the FTS3/4
117138   ** module (i.e. all the column names and special arguments). This loop
117139   ** does the following:
117140   **
117141   **   + Figures out the number of columns the FTSX table will have, and
117142   **     the number of bytes of space that must be allocated to store copies
117143   **     of the column names.
117144   **
117145   **   + If there is a tokenizer specification included in the arguments,
117146   **     initializes the tokenizer pTokenizer.
117147   */
117148   for(i=3; rc==SQLCIPHER_OK && i<argc; i++){
117149     char const *z = argv[i];
117150     int nKey;
117151     char *zVal;
117152
117153     /* Check if this is a tokenizer specification */
117154     if( !pTokenizer 
117155      && strlen(z)>8
117156      && 0==sqlcipher3_strnicmp(z, "tokenize", 8) 
117157      && 0==sqlcipher3Fts3IsIdChar(z[8])
117158     ){
117159       rc = sqlcipher3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
117160     }
117161
117162     /* Check if it is an FTS4 special argument. */
117163     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
117164       struct Fts4Option {
117165         const char *zOpt;
117166         int nOpt;
117167       } aFts4Opt[] = {
117168         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
117169         { "prefix",      6 },     /* 1 -> PREFIX */
117170         { "compress",    8 },     /* 2 -> COMPRESS */
117171         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
117172         { "order",       5 },     /* 4 -> ORDER */
117173         { "content",     7 }      /* 5 -> CONTENT */
117174       };
117175
117176       int iOpt;
117177       if( !zVal ){
117178         rc = SQLCIPHER_NOMEM;
117179       }else{
117180         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
117181           struct Fts4Option *pOp = &aFts4Opt[iOpt];
117182           if( nKey==pOp->nOpt && !sqlcipher3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
117183             break;
117184           }
117185         }
117186         if( iOpt==SizeofArray(aFts4Opt) ){
117187           *pzErr = sqlcipher3_mprintf("unrecognized parameter: %s", z);
117188           rc = SQLCIPHER_ERROR;
117189         }else{
117190           switch( iOpt ){
117191             case 0:               /* MATCHINFO */
117192               if( strlen(zVal)!=4 || sqlcipher3_strnicmp(zVal, "fts3", 4) ){
117193                 *pzErr = sqlcipher3_mprintf("unrecognized matchinfo: %s", zVal);
117194                 rc = SQLCIPHER_ERROR;
117195               }
117196               bNoDocsize = 1;
117197               break;
117198
117199             case 1:               /* PREFIX */
117200               sqlcipher3_free(zPrefix);
117201               zPrefix = zVal;
117202               zVal = 0;
117203               break;
117204
117205             case 2:               /* COMPRESS */
117206               sqlcipher3_free(zCompress);
117207               zCompress = zVal;
117208               zVal = 0;
117209               break;
117210
117211             case 3:               /* UNCOMPRESS */
117212               sqlcipher3_free(zUncompress);
117213               zUncompress = zVal;
117214               zVal = 0;
117215               break;
117216
117217             case 4:               /* ORDER */
117218               if( (strlen(zVal)!=3 || sqlcipher3_strnicmp(zVal, "asc", 3)) 
117219                && (strlen(zVal)!=4 || sqlcipher3_strnicmp(zVal, "desc", 4)) 
117220               ){
117221                 *pzErr = sqlcipher3_mprintf("unrecognized order: %s", zVal);
117222                 rc = SQLCIPHER_ERROR;
117223               }
117224               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
117225               break;
117226
117227             default:              /* CONTENT */
117228               assert( iOpt==5 );
117229               sqlcipher3_free(zUncompress);
117230               zContent = zVal;
117231               zVal = 0;
117232               break;
117233           }
117234         }
117235         sqlcipher3_free(zVal);
117236       }
117237     }
117238
117239     /* Otherwise, the argument is a column name. */
117240     else {
117241       nString += (int)(strlen(z) + 1);
117242       aCol[nCol++] = z;
117243     }
117244   }
117245
117246   /* If a content=xxx option was specified, the following:
117247   **
117248   **   1. Ignore any compress= and uncompress= options.
117249   **
117250   **   2. If no column names were specified as part of the CREATE VIRTUAL
117251   **      TABLE statement, use all columns from the content table.
117252   */
117253   if( rc==SQLCIPHER_OK && zContent ){
117254     sqlcipher3_free(zCompress); 
117255     sqlcipher3_free(zUncompress); 
117256     zCompress = 0;
117257     zUncompress = 0;
117258     if( nCol==0 ){
117259       sqlcipher3_free((void*)aCol); 
117260       aCol = 0;
117261       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
117262     }
117263     assert( rc!=SQLCIPHER_OK || nCol>0 );
117264   }
117265   if( rc!=SQLCIPHER_OK ) goto fts3_init_out;
117266
117267   if( nCol==0 ){
117268     assert( nString==0 );
117269     aCol[0] = "content";
117270     nString = 8;
117271     nCol = 1;
117272   }
117273
117274   if( pTokenizer==0 ){
117275     rc = sqlcipher3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
117276     if( rc!=SQLCIPHER_OK ) goto fts3_init_out;
117277   }
117278   assert( pTokenizer );
117279
117280   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
117281   if( rc==SQLCIPHER_ERROR ){
117282     assert( zPrefix );
117283     *pzErr = sqlcipher3_mprintf("error parsing prefix parameter: %s", zPrefix);
117284   }
117285   if( rc!=SQLCIPHER_OK ) goto fts3_init_out;
117286
117287   /* Allocate and populate the Fts3Table structure. */
117288   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
117289           nCol * sizeof(char *) +              /* azColumn */
117290           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
117291           nName +                              /* zName */
117292           nDb +                                /* zDb */
117293           nString;                             /* Space for azColumn strings */
117294   p = (Fts3Table*)sqlcipher3_malloc(nByte);
117295   if( p==0 ){
117296     rc = SQLCIPHER_NOMEM;
117297     goto fts3_init_out;
117298   }
117299   memset(p, 0, nByte);
117300   p->db = db;
117301   p->nColumn = nCol;
117302   p->nPendingData = 0;
117303   p->azColumn = (char **)&p[1];
117304   p->pTokenizer = pTokenizer;
117305   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
117306   p->bHasDocsize = (isFts4 && bNoDocsize==0);
117307   p->bHasStat = isFts4;
117308   p->bDescIdx = bDescIdx;
117309   p->zContentTbl = zContent;
117310   zContent = 0;
117311   TESTONLY( p->inTransaction = -1 );
117312   TESTONLY( p->mxSavepoint = -1 );
117313
117314   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
117315   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
117316   p->nIndex = nIndex;
117317   for(i=0; i<nIndex; i++){
117318     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
117319   }
117320
117321   /* Fill in the zName and zDb fields of the vtab structure. */
117322   zCsr = (char *)&p->aIndex[nIndex];
117323   p->zName = zCsr;
117324   memcpy(zCsr, argv[2], nName);
117325   zCsr += nName;
117326   p->zDb = zCsr;
117327   memcpy(zCsr, argv[1], nDb);
117328   zCsr += nDb;
117329
117330   /* Fill in the azColumn array */
117331   for(iCol=0; iCol<nCol; iCol++){
117332     char *z; 
117333     int n = 0;
117334     z = (char *)sqlcipher3Fts3NextToken(aCol[iCol], &n);
117335     memcpy(zCsr, z, n);
117336     zCsr[n] = '\0';
117337     sqlcipher3Fts3Dequote(zCsr);
117338     p->azColumn[iCol] = zCsr;
117339     zCsr += n+1;
117340     assert( zCsr <= &((char *)p)[nByte] );
117341   }
117342
117343   if( (zCompress==0)!=(zUncompress==0) ){
117344     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
117345     rc = SQLCIPHER_ERROR;
117346     *pzErr = sqlcipher3_mprintf("missing %s parameter in fts4 constructor", zMiss);
117347   }
117348   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
117349   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
117350   if( rc!=SQLCIPHER_OK ) goto fts3_init_out;
117351
117352   /* If this is an xCreate call, create the underlying tables in the 
117353   ** database. TODO: For xConnect(), it could verify that said tables exist.
117354   */
117355   if( isCreate ){
117356     rc = fts3CreateTables(p);
117357   }
117358
117359   /* Figure out the page-size for the database. This is required in order to
117360   ** estimate the cost of loading large doclists from the database.  */
117361   fts3DatabasePageSize(&rc, p);
117362   p->nNodeSize = p->nPgsz-35;
117363
117364   /* Declare the table schema to SQLite. */
117365   fts3DeclareVtab(&rc, p);
117366
117367 fts3_init_out:
117368   sqlcipher3_free(zPrefix);
117369   sqlcipher3_free(aIndex);
117370   sqlcipher3_free(zCompress);
117371   sqlcipher3_free(zUncompress);
117372   sqlcipher3_free(zContent);
117373   sqlcipher3_free((void *)aCol);
117374   if( rc!=SQLCIPHER_OK ){
117375     if( p ){
117376       fts3DisconnectMethod((sqlcipher3_vtab *)p);
117377     }else if( pTokenizer ){
117378       pTokenizer->pModule->xDestroy(pTokenizer);
117379     }
117380   }else{
117381     assert( p->pSegments==0 );
117382     *ppVTab = &p->base;
117383   }
117384   return rc;
117385 }
117386
117387 /*
117388 ** The xConnect() and xCreate() methods for the virtual table. All the
117389 ** work is done in function fts3InitVtab().
117390 */
117391 static int fts3ConnectMethod(
117392   sqlcipher3 *db,                    /* Database connection */
117393   void *pAux,                     /* Pointer to tokenizer hash table */
117394   int argc,                       /* Number of elements in argv array */
117395   const char * const *argv,       /* xCreate/xConnect argument array */
117396   sqlcipher3_vtab **ppVtab,          /* OUT: New sqlcipher3_vtab object */
117397   char **pzErr                    /* OUT: sqlcipher3_malloc'd error message */
117398 ){
117399   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
117400 }
117401 static int fts3CreateMethod(
117402   sqlcipher3 *db,                    /* Database connection */
117403   void *pAux,                     /* Pointer to tokenizer hash table */
117404   int argc,                       /* Number of elements in argv array */
117405   const char * const *argv,       /* xCreate/xConnect argument array */
117406   sqlcipher3_vtab **ppVtab,          /* OUT: New sqlcipher3_vtab object */
117407   char **pzErr                    /* OUT: sqlcipher3_malloc'd error message */
117408 ){
117409   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
117410 }
117411
117412 /* 
117413 ** Implementation of the xBestIndex method for FTS3 tables. There
117414 ** are three possible strategies, in order of preference:
117415 **
117416 **   1. Direct lookup by rowid or docid. 
117417 **   2. Full-text search using a MATCH operator on a non-docid column.
117418 **   3. Linear scan of %_content table.
117419 */
117420 static int fts3BestIndexMethod(sqlcipher3_vtab *pVTab, sqlcipher3_index_info *pInfo){
117421   Fts3Table *p = (Fts3Table *)pVTab;
117422   int i;                          /* Iterator variable */
117423   int iCons = -1;                 /* Index of constraint to use */
117424
117425   /* By default use a full table scan. This is an expensive option,
117426   ** so search through the constraints to see if a more efficient 
117427   ** strategy is possible.
117428   */
117429   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
117430   pInfo->estimatedCost = 500000;
117431   for(i=0; i<pInfo->nConstraint; i++){
117432     struct sqlcipher3_index_constraint *pCons = &pInfo->aConstraint[i];
117433     if( pCons->usable==0 ) continue;
117434
117435     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
117436     if( pCons->op==SQLCIPHER_INDEX_CONSTRAINT_EQ 
117437      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
117438     ){
117439       pInfo->idxNum = FTS3_DOCID_SEARCH;
117440       pInfo->estimatedCost = 1.0;
117441       iCons = i;
117442     }
117443
117444     /* A MATCH constraint. Use a full-text search.
117445     **
117446     ** If there is more than one MATCH constraint available, use the first
117447     ** one encountered. If there is both a MATCH constraint and a direct
117448     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
117449     ** though the rowid/docid lookup is faster than a MATCH query, selecting
117450     ** it would lead to an "unable to use function MATCH in the requested 
117451     ** context" error.
117452     */
117453     if( pCons->op==SQLCIPHER_INDEX_CONSTRAINT_MATCH 
117454      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
117455     ){
117456       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
117457       pInfo->estimatedCost = 2.0;
117458       iCons = i;
117459       break;
117460     }
117461   }
117462
117463   if( iCons>=0 ){
117464     pInfo->aConstraintUsage[iCons].argvIndex = 1;
117465     pInfo->aConstraintUsage[iCons].omit = 1;
117466   } 
117467
117468   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
117469   ** docid) order. Both ascending and descending are possible. 
117470   */
117471   if( pInfo->nOrderBy==1 ){
117472     struct sqlcipher3_index_orderby *pOrder = &pInfo->aOrderBy[0];
117473     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
117474       if( pOrder->desc ){
117475         pInfo->idxStr = "DESC";
117476       }else{
117477         pInfo->idxStr = "ASC";
117478       }
117479       pInfo->orderByConsumed = 1;
117480     }
117481   }
117482
117483   assert( p->pSegments==0 );
117484   return SQLCIPHER_OK;
117485 }
117486
117487 /*
117488 ** Implementation of xOpen method.
117489 */
117490 static int fts3OpenMethod(sqlcipher3_vtab *pVTab, sqlcipher3_vtab_cursor **ppCsr){
117491   sqlcipher3_vtab_cursor *pCsr;               /* Allocated cursor */
117492
117493   UNUSED_PARAMETER(pVTab);
117494
117495   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
117496   ** allocation succeeds, zero it and return SQLCIPHER_OK. Otherwise, 
117497   ** if the allocation fails, return SQLCIPHER_NOMEM.
117498   */
117499   *ppCsr = pCsr = (sqlcipher3_vtab_cursor *)sqlcipher3_malloc(sizeof(Fts3Cursor));
117500   if( !pCsr ){
117501     return SQLCIPHER_NOMEM;
117502   }
117503   memset(pCsr, 0, sizeof(Fts3Cursor));
117504   return SQLCIPHER_OK;
117505 }
117506
117507 /*
117508 ** Close the cursor.  For additional information see the documentation
117509 ** on the xClose method of the virtual table interface.
117510 */
117511 static int fts3CloseMethod(sqlcipher3_vtab_cursor *pCursor){
117512   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
117513   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
117514   sqlcipher3_finalize(pCsr->pStmt);
117515   sqlcipher3Fts3ExprFree(pCsr->pExpr);
117516   sqlcipher3Fts3FreeDeferredTokens(pCsr);
117517   sqlcipher3_free(pCsr->aDoclist);
117518   sqlcipher3_free(pCsr->aMatchinfo);
117519   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
117520   sqlcipher3_free(pCsr);
117521   return SQLCIPHER_OK;
117522 }
117523
117524 /*
117525 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
117526 ** compose and prepare an SQL statement of the form:
117527 **
117528 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
117529 **
117530 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
117531 ** it. If an error occurs, return an SQLite error code.
117532 **
117533 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLCIPHER_OK.
117534 */
117535 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlcipher3_stmt **ppStmt){
117536   int rc = SQLCIPHER_OK;
117537   if( pCsr->pStmt==0 ){
117538     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
117539     char *zSql;
117540     zSql = sqlcipher3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
117541     if( !zSql ) return SQLCIPHER_NOMEM;
117542     rc = sqlcipher3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
117543     sqlcipher3_free(zSql);
117544   }
117545   *ppStmt = pCsr->pStmt;
117546   return rc;
117547 }
117548
117549 /*
117550 ** Position the pCsr->pStmt statement so that it is on the row
117551 ** of the %_content table that contains the last match.  Return
117552 ** SQLCIPHER_OK on success.  
117553 */
117554 static int fts3CursorSeek(sqlcipher3_context *pContext, Fts3Cursor *pCsr){
117555   int rc = SQLCIPHER_OK;
117556   if( pCsr->isRequireSeek ){
117557     sqlcipher3_stmt *pStmt = 0;
117558
117559     rc = fts3CursorSeekStmt(pCsr, &pStmt);
117560     if( rc==SQLCIPHER_OK ){
117561       sqlcipher3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
117562       pCsr->isRequireSeek = 0;
117563       if( SQLCIPHER_ROW==sqlcipher3_step(pCsr->pStmt) ){
117564         return SQLCIPHER_OK;
117565       }else{
117566         rc = sqlcipher3_reset(pCsr->pStmt);
117567         if( rc==SQLCIPHER_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
117568           /* If no row was found and no error has occured, then the %_content
117569           ** table is missing a row that is present in the full-text index.
117570           ** The data structures are corrupt.  */
117571           rc = FTS_CORRUPT_VTAB;
117572           pCsr->isEof = 1;
117573         }
117574       }
117575     }
117576   }
117577
117578   if( rc!=SQLCIPHER_OK && pContext ){
117579     sqlcipher3_result_error_code(pContext, rc);
117580   }
117581   return rc;
117582 }
117583
117584 /*
117585 ** This function is used to process a single interior node when searching
117586 ** a b-tree for a term or term prefix. The node data is passed to this 
117587 ** function via the zNode/nNode parameters. The term to search for is
117588 ** passed in zTerm/nTerm.
117589 **
117590 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
117591 ** of the child node that heads the sub-tree that may contain the term.
117592 **
117593 ** If piLast is not NULL, then *piLast is set to the right-most child node
117594 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
117595 ** a prefix.
117596 **
117597 ** If an OOM error occurs, SQLCIPHER_NOMEM is returned. Otherwise, SQLCIPHER_OK.
117598 */
117599 static int fts3ScanInteriorNode(
117600   const char *zTerm,              /* Term to select leaves for */
117601   int nTerm,                      /* Size of term zTerm in bytes */
117602   const char *zNode,              /* Buffer containing segment interior node */
117603   int nNode,                      /* Size of buffer at zNode */
117604   sqlcipher3_int64 *piFirst,         /* OUT: Selected child node */
117605   sqlcipher3_int64 *piLast           /* OUT: Selected child node */
117606 ){
117607   int rc = SQLCIPHER_OK;             /* Return code */
117608   const char *zCsr = zNode;       /* Cursor to iterate through node */
117609   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
117610   char *zBuffer = 0;              /* Buffer to load terms into */
117611   int nAlloc = 0;                 /* Size of allocated buffer */
117612   int isFirstTerm = 1;            /* True when processing first term on page */
117613   sqlcipher3_int64 iChild;           /* Block id of child node to descend to */
117614
117615   /* Skip over the 'height' varint that occurs at the start of every 
117616   ** interior node. Then load the blockid of the left-child of the b-tree
117617   ** node into variable iChild.  
117618   **
117619   ** Even if the data structure on disk is corrupted, this (reading two
117620   ** varints from the buffer) does not risk an overread. If zNode is a
117621   ** root node, then the buffer comes from a SELECT statement. SQLite does
117622   ** not make this guarantee explicitly, but in practice there are always
117623   ** either more than 20 bytes of allocated space following the nNode bytes of
117624   ** contents, or two zero bytes. Or, if the node is read from the %_segments
117625   ** table, then there are always 20 bytes of zeroed padding following the
117626   ** nNode bytes of content (see sqlcipher3Fts3ReadBlock() for details).
117627   */
117628   zCsr += sqlcipher3Fts3GetVarint(zCsr, &iChild);
117629   zCsr += sqlcipher3Fts3GetVarint(zCsr, &iChild);
117630   if( zCsr>zEnd ){
117631     return FTS_CORRUPT_VTAB;
117632   }
117633   
117634   while( zCsr<zEnd && (piFirst || piLast) ){
117635     int cmp;                      /* memcmp() result */
117636     int nSuffix;                  /* Size of term suffix */
117637     int nPrefix = 0;              /* Size of term prefix */
117638     int nBuffer;                  /* Total term size */
117639   
117640     /* Load the next term on the node into zBuffer. Use realloc() to expand
117641     ** the size of zBuffer if required.  */
117642     if( !isFirstTerm ){
117643       zCsr += sqlcipher3Fts3GetVarint32(zCsr, &nPrefix);
117644     }
117645     isFirstTerm = 0;
117646     zCsr += sqlcipher3Fts3GetVarint32(zCsr, &nSuffix);
117647     
117648     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
117649       rc = FTS_CORRUPT_VTAB;
117650       goto finish_scan;
117651     }
117652     if( nPrefix+nSuffix>nAlloc ){
117653       char *zNew;
117654       nAlloc = (nPrefix+nSuffix) * 2;
117655       zNew = (char *)sqlcipher3_realloc(zBuffer, nAlloc);
117656       if( !zNew ){
117657         rc = SQLCIPHER_NOMEM;
117658         goto finish_scan;
117659       }
117660       zBuffer = zNew;
117661     }
117662     assert( zBuffer );
117663     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
117664     nBuffer = nPrefix + nSuffix;
117665     zCsr += nSuffix;
117666
117667     /* Compare the term we are searching for with the term just loaded from
117668     ** the interior node. If the specified term is greater than or equal
117669     ** to the term from the interior node, then all terms on the sub-tree 
117670     ** headed by node iChild are smaller than zTerm. No need to search 
117671     ** iChild.
117672     **
117673     ** If the interior node term is larger than the specified term, then
117674     ** the tree headed by iChild may contain the specified term.
117675     */
117676     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
117677     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
117678       *piFirst = iChild;
117679       piFirst = 0;
117680     }
117681
117682     if( piLast && cmp<0 ){
117683       *piLast = iChild;
117684       piLast = 0;
117685     }
117686
117687     iChild++;
117688   };
117689
117690   if( piFirst ) *piFirst = iChild;
117691   if( piLast ) *piLast = iChild;
117692
117693  finish_scan:
117694   sqlcipher3_free(zBuffer);
117695   return rc;
117696 }
117697
117698
117699 /*
117700 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
117701 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
117702 ** contains a term. This function searches the sub-tree headed by the zNode
117703 ** node for the range of leaf nodes that may contain the specified term
117704 ** or terms for which the specified term is a prefix.
117705 **
117706 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
117707 ** left-most leaf node in the tree that may contain the specified term.
117708 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
117709 ** right-most leaf node that may contain a term for which the specified
117710 ** term is a prefix.
117711 **
117712 ** It is possible that the range of returned leaf nodes does not contain 
117713 ** the specified term or any terms for which it is a prefix. However, if the 
117714 ** segment does contain any such terms, they are stored within the identified
117715 ** range. Because this function only inspects interior segment nodes (and
117716 ** never loads leaf nodes into memory), it is not possible to be sure.
117717 **
117718 ** If an error occurs, an error code other than SQLCIPHER_OK is returned.
117719 */ 
117720 static int fts3SelectLeaf(
117721   Fts3Table *p,                   /* Virtual table handle */
117722   const char *zTerm,              /* Term to select leaves for */
117723   int nTerm,                      /* Size of term zTerm in bytes */
117724   const char *zNode,              /* Buffer containing segment interior node */
117725   int nNode,                      /* Size of buffer at zNode */
117726   sqlcipher3_int64 *piLeaf,          /* Selected leaf node */
117727   sqlcipher3_int64 *piLeaf2          /* Selected leaf node */
117728 ){
117729   int rc;                         /* Return code */
117730   int iHeight;                    /* Height of this node in tree */
117731
117732   assert( piLeaf || piLeaf2 );
117733
117734   sqlcipher3Fts3GetVarint32(zNode, &iHeight);
117735   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
117736   assert( !piLeaf2 || !piLeaf || rc!=SQLCIPHER_OK || (*piLeaf<=*piLeaf2) );
117737
117738   if( rc==SQLCIPHER_OK && iHeight>1 ){
117739     char *zBlob = 0;              /* Blob read from %_segments table */
117740     int nBlob;                    /* Size of zBlob in bytes */
117741
117742     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
117743       rc = sqlcipher3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
117744       if( rc==SQLCIPHER_OK ){
117745         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
117746       }
117747       sqlcipher3_free(zBlob);
117748       piLeaf = 0;
117749       zBlob = 0;
117750     }
117751
117752     if( rc==SQLCIPHER_OK ){
117753       rc = sqlcipher3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
117754     }
117755     if( rc==SQLCIPHER_OK ){
117756       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
117757     }
117758     sqlcipher3_free(zBlob);
117759   }
117760
117761   return rc;
117762 }
117763
117764 /*
117765 ** This function is used to create delta-encoded serialized lists of FTS3 
117766 ** varints. Each call to this function appends a single varint to a list.
117767 */
117768 static void fts3PutDeltaVarint(
117769   char **pp,                      /* IN/OUT: Output pointer */
117770   sqlcipher3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
117771   sqlcipher3_int64 iVal              /* Write this value to the list */
117772 ){
117773   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
117774   *pp += sqlcipher3Fts3PutVarint(*pp, iVal-*piPrev);
117775   *piPrev = iVal;
117776 }
117777
117778 /*
117779 ** When this function is called, *ppPoslist is assumed to point to the 
117780 ** start of a position-list. After it returns, *ppPoslist points to the
117781 ** first byte after the position-list.
117782 **
117783 ** A position list is list of positions (delta encoded) and columns for 
117784 ** a single document record of a doclist.  So, in other words, this
117785 ** routine advances *ppPoslist so that it points to the next docid in
117786 ** the doclist, or to the first byte past the end of the doclist.
117787 **
117788 ** If pp is not NULL, then the contents of the position list are copied
117789 ** to *pp. *pp is set to point to the first byte past the last byte copied
117790 ** before this function returns.
117791 */
117792 static void fts3PoslistCopy(char **pp, char **ppPoslist){
117793   char *pEnd = *ppPoslist;
117794   char c = 0;
117795
117796   /* The end of a position list is marked by a zero encoded as an FTS3 
117797   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
117798   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
117799   ** of some other, multi-byte, value.
117800   **
117801   ** The following while-loop moves pEnd to point to the first byte that is not 
117802   ** immediately preceded by a byte with the 0x80 bit set. Then increments
117803   ** pEnd once more so that it points to the byte immediately following the
117804   ** last byte in the position-list.
117805   */
117806   while( *pEnd | c ){
117807     c = *pEnd++ & 0x80;
117808     testcase( c!=0 && (*pEnd)==0 );
117809   }
117810   pEnd++;  /* Advance past the POS_END terminator byte */
117811
117812   if( pp ){
117813     int n = (int)(pEnd - *ppPoslist);
117814     char *p = *pp;
117815     memcpy(p, *ppPoslist, n);
117816     p += n;
117817     *pp = p;
117818   }
117819   *ppPoslist = pEnd;
117820 }
117821
117822 /*
117823 ** When this function is called, *ppPoslist is assumed to point to the 
117824 ** start of a column-list. After it returns, *ppPoslist points to the
117825 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
117826 **
117827 ** A column-list is list of delta-encoded positions for a single column
117828 ** within a single document within a doclist.
117829 **
117830 ** The column-list is terminated either by a POS_COLUMN varint (1) or
117831 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
117832 ** the POS_COLUMN or POS_END that terminates the column-list.
117833 **
117834 ** If pp is not NULL, then the contents of the column-list are copied
117835 ** to *pp. *pp is set to point to the first byte past the last byte copied
117836 ** before this function returns.  The POS_COLUMN or POS_END terminator
117837 ** is not copied into *pp.
117838 */
117839 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
117840   char *pEnd = *ppPoslist;
117841   char c = 0;
117842
117843   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
117844   ** not part of a multi-byte varint.
117845   */
117846   while( 0xFE & (*pEnd | c) ){
117847     c = *pEnd++ & 0x80;
117848     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
117849   }
117850   if( pp ){
117851     int n = (int)(pEnd - *ppPoslist);
117852     char *p = *pp;
117853     memcpy(p, *ppPoslist, n);
117854     p += n;
117855     *pp = p;
117856   }
117857   *ppPoslist = pEnd;
117858 }
117859
117860 /*
117861 ** Value used to signify the end of an position-list. This is safe because
117862 ** it is not possible to have a document with 2^31 terms.
117863 */
117864 #define POSITION_LIST_END 0x7fffffff
117865
117866 /*
117867 ** This function is used to help parse position-lists. When this function is
117868 ** called, *pp may point to the start of the next varint in the position-list
117869 ** being parsed, or it may point to 1 byte past the end of the position-list
117870 ** (in which case **pp will be a terminator bytes POS_END (0) or
117871 ** (1)).
117872 **
117873 ** If *pp points past the end of the current position-list, set *pi to 
117874 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
117875 ** increment the current value of *pi by the value read, and set *pp to
117876 ** point to the next value before returning.
117877 **
117878 ** Before calling this routine *pi must be initialized to the value of
117879 ** the previous position, or zero if we are reading the first position
117880 ** in the position-list.  Because positions are delta-encoded, the value
117881 ** of the previous position is needed in order to compute the value of
117882 ** the next position.
117883 */
117884 static void fts3ReadNextPos(
117885   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
117886   sqlcipher3_int64 *pi             /* IN/OUT: Value read from position-list */
117887 ){
117888   if( (**pp)&0xFE ){
117889     fts3GetDeltaVarint(pp, pi);
117890     *pi -= 2;
117891   }else{
117892     *pi = POSITION_LIST_END;
117893   }
117894 }
117895
117896 /*
117897 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
117898 ** the value of iCol encoded as a varint to *pp.   This will start a new
117899 ** column list.
117900 **
117901 ** Set *pp to point to the byte just after the last byte written before 
117902 ** returning (do not modify it if iCol==0). Return the total number of bytes
117903 ** written (0 if iCol==0).
117904 */
117905 static int fts3PutColNumber(char **pp, int iCol){
117906   int n = 0;                      /* Number of bytes written */
117907   if( iCol ){
117908     char *p = *pp;                /* Output pointer */
117909     n = 1 + sqlcipher3Fts3PutVarint(&p[1], iCol);
117910     *p = 0x01;
117911     *pp = &p[n];
117912   }
117913   return n;
117914 }
117915
117916 /*
117917 ** Compute the union of two position lists.  The output written
117918 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
117919 ** order and with any duplicates removed.  All pointers are
117920 ** updated appropriately.   The caller is responsible for insuring
117921 ** that there is enough space in *pp to hold the complete output.
117922 */
117923 static void fts3PoslistMerge(
117924   char **pp,                      /* Output buffer */
117925   char **pp1,                     /* Left input list */
117926   char **pp2                      /* Right input list */
117927 ){
117928   char *p = *pp;
117929   char *p1 = *pp1;
117930   char *p2 = *pp2;
117931
117932   while( *p1 || *p2 ){
117933     int iCol1;         /* The current column index in pp1 */
117934     int iCol2;         /* The current column index in pp2 */
117935
117936     if( *p1==POS_COLUMN ) sqlcipher3Fts3GetVarint32(&p1[1], &iCol1);
117937     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
117938     else iCol1 = 0;
117939
117940     if( *p2==POS_COLUMN ) sqlcipher3Fts3GetVarint32(&p2[1], &iCol2);
117941     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
117942     else iCol2 = 0;
117943
117944     if( iCol1==iCol2 ){
117945       sqlcipher3_int64 i1 = 0;       /* Last position from pp1 */
117946       sqlcipher3_int64 i2 = 0;       /* Last position from pp2 */
117947       sqlcipher3_int64 iPrev = 0;
117948       int n = fts3PutColNumber(&p, iCol1);
117949       p1 += n;
117950       p2 += n;
117951
117952       /* At this point, both p1 and p2 point to the start of column-lists
117953       ** for the same column (the column with index iCol1 and iCol2).
117954       ** A column-list is a list of non-negative delta-encoded varints, each 
117955       ** incremented by 2 before being stored. Each list is terminated by a
117956       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
117957       ** and writes the results to buffer p. p is left pointing to the byte
117958       ** after the list written. No terminator (POS_END or POS_COLUMN) is
117959       ** written to the output.
117960       */
117961       fts3GetDeltaVarint(&p1, &i1);
117962       fts3GetDeltaVarint(&p2, &i2);
117963       do {
117964         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
117965         iPrev -= 2;
117966         if( i1==i2 ){
117967           fts3ReadNextPos(&p1, &i1);
117968           fts3ReadNextPos(&p2, &i2);
117969         }else if( i1<i2 ){
117970           fts3ReadNextPos(&p1, &i1);
117971         }else{
117972           fts3ReadNextPos(&p2, &i2);
117973         }
117974       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
117975     }else if( iCol1<iCol2 ){
117976       p1 += fts3PutColNumber(&p, iCol1);
117977       fts3ColumnlistCopy(&p, &p1);
117978     }else{
117979       p2 += fts3PutColNumber(&p, iCol2);
117980       fts3ColumnlistCopy(&p, &p2);
117981     }
117982   }
117983
117984   *p++ = POS_END;
117985   *pp = p;
117986   *pp1 = p1 + 1;
117987   *pp2 = p2 + 1;
117988 }
117989
117990 /*
117991 ** This function is used to merge two position lists into one. When it is
117992 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
117993 ** the part of a doclist that follows each document id. For example, if a row
117994 ** contains:
117995 **
117996 **     'a b c'|'x y z'|'a b b a'
117997 **
117998 ** Then the position list for this row for token 'b' would consist of:
117999 **
118000 **     0x02 0x01 0x02 0x03 0x03 0x00
118001 **
118002 ** When this function returns, both *pp1 and *pp2 are left pointing to the
118003 ** byte following the 0x00 terminator of their respective position lists.
118004 **
118005 ** If isSaveLeft is 0, an entry is added to the output position list for 
118006 ** each position in *pp2 for which there exists one or more positions in
118007 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
118008 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
118009 ** slots before it.
118010 **
118011 ** e.g. nToken==1 searches for adjacent positions.
118012 */
118013 static int fts3PoslistPhraseMerge(
118014   char **pp,                      /* IN/OUT: Preallocated output buffer */
118015   int nToken,                     /* Maximum difference in token positions */
118016   int isSaveLeft,                 /* Save the left position */
118017   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
118018   char **pp1,                     /* IN/OUT: Left input list */
118019   char **pp2                      /* IN/OUT: Right input list */
118020 ){
118021   char *p = *pp;
118022   char *p1 = *pp1;
118023   char *p2 = *pp2;
118024   int iCol1 = 0;
118025   int iCol2 = 0;
118026
118027   /* Never set both isSaveLeft and isExact for the same invocation. */
118028   assert( isSaveLeft==0 || isExact==0 );
118029
118030   assert( p!=0 && *p1!=0 && *p2!=0 );
118031   if( *p1==POS_COLUMN ){ 
118032     p1++;
118033     p1 += sqlcipher3Fts3GetVarint32(p1, &iCol1);
118034   }
118035   if( *p2==POS_COLUMN ){ 
118036     p2++;
118037     p2 += sqlcipher3Fts3GetVarint32(p2, &iCol2);
118038   }
118039
118040   while( 1 ){
118041     if( iCol1==iCol2 ){
118042       char *pSave = p;
118043       sqlcipher3_int64 iPrev = 0;
118044       sqlcipher3_int64 iPos1 = 0;
118045       sqlcipher3_int64 iPos2 = 0;
118046
118047       if( iCol1 ){
118048         *p++ = POS_COLUMN;
118049         p += sqlcipher3Fts3PutVarint(p, iCol1);
118050       }
118051
118052       assert( *p1!=POS_END && *p1!=POS_COLUMN );
118053       assert( *p2!=POS_END && *p2!=POS_COLUMN );
118054       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
118055       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
118056
118057       while( 1 ){
118058         if( iPos2==iPos1+nToken 
118059          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
118060         ){
118061           sqlcipher3_int64 iSave;
118062           iSave = isSaveLeft ? iPos1 : iPos2;
118063           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
118064           pSave = 0;
118065           assert( p );
118066         }
118067         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
118068           if( (*p2&0xFE)==0 ) break;
118069           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
118070         }else{
118071           if( (*p1&0xFE)==0 ) break;
118072           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
118073         }
118074       }
118075
118076       if( pSave ){
118077         assert( pp && p );
118078         p = pSave;
118079       }
118080
118081       fts3ColumnlistCopy(0, &p1);
118082       fts3ColumnlistCopy(0, &p2);
118083       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
118084       if( 0==*p1 || 0==*p2 ) break;
118085
118086       p1++;
118087       p1 += sqlcipher3Fts3GetVarint32(p1, &iCol1);
118088       p2++;
118089       p2 += sqlcipher3Fts3GetVarint32(p2, &iCol2);
118090     }
118091
118092     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
118093     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
118094     ** end of the position list, or the 0x01 that precedes the next 
118095     ** column-number in the position list. 
118096     */
118097     else if( iCol1<iCol2 ){
118098       fts3ColumnlistCopy(0, &p1);
118099       if( 0==*p1 ) break;
118100       p1++;
118101       p1 += sqlcipher3Fts3GetVarint32(p1, &iCol1);
118102     }else{
118103       fts3ColumnlistCopy(0, &p2);
118104       if( 0==*p2 ) break;
118105       p2++;
118106       p2 += sqlcipher3Fts3GetVarint32(p2, &iCol2);
118107     }
118108   }
118109
118110   fts3PoslistCopy(0, &p2);
118111   fts3PoslistCopy(0, &p1);
118112   *pp1 = p1;
118113   *pp2 = p2;
118114   if( *pp==p ){
118115     return 0;
118116   }
118117   *p++ = 0x00;
118118   *pp = p;
118119   return 1;
118120 }
118121
118122 /*
118123 ** Merge two position-lists as required by the NEAR operator. The argument
118124 ** position lists correspond to the left and right phrases of an expression 
118125 ** like:
118126 **
118127 **     "phrase 1" NEAR "phrase number 2"
118128 **
118129 ** Position list *pp1 corresponds to the left-hand side of the NEAR 
118130 ** expression and *pp2 to the right. As usual, the indexes in the position 
118131 ** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
118132 ** in the example above).
118133 **
118134 ** The output position list - written to *pp - is a copy of *pp2 with those
118135 ** entries that are not sufficiently NEAR entries in *pp1 removed.
118136 */
118137 static int fts3PoslistNearMerge(
118138   char **pp,                      /* Output buffer */
118139   char *aTmp,                     /* Temporary buffer space */
118140   int nRight,                     /* Maximum difference in token positions */
118141   int nLeft,                      /* Maximum difference in token positions */
118142   char **pp1,                     /* IN/OUT: Left input list */
118143   char **pp2                      /* IN/OUT: Right input list */
118144 ){
118145   char *p1 = *pp1;
118146   char *p2 = *pp2;
118147
118148   char *pTmp1 = aTmp;
118149   char *pTmp2;
118150   char *aTmp2;
118151   int res = 1;
118152
118153   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
118154   aTmp2 = pTmp2 = pTmp1;
118155   *pp1 = p1;
118156   *pp2 = p2;
118157   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
118158   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
118159     fts3PoslistMerge(pp, &aTmp, &aTmp2);
118160   }else if( pTmp1!=aTmp ){
118161     fts3PoslistCopy(pp, &aTmp);
118162   }else if( pTmp2!=aTmp2 ){
118163     fts3PoslistCopy(pp, &aTmp2);
118164   }else{
118165     res = 0;
118166   }
118167
118168   return res;
118169 }
118170
118171 /* 
118172 ** An instance of this function is used to merge together the (potentially
118173 ** large number of) doclists for each term that matches a prefix query.
118174 ** See function fts3TermSelectMerge() for details.
118175 */
118176 typedef struct TermSelect TermSelect;
118177 struct TermSelect {
118178   char *aaOutput[16];             /* Malloc'd output buffers */
118179   int anOutput[16];               /* Size each output buffer in bytes */
118180 };
118181
118182 /*
118183 ** This function is used to read a single varint from a buffer. Parameter
118184 ** pEnd points 1 byte past the end of the buffer. When this function is
118185 ** called, if *pp points to pEnd or greater, then the end of the buffer
118186 ** has been reached. In this case *pp is set to 0 and the function returns.
118187 **
118188 ** If *pp does not point to or past pEnd, then a single varint is read
118189 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
118190 **
118191 ** If bDescIdx is false, the value read is added to *pVal before returning.
118192 ** If it is true, the value read is subtracted from *pVal before this 
118193 ** function returns.
118194 */
118195 static void fts3GetDeltaVarint3(
118196   char **pp,                      /* IN/OUT: Point to read varint from */
118197   char *pEnd,                     /* End of buffer */
118198   int bDescIdx,                   /* True if docids are descending */
118199   sqlcipher3_int64 *pVal             /* IN/OUT: Integer value */
118200 ){
118201   if( *pp>=pEnd ){
118202     *pp = 0;
118203   }else{
118204     sqlcipher3_int64 iVal;
118205     *pp += sqlcipher3Fts3GetVarint(*pp, &iVal);
118206     if( bDescIdx ){
118207       *pVal -= iVal;
118208     }else{
118209       *pVal += iVal;
118210     }
118211   }
118212 }
118213
118214 /*
118215 ** This function is used to write a single varint to a buffer. The varint
118216 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
118217 ** end of the value written.
118218 **
118219 ** If *pbFirst is zero when this function is called, the value written to
118220 ** the buffer is that of parameter iVal. 
118221 **
118222 ** If *pbFirst is non-zero when this function is called, then the value 
118223 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
118224 ** (if bDescIdx is non-zero).
118225 **
118226 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
118227 ** to the value of parameter iVal.
118228 */
118229 static void fts3PutDeltaVarint3(
118230   char **pp,                      /* IN/OUT: Output pointer */
118231   int bDescIdx,                   /* True for descending docids */
118232   sqlcipher3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
118233   int *pbFirst,                   /* IN/OUT: True after first int written */
118234   sqlcipher3_int64 iVal              /* Write this value to the list */
118235 ){
118236   sqlcipher3_int64 iWrite;
118237   if( bDescIdx==0 || *pbFirst==0 ){
118238     iWrite = iVal - *piPrev;
118239   }else{
118240     iWrite = *piPrev - iVal;
118241   }
118242   assert( *pbFirst || *piPrev==0 );
118243   assert( *pbFirst==0 || iWrite>0 );
118244   *pp += sqlcipher3Fts3PutVarint(*pp, iWrite);
118245   *piPrev = iVal;
118246   *pbFirst = 1;
118247 }
118248
118249
118250 /*
118251 ** This macro is used by various functions that merge doclists. The two
118252 ** arguments are 64-bit docid values. If the value of the stack variable
118253 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 
118254 ** Otherwise, (i2-i1).
118255 **
118256 ** Using this makes it easier to write code that can merge doclists that are
118257 ** sorted in either ascending or descending order.
118258 */
118259 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
118260
118261 /*
118262 ** This function does an "OR" merge of two doclists (output contains all
118263 ** positions contained in either argument doclist). If the docids in the 
118264 ** input doclists are sorted in ascending order, parameter bDescDoclist
118265 ** should be false. If they are sorted in ascending order, it should be
118266 ** passed a non-zero value.
118267 **
118268 ** If no error occurs, *paOut is set to point at an sqlcipher3_malloc'd buffer
118269 ** containing the output doclist and SQLCIPHER_OK is returned. In this case
118270 ** *pnOut is set to the number of bytes in the output doclist.
118271 **
118272 ** If an error occurs, an SQLite error code is returned. The output values
118273 ** are undefined in this case.
118274 */
118275 static int fts3DoclistOrMerge(
118276   int bDescDoclist,               /* True if arguments are desc */
118277   char *a1, int n1,               /* First doclist */
118278   char *a2, int n2,               /* Second doclist */
118279   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
118280 ){
118281   sqlcipher3_int64 i1 = 0;
118282   sqlcipher3_int64 i2 = 0;
118283   sqlcipher3_int64 iPrev = 0;
118284   char *pEnd1 = &a1[n1];
118285   char *pEnd2 = &a2[n2];
118286   char *p1 = a1;
118287   char *p2 = a2;
118288   char *p;
118289   char *aOut;
118290   int bFirstOut = 0;
118291
118292   *paOut = 0;
118293   *pnOut = 0;
118294
118295   /* Allocate space for the output. Both the input and output doclists
118296   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
118297   ** then the first docid in each list is simply encoded as a varint. For
118298   ** each subsequent docid, the varint stored is the difference between the
118299   ** current and previous docid (a positive number - since the list is in
118300   ** ascending order).
118301   **
118302   ** The first docid written to the output is therefore encoded using the 
118303   ** same number of bytes as it is in whichever of the input lists it is
118304   ** read from. And each subsequent docid read from the same input list 
118305   ** consumes either the same or less bytes as it did in the input (since
118306   ** the difference between it and the previous value in the output must
118307   ** be a positive value less than or equal to the delta value read from 
118308   ** the input list). The same argument applies to all but the first docid
118309   ** read from the 'other' list. And to the contents of all position lists
118310   ** that will be copied and merged from the input to the output.
118311   **
118312   ** However, if the first docid copied to the output is a negative number,
118313   ** then the encoding of the first docid from the 'other' input list may
118314   ** be larger in the output than it was in the input (since the delta value
118315   ** may be a larger positive integer than the actual docid).
118316   **
118317   ** The space required to store the output is therefore the sum of the
118318   ** sizes of the two inputs, plus enough space for exactly one of the input
118319   ** docids to grow. 
118320   **
118321   ** A symetric argument may be made if the doclists are in descending 
118322   ** order.
118323   */
118324   aOut = sqlcipher3_malloc(n1+n2+FTS3_VARINT_MAX-1);
118325   if( !aOut ) return SQLCIPHER_NOMEM;
118326
118327   p = aOut;
118328   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
118329   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
118330   while( p1 || p2 ){
118331     sqlcipher3_int64 iDiff = DOCID_CMP(i1, i2);
118332
118333     if( p2 && p1 && iDiff==0 ){
118334       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
118335       fts3PoslistMerge(&p, &p1, &p2);
118336       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118337       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118338     }else if( !p2 || (p1 && iDiff<0) ){
118339       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
118340       fts3PoslistCopy(&p, &p1);
118341       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118342     }else{
118343       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
118344       fts3PoslistCopy(&p, &p2);
118345       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118346     }
118347   }
118348
118349   *paOut = aOut;
118350   *pnOut = (p-aOut);
118351   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
118352   return SQLCIPHER_OK;
118353 }
118354
118355 /*
118356 ** This function does a "phrase" merge of two doclists. In a phrase merge,
118357 ** the output contains a copy of each position from the right-hand input
118358 ** doclist for which there is a position in the left-hand input doclist
118359 ** exactly nDist tokens before it.
118360 **
118361 ** If the docids in the input doclists are sorted in ascending order,
118362 ** parameter bDescDoclist should be false. If they are sorted in ascending 
118363 ** order, it should be passed a non-zero value.
118364 **
118365 ** The right-hand input doclist is overwritten by this function.
118366 */
118367 static void fts3DoclistPhraseMerge(
118368   int bDescDoclist,               /* True if arguments are desc */
118369   int nDist,                      /* Distance from left to right (1=adjacent) */
118370   char *aLeft, int nLeft,         /* Left doclist */
118371   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
118372 ){
118373   sqlcipher3_int64 i1 = 0;
118374   sqlcipher3_int64 i2 = 0;
118375   sqlcipher3_int64 iPrev = 0;
118376   char *pEnd1 = &aLeft[nLeft];
118377   char *pEnd2 = &aRight[*pnRight];
118378   char *p1 = aLeft;
118379   char *p2 = aRight;
118380   char *p;
118381   int bFirstOut = 0;
118382   char *aOut = aRight;
118383
118384   assert( nDist>0 );
118385
118386   p = aOut;
118387   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
118388   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
118389
118390   while( p1 && p2 ){
118391     sqlcipher3_int64 iDiff = DOCID_CMP(i1, i2);
118392     if( iDiff==0 ){
118393       char *pSave = p;
118394       sqlcipher3_int64 iPrevSave = iPrev;
118395       int bFirstOutSave = bFirstOut;
118396
118397       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
118398       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
118399         p = pSave;
118400         iPrev = iPrevSave;
118401         bFirstOut = bFirstOutSave;
118402       }
118403       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118404       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118405     }else if( iDiff<0 ){
118406       fts3PoslistCopy(0, &p1);
118407       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118408     }else{
118409       fts3PoslistCopy(0, &p2);
118410       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118411     }
118412   }
118413
118414   *pnRight = p - aOut;
118415 }
118416
118417 /*
118418 ** Argument pList points to a position list nList bytes in size. This
118419 ** function checks to see if the position list contains any entries for
118420 ** a token in position 0 (of any column). If so, it writes argument iDelta
118421 ** to the output buffer pOut, followed by a position list consisting only
118422 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
118423 ** The value returned is the number of bytes written to pOut (if any).
118424 */
118425 SQLCIPHER_PRIVATE int sqlcipher3Fts3FirstFilter(
118426   sqlcipher3_int64 iDelta,           /* Varint that may be written to pOut */
118427   char *pList,                    /* Position list (no 0x00 term) */
118428   int nList,                      /* Size of pList in bytes */
118429   char *pOut                      /* Write output here */
118430 ){
118431   int nOut = 0;
118432   int bWritten = 0;               /* True once iDelta has been written */
118433   char *p = pList;
118434   char *pEnd = &pList[nList];
118435
118436   if( *p!=0x01 ){
118437     if( *p==0x02 ){
118438       nOut += sqlcipher3Fts3PutVarint(&pOut[nOut], iDelta);
118439       pOut[nOut++] = 0x02;
118440       bWritten = 1;
118441     }
118442     fts3ColumnlistCopy(0, &p);
118443   }
118444
118445   while( p<pEnd && *p==0x01 ){
118446     sqlcipher3_int64 iCol;
118447     p++;
118448     p += sqlcipher3Fts3GetVarint(p, &iCol);
118449     if( *p==0x02 ){
118450       if( bWritten==0 ){
118451         nOut += sqlcipher3Fts3PutVarint(&pOut[nOut], iDelta);
118452         bWritten = 1;
118453       }
118454       pOut[nOut++] = 0x01;
118455       nOut += sqlcipher3Fts3PutVarint(&pOut[nOut], iCol);
118456       pOut[nOut++] = 0x02;
118457     }
118458     fts3ColumnlistCopy(0, &p);
118459   }
118460   if( bWritten ){
118461     pOut[nOut++] = 0x00;
118462   }
118463
118464   return nOut;
118465 }
118466
118467
118468 /*
118469 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
118470 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
118471 ** other doclists (except the aaOutput[0] one) and return SQLCIPHER_OK.
118472 **
118473 ** If an OOM error occurs, return SQLCIPHER_NOMEM. In this case it is
118474 ** the responsibility of the caller to free any doclists left in the
118475 ** TermSelect.aaOutput[] array.
118476 */
118477 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
118478   char *aOut = 0;
118479   int nOut = 0;
118480   int i;
118481
118482   /* Loop through the doclists in the aaOutput[] array. Merge them all
118483   ** into a single doclist.
118484   */
118485   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
118486     if( pTS->aaOutput[i] ){
118487       if( !aOut ){
118488         aOut = pTS->aaOutput[i];
118489         nOut = pTS->anOutput[i];
118490         pTS->aaOutput[i] = 0;
118491       }else{
118492         int nNew;
118493         char *aNew;
118494
118495         int rc = fts3DoclistOrMerge(p->bDescIdx, 
118496             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
118497         );
118498         if( rc!=SQLCIPHER_OK ){
118499           sqlcipher3_free(aOut);
118500           return rc;
118501         }
118502
118503         sqlcipher3_free(pTS->aaOutput[i]);
118504         sqlcipher3_free(aOut);
118505         pTS->aaOutput[i] = 0;
118506         aOut = aNew;
118507         nOut = nNew;
118508       }
118509     }
118510   }
118511
118512   pTS->aaOutput[0] = aOut;
118513   pTS->anOutput[0] = nOut;
118514   return SQLCIPHER_OK;
118515 }
118516
118517 /*
118518 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
118519 ** as the first argument. The merge is an "OR" merge (see function
118520 ** fts3DoclistOrMerge() for details).
118521 **
118522 ** This function is called with the doclist for each term that matches
118523 ** a queried prefix. It merges all these doclists into one, the doclist
118524 ** for the specified prefix. Since there can be a very large number of
118525 ** doclists to merge, the merging is done pair-wise using the TermSelect
118526 ** object.
118527 **
118528 ** This function returns SQLCIPHER_OK if the merge is successful, or an
118529 ** SQLite error code (SQLCIPHER_NOMEM) if an error occurs.
118530 */
118531 static int fts3TermSelectMerge(
118532   Fts3Table *p,                   /* FTS table handle */
118533   TermSelect *pTS,                /* TermSelect object to merge into */
118534   char *aDoclist,                 /* Pointer to doclist */
118535   int nDoclist                    /* Size of aDoclist in bytes */
118536 ){
118537   if( pTS->aaOutput[0]==0 ){
118538     /* If this is the first term selected, copy the doclist to the output
118539     ** buffer using memcpy(). */
118540     pTS->aaOutput[0] = sqlcipher3_malloc(nDoclist);
118541     pTS->anOutput[0] = nDoclist;
118542     if( pTS->aaOutput[0] ){
118543       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
118544     }else{
118545       return SQLCIPHER_NOMEM;
118546     }
118547   }else{
118548     char *aMerge = aDoclist;
118549     int nMerge = nDoclist;
118550     int iOut;
118551
118552     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
118553       if( pTS->aaOutput[iOut]==0 ){
118554         assert( iOut>0 );
118555         pTS->aaOutput[iOut] = aMerge;
118556         pTS->anOutput[iOut] = nMerge;
118557         break;
118558       }else{
118559         char *aNew;
118560         int nNew;
118561
118562         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
118563             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
118564         );
118565         if( rc!=SQLCIPHER_OK ){
118566           if( aMerge!=aDoclist ) sqlcipher3_free(aMerge);
118567           return rc;
118568         }
118569
118570         if( aMerge!=aDoclist ) sqlcipher3_free(aMerge);
118571         sqlcipher3_free(pTS->aaOutput[iOut]);
118572         pTS->aaOutput[iOut] = 0;
118573   
118574         aMerge = aNew;
118575         nMerge = nNew;
118576         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
118577           pTS->aaOutput[iOut] = aMerge;
118578           pTS->anOutput[iOut] = nMerge;
118579         }
118580       }
118581     }
118582   }
118583   return SQLCIPHER_OK;
118584 }
118585
118586 /*
118587 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
118588 */
118589 static int fts3SegReaderCursorAppend(
118590   Fts3MultiSegReader *pCsr, 
118591   Fts3SegReader *pNew
118592 ){
118593   if( (pCsr->nSegment%16)==0 ){
118594     Fts3SegReader **apNew;
118595     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
118596     apNew = (Fts3SegReader **)sqlcipher3_realloc(pCsr->apSegment, nByte);
118597     if( !apNew ){
118598       sqlcipher3Fts3SegReaderFree(pNew);
118599       return SQLCIPHER_NOMEM;
118600     }
118601     pCsr->apSegment = apNew;
118602   }
118603   pCsr->apSegment[pCsr->nSegment++] = pNew;
118604   return SQLCIPHER_OK;
118605 }
118606
118607 /*
118608 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
118609 ** 8th argument.
118610 **
118611 ** This function returns SQLCIPHER_OK if successful, or an SQLite error code
118612 ** otherwise.
118613 */
118614 static int fts3SegReaderCursor(
118615   Fts3Table *p,                   /* FTS3 table handle */
118616   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
118617   int iLevel,                     /* Level of segments to scan */
118618   const char *zTerm,              /* Term to query for */
118619   int nTerm,                      /* Size of zTerm in bytes */
118620   int isPrefix,                   /* True for a prefix search */
118621   int isScan,                     /* True to scan from zTerm to EOF */
118622   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
118623 ){
118624   int rc = SQLCIPHER_OK;             /* Error code */
118625   sqlcipher3_stmt *pStmt = 0;        /* Statement to iterate through segments */
118626   int rc2;                        /* Result of sqlcipher3_reset() */
118627
118628   /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
118629   ** for the pending-terms. If this is a scan, then this call must be being
118630   ** made by an fts4aux module, not an FTS table. In this case calling
118631   ** Fts3SegReaderPending might segfault, as the data structures used by 
118632   ** fts4aux are not completely populated. So it's easiest to filter these
118633   ** calls out here.  */
118634   if( iLevel<0 && p->aIndex ){
118635     Fts3SegReader *pSeg = 0;
118636     rc = sqlcipher3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
118637     if( rc==SQLCIPHER_OK && pSeg ){
118638       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
118639     }
118640   }
118641
118642   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
118643     if( rc==SQLCIPHER_OK ){
118644       rc = sqlcipher3Fts3AllSegdirs(p, iIndex, iLevel, &pStmt);
118645     }
118646
118647     while( rc==SQLCIPHER_OK && SQLCIPHER_ROW==(rc = sqlcipher3_step(pStmt)) ){
118648       Fts3SegReader *pSeg = 0;
118649
118650       /* Read the values returned by the SELECT into local variables. */
118651       sqlcipher3_int64 iStartBlock = sqlcipher3_column_int64(pStmt, 1);
118652       sqlcipher3_int64 iLeavesEndBlock = sqlcipher3_column_int64(pStmt, 2);
118653       sqlcipher3_int64 iEndBlock = sqlcipher3_column_int64(pStmt, 3);
118654       int nRoot = sqlcipher3_column_bytes(pStmt, 4);
118655       char const *zRoot = sqlcipher3_column_blob(pStmt, 4);
118656
118657       /* If zTerm is not NULL, and this segment is not stored entirely on its
118658       ** root node, the range of leaves scanned can be reduced. Do this. */
118659       if( iStartBlock && zTerm ){
118660         sqlcipher3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
118661         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
118662         if( rc!=SQLCIPHER_OK ) goto finished;
118663         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
118664       }
118665  
118666       rc = sqlcipher3Fts3SegReaderNew(pCsr->nSegment+1, 
118667           iStartBlock, iLeavesEndBlock, iEndBlock, zRoot, nRoot, &pSeg
118668       );
118669       if( rc!=SQLCIPHER_OK ) goto finished;
118670       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
118671     }
118672   }
118673
118674  finished:
118675   rc2 = sqlcipher3_reset(pStmt);
118676   if( rc==SQLCIPHER_DONE ) rc = rc2;
118677
118678   return rc;
118679 }
118680
118681 /*
118682 ** Set up a cursor object for iterating through a full-text index or a 
118683 ** single level therein.
118684 */
118685 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderCursor(
118686   Fts3Table *p,                   /* FTS3 table handle */
118687   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
118688   int iLevel,                     /* Level of segments to scan */
118689   const char *zTerm,              /* Term to query for */
118690   int nTerm,                      /* Size of zTerm in bytes */
118691   int isPrefix,                   /* True for a prefix search */
118692   int isScan,                     /* True to scan from zTerm to EOF */
118693   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
118694 ){
118695   assert( iIndex>=0 && iIndex<p->nIndex );
118696   assert( iLevel==FTS3_SEGCURSOR_ALL
118697       ||  iLevel==FTS3_SEGCURSOR_PENDING 
118698       ||  iLevel>=0
118699   );
118700   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
118701   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
118702   assert( isPrefix==0 || isScan==0 );
118703
118704   /* "isScan" is only set to true by the ft4aux module, an ordinary
118705   ** full-text tables. */
118706   assert( isScan==0 || p->aIndex==0 );
118707
118708   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
118709
118710   return fts3SegReaderCursor(
118711       p, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
118712   );
118713 }
118714
118715 /*
118716 ** In addition to its current configuration, have the Fts3MultiSegReader
118717 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
118718 **
118719 ** SQLCIPHER_OK is returned if no error occurs, otherwise an SQLite error code.
118720 */
118721 static int fts3SegReaderCursorAddZero(
118722   Fts3Table *p,                   /* FTS virtual table handle */
118723   const char *zTerm,              /* Term to scan doclist of */
118724   int nTerm,                      /* Number of bytes in zTerm */
118725   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
118726 ){
118727   return fts3SegReaderCursor(p, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr);
118728 }
118729
118730 /*
118731 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
118732 ** if isPrefix is true, to scan the doclist for all terms for which 
118733 ** zTerm/nTerm is a prefix. If successful, return SQLCIPHER_OK and write
118734 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
118735 ** an SQLite error code.
118736 **
118737 ** It is the responsibility of the caller to free this object by eventually
118738 ** passing it to fts3SegReaderCursorFree() 
118739 **
118740 ** SQLCIPHER_OK is returned if no error occurs, otherwise an SQLite error code.
118741 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
118742 */
118743 static int fts3TermSegReaderCursor(
118744   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
118745   const char *zTerm,              /* Term to query for */
118746   int nTerm,                      /* Size of zTerm in bytes */
118747   int isPrefix,                   /* True for a prefix search */
118748   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
118749 ){
118750   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
118751   int rc = SQLCIPHER_NOMEM;          /* Return code */
118752
118753   pSegcsr = sqlcipher3_malloc(sizeof(Fts3MultiSegReader));
118754   if( pSegcsr ){
118755     int i;
118756     int bFound = 0;               /* True once an index has been found */
118757     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
118758
118759     if( isPrefix ){
118760       for(i=1; bFound==0 && i<p->nIndex; i++){
118761         if( p->aIndex[i].nPrefix==nTerm ){
118762           bFound = 1;
118763           rc = sqlcipher3Fts3SegReaderCursor(
118764               p, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr);
118765           pSegcsr->bLookup = 1;
118766         }
118767       }
118768
118769       for(i=1; bFound==0 && i<p->nIndex; i++){
118770         if( p->aIndex[i].nPrefix==nTerm+1 ){
118771           bFound = 1;
118772           rc = sqlcipher3Fts3SegReaderCursor(
118773               p, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
118774           );
118775           if( rc==SQLCIPHER_OK ){
118776             rc = fts3SegReaderCursorAddZero(p, zTerm, nTerm, pSegcsr);
118777           }
118778         }
118779       }
118780     }
118781
118782     if( bFound==0 ){
118783       rc = sqlcipher3Fts3SegReaderCursor(
118784           p, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
118785       );
118786       pSegcsr->bLookup = !isPrefix;
118787     }
118788   }
118789
118790   *ppSegcsr = pSegcsr;
118791   return rc;
118792 }
118793
118794 /*
118795 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
118796 */
118797 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
118798   sqlcipher3Fts3SegReaderFinish(pSegcsr);
118799   sqlcipher3_free(pSegcsr);
118800 }
118801
118802 /*
118803 ** This function retreives the doclist for the specified term (or term
118804 ** prefix) from the database.
118805 */
118806 static int fts3TermSelect(
118807   Fts3Table *p,                   /* Virtual table handle */
118808   Fts3PhraseToken *pTok,          /* Token to query for */
118809   int iColumn,                    /* Column to query (or -ve for all columns) */
118810   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
118811   char **ppOut                    /* OUT: Malloced result buffer */
118812 ){
118813   int rc;                         /* Return code */
118814   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
118815   TermSelect tsc;                 /* Object for pair-wise doclist merging */
118816   Fts3SegFilter filter;           /* Segment term filter configuration */
118817
118818   pSegcsr = pTok->pSegcsr;
118819   memset(&tsc, 0, sizeof(TermSelect));
118820
118821   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
118822         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
118823         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
118824         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
118825   filter.iCol = iColumn;
118826   filter.zTerm = pTok->z;
118827   filter.nTerm = pTok->n;
118828
118829   rc = sqlcipher3Fts3SegReaderStart(p, pSegcsr, &filter);
118830   while( SQLCIPHER_OK==rc
118831       && SQLCIPHER_ROW==(rc = sqlcipher3Fts3SegReaderStep(p, pSegcsr)) 
118832   ){
118833     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
118834   }
118835
118836   if( rc==SQLCIPHER_OK ){
118837     rc = fts3TermSelectFinishMerge(p, &tsc);
118838   }
118839   if( rc==SQLCIPHER_OK ){
118840     *ppOut = tsc.aaOutput[0];
118841     *pnOut = tsc.anOutput[0];
118842   }else{
118843     int i;
118844     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
118845       sqlcipher3_free(tsc.aaOutput[i]);
118846     }
118847   }
118848
118849   fts3SegReaderCursorFree(pSegcsr);
118850   pTok->pSegcsr = 0;
118851   return rc;
118852 }
118853
118854 /*
118855 ** This function counts the total number of docids in the doclist stored
118856 ** in buffer aList[], size nList bytes.
118857 **
118858 ** If the isPoslist argument is true, then it is assumed that the doclist
118859 ** contains a position-list following each docid. Otherwise, it is assumed
118860 ** that the doclist is simply a list of docids stored as delta encoded 
118861 ** varints.
118862 */
118863 static int fts3DoclistCountDocids(char *aList, int nList){
118864   int nDoc = 0;                   /* Return value */
118865   if( aList ){
118866     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
118867     char *p = aList;              /* Cursor */
118868     while( p<aEnd ){
118869       nDoc++;
118870       while( (*p++)&0x80 );     /* Skip docid varint */
118871       fts3PoslistCopy(0, &p);   /* Skip over position list */
118872     }
118873   }
118874
118875   return nDoc;
118876 }
118877
118878 /*
118879 ** Advance the cursor to the next row in the %_content table that
118880 ** matches the search criteria.  For a MATCH search, this will be
118881 ** the next row that matches. For a full-table scan, this will be
118882 ** simply the next row in the %_content table.  For a docid lookup,
118883 ** this routine simply sets the EOF flag.
118884 **
118885 ** Return SQLCIPHER_OK if nothing goes wrong.  SQLCIPHER_OK is returned
118886 ** even if we reach end-of-file.  The fts3EofMethod() will be called
118887 ** subsequently to determine whether or not an EOF was hit.
118888 */
118889 static int fts3NextMethod(sqlcipher3_vtab_cursor *pCursor){
118890   int rc;
118891   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
118892   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
118893     if( SQLCIPHER_ROW!=sqlcipher3_step(pCsr->pStmt) ){
118894       pCsr->isEof = 1;
118895       rc = sqlcipher3_reset(pCsr->pStmt);
118896     }else{
118897       pCsr->iPrevId = sqlcipher3_column_int64(pCsr->pStmt, 0);
118898       rc = SQLCIPHER_OK;
118899     }
118900   }else{
118901     rc = fts3EvalNext((Fts3Cursor *)pCursor);
118902   }
118903   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
118904   return rc;
118905 }
118906
118907 /*
118908 ** This is the xFilter interface for the virtual table.  See
118909 ** the virtual table xFilter method documentation for additional
118910 ** information.
118911 **
118912 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
118913 ** the %_content table.
118914 **
118915 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
118916 ** in the %_content table.
118917 **
118918 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
118919 ** column on the left-hand side of the MATCH operator is column
118920 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
118921 ** side of the MATCH operator.
118922 */
118923 static int fts3FilterMethod(
118924   sqlcipher3_vtab_cursor *pCursor,   /* The cursor used for this query */
118925   int idxNum,                     /* Strategy index */
118926   const char *idxStr,             /* Unused */
118927   int nVal,                       /* Number of elements in apVal */
118928   sqlcipher3_value **apVal           /* Arguments for the indexing scheme */
118929 ){
118930   int rc;
118931   char *zSql;                     /* SQL statement used to access %_content */
118932   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
118933   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
118934
118935   UNUSED_PARAMETER(idxStr);
118936   UNUSED_PARAMETER(nVal);
118937
118938   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
118939   assert( nVal==0 || nVal==1 );
118940   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
118941   assert( p->pSegments==0 );
118942
118943   /* In case the cursor has been used before, clear it now. */
118944   sqlcipher3_finalize(pCsr->pStmt);
118945   sqlcipher3_free(pCsr->aDoclist);
118946   sqlcipher3Fts3ExprFree(pCsr->pExpr);
118947   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlcipher3_vtab_cursor));
118948
118949   if( idxStr ){
118950     pCsr->bDesc = (idxStr[0]=='D');
118951   }else{
118952     pCsr->bDesc = p->bDescIdx;
118953   }
118954   pCsr->eSearch = (i16)idxNum;
118955
118956   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
118957     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
118958     const char *zQuery = (const char *)sqlcipher3_value_text(apVal[0]);
118959
118960     if( zQuery==0 && sqlcipher3_value_type(apVal[0])!=SQLCIPHER_NULL ){
118961       return SQLCIPHER_NOMEM;
118962     }
118963
118964     rc = sqlcipher3Fts3ExprParse(p->pTokenizer, p->azColumn, p->bHasStat, 
118965         p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
118966     );
118967     if( rc!=SQLCIPHER_OK ){
118968       if( rc==SQLCIPHER_ERROR ){
118969         static const char *zErr = "malformed MATCH expression: [%s]";
118970         p->base.zErrMsg = sqlcipher3_mprintf(zErr, zQuery);
118971       }
118972       return rc;
118973     }
118974
118975     rc = sqlcipher3Fts3ReadLock(p);
118976     if( rc!=SQLCIPHER_OK ) return rc;
118977
118978     rc = fts3EvalStart(pCsr);
118979
118980     sqlcipher3Fts3SegmentsClose(p);
118981     if( rc!=SQLCIPHER_OK ) return rc;
118982     pCsr->pNextId = pCsr->aDoclist;
118983     pCsr->iPrevId = 0;
118984   }
118985
118986   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
118987   ** statement loops through all rows of the %_content table. For a
118988   ** full-text query or docid lookup, the statement retrieves a single
118989   ** row by docid.
118990   */
118991   if( idxNum==FTS3_FULLSCAN_SEARCH ){
118992     zSql = sqlcipher3_mprintf(
118993         "SELECT %s ORDER BY rowid %s",
118994         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
118995     );
118996     if( zSql ){
118997       rc = sqlcipher3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
118998       sqlcipher3_free(zSql);
118999     }else{
119000       rc = SQLCIPHER_NOMEM;
119001     }
119002   }else if( idxNum==FTS3_DOCID_SEARCH ){
119003     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
119004     if( rc==SQLCIPHER_OK ){
119005       rc = sqlcipher3_bind_value(pCsr->pStmt, 1, apVal[0]);
119006     }
119007   }
119008   if( rc!=SQLCIPHER_OK ) return rc;
119009
119010   return fts3NextMethod(pCursor);
119011 }
119012
119013 /* 
119014 ** This is the xEof method of the virtual table. SQLite calls this 
119015 ** routine to find out if it has reached the end of a result set.
119016 */
119017 static int fts3EofMethod(sqlcipher3_vtab_cursor *pCursor){
119018   return ((Fts3Cursor *)pCursor)->isEof;
119019 }
119020
119021 /* 
119022 ** This is the xRowid method. The SQLite core calls this routine to
119023 ** retrieve the rowid for the current row of the result set. fts3
119024 ** exposes %_content.docid as the rowid for the virtual table. The
119025 ** rowid should be written to *pRowid.
119026 */
119027 static int fts3RowidMethod(sqlcipher3_vtab_cursor *pCursor, sqlcipher_int64 *pRowid){
119028   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
119029   *pRowid = pCsr->iPrevId;
119030   return SQLCIPHER_OK;
119031 }
119032
119033 /* 
119034 ** This is the xColumn method, called by SQLite to request a value from
119035 ** the row that the supplied cursor currently points to.
119036 */
119037 static int fts3ColumnMethod(
119038   sqlcipher3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
119039   sqlcipher3_context *pContext,      /* Context for sqlcipher3_result_xxx() calls */
119040   int iCol                        /* Index of column to read value from */
119041 ){
119042   int rc = SQLCIPHER_OK;             /* Return Code */
119043   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
119044   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
119045
119046   /* The column value supplied by SQLite must be in range. */
119047   assert( iCol>=0 && iCol<=p->nColumn+1 );
119048
119049   if( iCol==p->nColumn+1 ){
119050     /* This call is a request for the "docid" column. Since "docid" is an 
119051     ** alias for "rowid", use the xRowid() method to obtain the value.
119052     */
119053     sqlcipher3_result_int64(pContext, pCsr->iPrevId);
119054   }else if( iCol==p->nColumn ){
119055     /* The extra column whose name is the same as the table.
119056     ** Return a blob which is a pointer to the cursor.
119057     */
119058     sqlcipher3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLCIPHER_TRANSIENT);
119059   }else{
119060     rc = fts3CursorSeek(0, pCsr);
119061     if( rc==SQLCIPHER_OK && sqlcipher3_data_count(pCsr->pStmt)>(iCol+1) ){
119062       sqlcipher3_result_value(pContext, sqlcipher3_column_value(pCsr->pStmt, iCol+1));
119063     }
119064   }
119065
119066   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119067   return rc;
119068 }
119069
119070 /* 
119071 ** This function is the implementation of the xUpdate callback used by 
119072 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
119073 ** inserted, updated or deleted.
119074 */
119075 static int fts3UpdateMethod(
119076   sqlcipher3_vtab *pVtab,            /* Virtual table handle */
119077   int nArg,                       /* Size of argument array */
119078   sqlcipher3_value **apVal,          /* Array of arguments */
119079   sqlcipher_int64 *pRowid            /* OUT: The affected (or effected) rowid */
119080 ){
119081   return sqlcipher3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
119082 }
119083
119084 /*
119085 ** Implementation of xSync() method. Flush the contents of the pending-terms
119086 ** hash-table to the database.
119087 */
119088 static int fts3SyncMethod(sqlcipher3_vtab *pVtab){
119089   int rc = sqlcipher3Fts3PendingTermsFlush((Fts3Table *)pVtab);
119090   sqlcipher3Fts3SegmentsClose((Fts3Table *)pVtab);
119091   return rc;
119092 }
119093
119094 /*
119095 ** Implementation of xBegin() method. This is a no-op.
119096 */
119097 static int fts3BeginMethod(sqlcipher3_vtab *pVtab){
119098   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
119099   UNUSED_PARAMETER(pVtab);
119100   assert( p->pSegments==0 );
119101   assert( p->nPendingData==0 );
119102   assert( p->inTransaction!=1 );
119103   TESTONLY( p->inTransaction = 1 );
119104   TESTONLY( p->mxSavepoint = -1; );
119105   return SQLCIPHER_OK;
119106 }
119107
119108 /*
119109 ** Implementation of xCommit() method. This is a no-op. The contents of
119110 ** the pending-terms hash-table have already been flushed into the database
119111 ** by fts3SyncMethod().
119112 */
119113 static int fts3CommitMethod(sqlcipher3_vtab *pVtab){
119114   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
119115   UNUSED_PARAMETER(pVtab);
119116   assert( p->nPendingData==0 );
119117   assert( p->inTransaction!=0 );
119118   assert( p->pSegments==0 );
119119   TESTONLY( p->inTransaction = 0 );
119120   TESTONLY( p->mxSavepoint = -1; );
119121   return SQLCIPHER_OK;
119122 }
119123
119124 /*
119125 ** Implementation of xRollback(). Discard the contents of the pending-terms
119126 ** hash-table. Any changes made to the database are reverted by SQLite.
119127 */
119128 static int fts3RollbackMethod(sqlcipher3_vtab *pVtab){
119129   Fts3Table *p = (Fts3Table*)pVtab;
119130   sqlcipher3Fts3PendingTermsClear(p);
119131   assert( p->inTransaction!=0 );
119132   TESTONLY( p->inTransaction = 0 );
119133   TESTONLY( p->mxSavepoint = -1; );
119134   return SQLCIPHER_OK;
119135 }
119136
119137 /*
119138 ** When called, *ppPoslist must point to the byte immediately following the
119139 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
119140 ** moves *ppPoslist so that it instead points to the first byte of the
119141 ** same position list.
119142 */
119143 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
119144   char *p = &(*ppPoslist)[-2];
119145   char c = 0;
119146
119147   while( p>pStart && (c=*p--)==0 );
119148   while( p>pStart && (*p & 0x80) | c ){ 
119149     c = *p--; 
119150   }
119151   if( p>pStart ){ p = &p[2]; }
119152   while( *p++&0x80 );
119153   *ppPoslist = p;
119154 }
119155
119156 /*
119157 ** Helper function used by the implementation of the overloaded snippet(),
119158 ** offsets() and optimize() SQL functions.
119159 **
119160 ** If the value passed as the third argument is a blob of size
119161 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
119162 ** output variable *ppCsr and SQLCIPHER_OK is returned. Otherwise, an error
119163 ** message is written to context pContext and SQLCIPHER_ERROR returned. The
119164 ** string passed via zFunc is used as part of the error message.
119165 */
119166 static int fts3FunctionArg(
119167   sqlcipher3_context *pContext,      /* SQL function call context */
119168   const char *zFunc,              /* Function name */
119169   sqlcipher3_value *pVal,            /* argv[0] passed to function */
119170   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
119171 ){
119172   Fts3Cursor *pRet;
119173   if( sqlcipher3_value_type(pVal)!=SQLCIPHER_BLOB 
119174    || sqlcipher3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
119175   ){
119176     char *zErr = sqlcipher3_mprintf("illegal first argument to %s", zFunc);
119177     sqlcipher3_result_error(pContext, zErr, -1);
119178     sqlcipher3_free(zErr);
119179     return SQLCIPHER_ERROR;
119180   }
119181   memcpy(&pRet, sqlcipher3_value_blob(pVal), sizeof(Fts3Cursor *));
119182   *ppCsr = pRet;
119183   return SQLCIPHER_OK;
119184 }
119185
119186 /*
119187 ** Implementation of the snippet() function for FTS3
119188 */
119189 static void fts3SnippetFunc(
119190   sqlcipher3_context *pContext,      /* SQLite function call context */
119191   int nVal,                       /* Size of apVal[] array */
119192   sqlcipher3_value **apVal           /* Array of arguments */
119193 ){
119194   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119195   const char *zStart = "<b>";
119196   const char *zEnd = "</b>";
119197   const char *zEllipsis = "<b>...</b>";
119198   int iCol = -1;
119199   int nToken = 15;                /* Default number of tokens in snippet */
119200
119201   /* There must be at least one argument passed to this function (otherwise
119202   ** the non-overloaded version would have been called instead of this one).
119203   */
119204   assert( nVal>=1 );
119205
119206   if( nVal>6 ){
119207     sqlcipher3_result_error(pContext, 
119208         "wrong number of arguments to function snippet()", -1);
119209     return;
119210   }
119211   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
119212
119213   switch( nVal ){
119214     case 6: nToken = sqlcipher3_value_int(apVal[5]);
119215     case 5: iCol = sqlcipher3_value_int(apVal[4]);
119216     case 4: zEllipsis = (const char*)sqlcipher3_value_text(apVal[3]);
119217     case 3: zEnd = (const char*)sqlcipher3_value_text(apVal[2]);
119218     case 2: zStart = (const char*)sqlcipher3_value_text(apVal[1]);
119219   }
119220   if( !zEllipsis || !zEnd || !zStart ){
119221     sqlcipher3_result_error_nomem(pContext);
119222   }else if( SQLCIPHER_OK==fts3CursorSeek(pContext, pCsr) ){
119223     sqlcipher3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
119224   }
119225 }
119226
119227 /*
119228 ** Implementation of the offsets() function for FTS3
119229 */
119230 static void fts3OffsetsFunc(
119231   sqlcipher3_context *pContext,      /* SQLite function call context */
119232   int nVal,                       /* Size of argument array */
119233   sqlcipher3_value **apVal           /* Array of arguments */
119234 ){
119235   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119236
119237   UNUSED_PARAMETER(nVal);
119238
119239   assert( nVal==1 );
119240   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
119241   assert( pCsr );
119242   if( SQLCIPHER_OK==fts3CursorSeek(pContext, pCsr) ){
119243     sqlcipher3Fts3Offsets(pContext, pCsr);
119244   }
119245 }
119246
119247 /* 
119248 ** Implementation of the special optimize() function for FTS3. This 
119249 ** function merges all segments in the database to a single segment.
119250 ** Example usage is:
119251 **
119252 **   SELECT optimize(t) FROM t LIMIT 1;
119253 **
119254 ** where 't' is the name of an FTS3 table.
119255 */
119256 static void fts3OptimizeFunc(
119257   sqlcipher3_context *pContext,      /* SQLite function call context */
119258   int nVal,                       /* Size of argument array */
119259   sqlcipher3_value **apVal           /* Array of arguments */
119260 ){
119261   int rc;                         /* Return code */
119262   Fts3Table *p;                   /* Virtual table handle */
119263   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
119264
119265   UNUSED_PARAMETER(nVal);
119266
119267   assert( nVal==1 );
119268   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
119269   p = (Fts3Table *)pCursor->base.pVtab;
119270   assert( p );
119271
119272   rc = sqlcipher3Fts3Optimize(p);
119273
119274   switch( rc ){
119275     case SQLCIPHER_OK:
119276       sqlcipher3_result_text(pContext, "Index optimized", -1, SQLCIPHER_STATIC);
119277       break;
119278     case SQLCIPHER_DONE:
119279       sqlcipher3_result_text(pContext, "Index already optimal", -1, SQLCIPHER_STATIC);
119280       break;
119281     default:
119282       sqlcipher3_result_error_code(pContext, rc);
119283       break;
119284   }
119285 }
119286
119287 /*
119288 ** Implementation of the matchinfo() function for FTS3
119289 */
119290 static void fts3MatchinfoFunc(
119291   sqlcipher3_context *pContext,      /* SQLite function call context */
119292   int nVal,                       /* Size of argument array */
119293   sqlcipher3_value **apVal           /* Array of arguments */
119294 ){
119295   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119296   assert( nVal==1 || nVal==2 );
119297   if( SQLCIPHER_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
119298     const char *zArg = 0;
119299     if( nVal>1 ){
119300       zArg = (const char *)sqlcipher3_value_text(apVal[1]);
119301     }
119302     sqlcipher3Fts3Matchinfo(pContext, pCsr, zArg);
119303   }
119304 }
119305
119306 /*
119307 ** This routine implements the xFindFunction method for the FTS3
119308 ** virtual table.
119309 */
119310 static int fts3FindFunctionMethod(
119311   sqlcipher3_vtab *pVtab,            /* Virtual table handle */
119312   int nArg,                       /* Number of SQL function arguments */
119313   const char *zName,              /* Name of SQL function */
119314   void (**pxFunc)(sqlcipher3_context*,int,sqlcipher3_value**), /* OUT: Result */
119315   void **ppArg                    /* Unused */
119316 ){
119317   struct Overloaded {
119318     const char *zName;
119319     void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**);
119320   } aOverload[] = {
119321     { "snippet", fts3SnippetFunc },
119322     { "offsets", fts3OffsetsFunc },
119323     { "optimize", fts3OptimizeFunc },
119324     { "matchinfo", fts3MatchinfoFunc },
119325   };
119326   int i;                          /* Iterator variable */
119327
119328   UNUSED_PARAMETER(pVtab);
119329   UNUSED_PARAMETER(nArg);
119330   UNUSED_PARAMETER(ppArg);
119331
119332   for(i=0; i<SizeofArray(aOverload); i++){
119333     if( strcmp(zName, aOverload[i].zName)==0 ){
119334       *pxFunc = aOverload[i].xFunc;
119335       return 1;
119336     }
119337   }
119338
119339   /* No function of the specified name was found. Return 0. */
119340   return 0;
119341 }
119342
119343 /*
119344 ** Implementation of FTS3 xRename method. Rename an fts3 table.
119345 */
119346 static int fts3RenameMethod(
119347   sqlcipher3_vtab *pVtab,            /* Virtual table handle */
119348   const char *zName               /* New name of table */
119349 ){
119350   Fts3Table *p = (Fts3Table *)pVtab;
119351   sqlcipher3 *db = p->db;            /* Database connection */
119352   int rc;                         /* Return Code */
119353
119354   /* As it happens, the pending terms table is always empty here. This is
119355   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 
119356   ** always opens a savepoint transaction. And the xSavepoint() method 
119357   ** flushes the pending terms table. But leave the (no-op) call to
119358   ** PendingTermsFlush() in in case that changes.
119359   */
119360   assert( p->nPendingData==0 );
119361   rc = sqlcipher3Fts3PendingTermsFlush(p);
119362
119363   if( p->zContentTbl==0 ){
119364     fts3DbExec(&rc, db,
119365       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
119366       p->zDb, p->zName, zName
119367     );
119368   }
119369
119370   if( p->bHasDocsize ){
119371     fts3DbExec(&rc, db,
119372       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
119373       p->zDb, p->zName, zName
119374     );
119375   }
119376   if( p->bHasStat ){
119377     fts3DbExec(&rc, db,
119378       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
119379       p->zDb, p->zName, zName
119380     );
119381   }
119382   fts3DbExec(&rc, db,
119383     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
119384     p->zDb, p->zName, zName
119385   );
119386   fts3DbExec(&rc, db,
119387     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
119388     p->zDb, p->zName, zName
119389   );
119390   return rc;
119391 }
119392
119393 /*
119394 ** The xSavepoint() method.
119395 **
119396 ** Flush the contents of the pending-terms table to disk.
119397 */
119398 static int fts3SavepointMethod(sqlcipher3_vtab *pVtab, int iSavepoint){
119399   UNUSED_PARAMETER(iSavepoint);
119400   assert( ((Fts3Table *)pVtab)->inTransaction );
119401   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
119402   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
119403   return fts3SyncMethod(pVtab);
119404 }
119405
119406 /*
119407 ** The xRelease() method.
119408 **
119409 ** This is a no-op.
119410 */
119411 static int fts3ReleaseMethod(sqlcipher3_vtab *pVtab, int iSavepoint){
119412   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
119413   UNUSED_PARAMETER(iSavepoint);
119414   UNUSED_PARAMETER(pVtab);
119415   assert( p->inTransaction );
119416   assert( p->mxSavepoint >= iSavepoint );
119417   TESTONLY( p->mxSavepoint = iSavepoint-1 );
119418   return SQLCIPHER_OK;
119419 }
119420
119421 /*
119422 ** The xRollbackTo() method.
119423 **
119424 ** Discard the contents of the pending terms table.
119425 */
119426 static int fts3RollbackToMethod(sqlcipher3_vtab *pVtab, int iSavepoint){
119427   Fts3Table *p = (Fts3Table*)pVtab;
119428   UNUSED_PARAMETER(iSavepoint);
119429   assert( p->inTransaction );
119430   assert( p->mxSavepoint >= iSavepoint );
119431   TESTONLY( p->mxSavepoint = iSavepoint );
119432   sqlcipher3Fts3PendingTermsClear(p);
119433   return SQLCIPHER_OK;
119434 }
119435
119436 static const sqlcipher3_module fts3Module = {
119437   /* iVersion      */ 2,
119438   /* xCreate       */ fts3CreateMethod,
119439   /* xConnect      */ fts3ConnectMethod,
119440   /* xBestIndex    */ fts3BestIndexMethod,
119441   /* xDisconnect   */ fts3DisconnectMethod,
119442   /* xDestroy      */ fts3DestroyMethod,
119443   /* xOpen         */ fts3OpenMethod,
119444   /* xClose        */ fts3CloseMethod,
119445   /* xFilter       */ fts3FilterMethod,
119446   /* xNext         */ fts3NextMethod,
119447   /* xEof          */ fts3EofMethod,
119448   /* xColumn       */ fts3ColumnMethod,
119449   /* xRowid        */ fts3RowidMethod,
119450   /* xUpdate       */ fts3UpdateMethod,
119451   /* xBegin        */ fts3BeginMethod,
119452   /* xSync         */ fts3SyncMethod,
119453   /* xCommit       */ fts3CommitMethod,
119454   /* xRollback     */ fts3RollbackMethod,
119455   /* xFindFunction */ fts3FindFunctionMethod,
119456   /* xRename */       fts3RenameMethod,
119457   /* xSavepoint    */ fts3SavepointMethod,
119458   /* xRelease      */ fts3ReleaseMethod,
119459   /* xRollbackTo   */ fts3RollbackToMethod,
119460 };
119461
119462 /*
119463 ** This function is registered as the module destructor (called when an
119464 ** FTS3 enabled database connection is closed). It frees the memory
119465 ** allocated for the tokenizer hash table.
119466 */
119467 static void hashDestroy(void *p){
119468   Fts3Hash *pHash = (Fts3Hash *)p;
119469   sqlcipher3Fts3HashClear(pHash);
119470   sqlcipher3_free(pHash);
119471 }
119472
119473 /*
119474 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
119475 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
119476 ** respectively. The following three forward declarations are for functions
119477 ** declared in these files used to retrieve the respective implementations.
119478 **
119479 ** Calling sqlcipher3Fts3SimpleTokenizerModule() sets the value pointed
119480 ** to by the argument to point to the "simple" tokenizer implementation.
119481 ** And so on.
119482 */
119483 SQLCIPHER_PRIVATE void sqlcipher3Fts3SimpleTokenizerModule(sqlcipher3_tokenizer_module const**ppModule);
119484 SQLCIPHER_PRIVATE void sqlcipher3Fts3PorterTokenizerModule(sqlcipher3_tokenizer_module const**ppModule);
119485 #ifdef SQLCIPHER_ENABLE_ICU
119486 SQLCIPHER_PRIVATE void sqlcipher3Fts3IcuTokenizerModule(sqlcipher3_tokenizer_module const**ppModule);
119487 #endif
119488
119489 /*
119490 ** Initialise the fts3 extension. If this extension is built as part
119491 ** of the sqlcipher library, then this function is called directly by
119492 ** SQLite. If fts3 is built as a dynamically loadable extension, this
119493 ** function is called by the sqlcipher3_extension_init() entry point.
119494 */
119495 SQLCIPHER_PRIVATE int sqlcipher3Fts3Init(sqlcipher3 *db){
119496   int rc = SQLCIPHER_OK;
119497   Fts3Hash *pHash = 0;
119498   const sqlcipher3_tokenizer_module *pSimple = 0;
119499   const sqlcipher3_tokenizer_module *pPorter = 0;
119500
119501 #ifdef SQLCIPHER_ENABLE_ICU
119502   const sqlcipher3_tokenizer_module *pIcu = 0;
119503   sqlcipher3Fts3IcuTokenizerModule(&pIcu);
119504 #endif
119505
119506 #ifdef SQLCIPHER_TEST
119507   rc = sqlcipher3Fts3InitTerm(db);
119508   if( rc!=SQLCIPHER_OK ) return rc;
119509 #endif
119510
119511   rc = sqlcipher3Fts3InitAux(db);
119512   if( rc!=SQLCIPHER_OK ) return rc;
119513
119514   sqlcipher3Fts3SimpleTokenizerModule(&pSimple);
119515   sqlcipher3Fts3PorterTokenizerModule(&pPorter);
119516
119517   /* Allocate and initialise the hash-table used to store tokenizers. */
119518   pHash = sqlcipher3_malloc(sizeof(Fts3Hash));
119519   if( !pHash ){
119520     rc = SQLCIPHER_NOMEM;
119521   }else{
119522     sqlcipher3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
119523   }
119524
119525   /* Load the built-in tokenizers into the hash table */
119526   if( rc==SQLCIPHER_OK ){
119527     if( sqlcipher3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
119528      || sqlcipher3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
119529 #ifdef SQLCIPHER_ENABLE_ICU
119530      || (pIcu && sqlcipher3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
119531 #endif
119532     ){
119533       rc = SQLCIPHER_NOMEM;
119534     }
119535   }
119536
119537 #ifdef SQLCIPHER_TEST
119538   if( rc==SQLCIPHER_OK ){
119539     rc = sqlcipher3Fts3ExprInitTestInterface(db);
119540   }
119541 #endif
119542
119543   /* Create the virtual table wrapper around the hash-table and overload 
119544   ** the two scalar functions. If this is successful, register the
119545   ** module with sqlcipher.
119546   */
119547   if( SQLCIPHER_OK==rc 
119548    && SQLCIPHER_OK==(rc = sqlcipher3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
119549    && SQLCIPHER_OK==(rc = sqlcipher3_overload_function(db, "snippet", -1))
119550    && SQLCIPHER_OK==(rc = sqlcipher3_overload_function(db, "offsets", 1))
119551    && SQLCIPHER_OK==(rc = sqlcipher3_overload_function(db, "matchinfo", 1))
119552    && SQLCIPHER_OK==(rc = sqlcipher3_overload_function(db, "matchinfo", 2))
119553    && SQLCIPHER_OK==(rc = sqlcipher3_overload_function(db, "optimize", 1))
119554   ){
119555     rc = sqlcipher3_create_module_v2(
119556         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
119557     );
119558     if( rc==SQLCIPHER_OK ){
119559       rc = sqlcipher3_create_module_v2(
119560           db, "fts4", &fts3Module, (void *)pHash, 0
119561       );
119562     }
119563     return rc;
119564   }
119565
119566   /* An error has occurred. Delete the hash table and return the error code. */
119567   assert( rc!=SQLCIPHER_OK );
119568   if( pHash ){
119569     sqlcipher3Fts3HashClear(pHash);
119570     sqlcipher3_free(pHash);
119571   }
119572   return rc;
119573 }
119574
119575 /*
119576 ** Allocate an Fts3MultiSegReader for each token in the expression headed
119577 ** by pExpr. 
119578 **
119579 ** An Fts3SegReader object is a cursor that can seek or scan a range of
119580 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
119581 ** Fts3SegReader objects internally to provide an interface to seek or scan
119582 ** within the union of all segments of a b-tree. Hence the name.
119583 **
119584 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
119585 ** segment b-tree (if the term is not a prefix or it is a prefix for which
119586 ** there exists prefix b-tree of the right length) then it may be traversed
119587 ** and merged incrementally. Otherwise, it has to be merged into an in-memory 
119588 ** doclist and then traversed.
119589 */
119590 static void fts3EvalAllocateReaders(
119591   Fts3Cursor *pCsr,               /* FTS cursor handle */
119592   Fts3Expr *pExpr,                /* Allocate readers for this expression */
119593   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
119594   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
119595   int *pRc                        /* IN/OUT: Error code */
119596 ){
119597   if( pExpr && SQLCIPHER_OK==*pRc ){
119598     if( pExpr->eType==FTSQUERY_PHRASE ){
119599       int i;
119600       int nToken = pExpr->pPhrase->nToken;
119601       *pnToken += nToken;
119602       for(i=0; i<nToken; i++){
119603         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
119604         int rc = fts3TermSegReaderCursor(pCsr, 
119605             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
119606         );
119607         if( rc!=SQLCIPHER_OK ){
119608           *pRc = rc;
119609           return;
119610         }
119611       }
119612       assert( pExpr->pPhrase->iDoclistToken==0 );
119613       pExpr->pPhrase->iDoclistToken = -1;
119614     }else{
119615       *pnOr += (pExpr->eType==FTSQUERY_OR);
119616       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
119617       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
119618     }
119619   }
119620 }
119621
119622 /*
119623 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
119624 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
119625 **
119626 ** This function assumes that pList points to a buffer allocated using
119627 ** sqlcipher3_malloc(). This function takes responsibility for eventually
119628 ** freeing the buffer.
119629 */
119630 static void fts3EvalPhraseMergeToken(
119631   Fts3Table *pTab,                /* FTS Table pointer */
119632   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
119633   int iToken,                     /* Token pList/nList corresponds to */
119634   char *pList,                    /* Pointer to doclist */
119635   int nList                       /* Number of bytes in pList */
119636 ){
119637   assert( iToken!=p->iDoclistToken );
119638
119639   if( pList==0 ){
119640     sqlcipher3_free(p->doclist.aAll);
119641     p->doclist.aAll = 0;
119642     p->doclist.nAll = 0;
119643   }
119644
119645   else if( p->iDoclistToken<0 ){
119646     p->doclist.aAll = pList;
119647     p->doclist.nAll = nList;
119648   }
119649
119650   else if( p->doclist.aAll==0 ){
119651     sqlcipher3_free(pList);
119652   }
119653
119654   else {
119655     char *pLeft;
119656     char *pRight;
119657     int nLeft;
119658     int nRight;
119659     int nDiff;
119660
119661     if( p->iDoclistToken<iToken ){
119662       pLeft = p->doclist.aAll;
119663       nLeft = p->doclist.nAll;
119664       pRight = pList;
119665       nRight = nList;
119666       nDiff = iToken - p->iDoclistToken;
119667     }else{
119668       pRight = p->doclist.aAll;
119669       nRight = p->doclist.nAll;
119670       pLeft = pList;
119671       nLeft = nList;
119672       nDiff = p->iDoclistToken - iToken;
119673     }
119674
119675     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
119676     sqlcipher3_free(pLeft);
119677     p->doclist.aAll = pRight;
119678     p->doclist.nAll = nRight;
119679   }
119680
119681   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
119682 }
119683
119684 /*
119685 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
119686 ** does not take deferred tokens into account.
119687 **
119688 ** SQLCIPHER_OK is returned if no error occurs, otherwise an SQLite error code.
119689 */
119690 static int fts3EvalPhraseLoad(
119691   Fts3Cursor *pCsr,               /* FTS Cursor handle */
119692   Fts3Phrase *p                   /* Phrase object */
119693 ){
119694   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
119695   int iToken;
119696   int rc = SQLCIPHER_OK;
119697
119698   for(iToken=0; rc==SQLCIPHER_OK && iToken<p->nToken; iToken++){
119699     Fts3PhraseToken *pToken = &p->aToken[iToken];
119700     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
119701
119702     if( pToken->pSegcsr ){
119703       int nThis = 0;
119704       char *pThis = 0;
119705       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
119706       if( rc==SQLCIPHER_OK ){
119707         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
119708       }
119709     }
119710     assert( pToken->pSegcsr==0 );
119711   }
119712
119713   return rc;
119714 }
119715
119716 /*
119717 ** This function is called on each phrase after the position lists for
119718 ** any deferred tokens have been loaded into memory. It updates the phrases
119719 ** current position list to include only those positions that are really
119720 ** instances of the phrase (after considering deferred tokens). If this
119721 ** means that the phrase does not appear in the current row, doclist.pList
119722 ** and doclist.nList are both zeroed.
119723 **
119724 ** SQLCIPHER_OK is returned if no error occurs, otherwise an SQLite error code.
119725 */
119726 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
119727   int iToken;                     /* Used to iterate through phrase tokens */
119728   char *aPoslist = 0;             /* Position list for deferred tokens */
119729   int nPoslist = 0;               /* Number of bytes in aPoslist */
119730   int iPrev = -1;                 /* Token number of previous deferred token */
119731
119732   assert( pPhrase->doclist.bFreeList==0 );
119733
119734   for(iToken=0; iToken<pPhrase->nToken; iToken++){
119735     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
119736     Fts3DeferredToken *pDeferred = pToken->pDeferred;
119737
119738     if( pDeferred ){
119739       char *pList;
119740       int nList;
119741       int rc = sqlcipher3Fts3DeferredTokenList(pDeferred, &pList, &nList);
119742       if( rc!=SQLCIPHER_OK ) return rc;
119743
119744       if( pList==0 ){
119745         sqlcipher3_free(aPoslist);
119746         pPhrase->doclist.pList = 0;
119747         pPhrase->doclist.nList = 0;
119748         return SQLCIPHER_OK;
119749
119750       }else if( aPoslist==0 ){
119751         aPoslist = pList;
119752         nPoslist = nList;
119753
119754       }else{
119755         char *aOut = pList;
119756         char *p1 = aPoslist;
119757         char *p2 = aOut;
119758
119759         assert( iPrev>=0 );
119760         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
119761         sqlcipher3_free(aPoslist);
119762         aPoslist = pList;
119763         nPoslist = aOut - aPoslist;
119764         if( nPoslist==0 ){
119765           sqlcipher3_free(aPoslist);
119766           pPhrase->doclist.pList = 0;
119767           pPhrase->doclist.nList = 0;
119768           return SQLCIPHER_OK;
119769         }
119770       }
119771       iPrev = iToken;
119772     }
119773   }
119774
119775   if( iPrev>=0 ){
119776     int nMaxUndeferred = pPhrase->iDoclistToken;
119777     if( nMaxUndeferred<0 ){
119778       pPhrase->doclist.pList = aPoslist;
119779       pPhrase->doclist.nList = nPoslist;
119780       pPhrase->doclist.iDocid = pCsr->iPrevId;
119781       pPhrase->doclist.bFreeList = 1;
119782     }else{
119783       int nDistance;
119784       char *p1;
119785       char *p2;
119786       char *aOut;
119787
119788       if( nMaxUndeferred>iPrev ){
119789         p1 = aPoslist;
119790         p2 = pPhrase->doclist.pList;
119791         nDistance = nMaxUndeferred - iPrev;
119792       }else{
119793         p1 = pPhrase->doclist.pList;
119794         p2 = aPoslist;
119795         nDistance = iPrev - nMaxUndeferred;
119796       }
119797
119798       aOut = (char *)sqlcipher3_malloc(nPoslist+8);
119799       if( !aOut ){
119800         sqlcipher3_free(aPoslist);
119801         return SQLCIPHER_NOMEM;
119802       }
119803       
119804       pPhrase->doclist.pList = aOut;
119805       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
119806         pPhrase->doclist.bFreeList = 1;
119807         pPhrase->doclist.nList = (aOut - pPhrase->doclist.pList);
119808       }else{
119809         sqlcipher3_free(aOut);
119810         pPhrase->doclist.pList = 0;
119811         pPhrase->doclist.nList = 0;
119812       }
119813       sqlcipher3_free(aPoslist);
119814     }
119815   }
119816
119817   return SQLCIPHER_OK;
119818 }
119819
119820 /*
119821 ** This function is called for each Fts3Phrase in a full-text query 
119822 ** expression to initialize the mechanism for returning rows. Once this
119823 ** function has been called successfully on an Fts3Phrase, it may be
119824 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
119825 **
119826 ** If parameter bOptOk is true, then the phrase may (or may not) use the
119827 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
119828 ** memory within this call.
119829 **
119830 ** SQLCIPHER_OK is returned if no error occurs, otherwise an SQLite error code.
119831 */
119832 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
119833   int rc;                         /* Error code */
119834   Fts3PhraseToken *pFirst = &p->aToken[0];
119835   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
119836
119837   if( pCsr->bDesc==pTab->bDescIdx 
119838    && bOptOk==1 
119839    && p->nToken==1 
119840    && pFirst->pSegcsr 
119841    && pFirst->pSegcsr->bLookup 
119842    && pFirst->bFirst==0
119843   ){
119844     /* Use the incremental approach. */
119845     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
119846     rc = sqlcipher3Fts3MsrIncrStart(
119847         pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
119848     p->bIncr = 1;
119849
119850   }else{
119851     /* Load the full doclist for the phrase into memory. */
119852     rc = fts3EvalPhraseLoad(pCsr, p);
119853     p->bIncr = 0;
119854   }
119855
119856   assert( rc!=SQLCIPHER_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
119857   return rc;
119858 }
119859
119860 /*
119861 ** This function is used to iterate backwards (from the end to start) 
119862 ** through doclists. It is used by this module to iterate through phrase
119863 ** doclists in reverse and by the fts3_write.c module to iterate through
119864 ** pending-terms lists when writing to databases with "order=desc".
119865 **
119866 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or 
119867 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
119868 ** function iterates from the end of the doclist to the beginning.
119869 */
119870 SQLCIPHER_PRIVATE void sqlcipher3Fts3DoclistPrev(
119871   int bDescIdx,                   /* True if the doclist is desc */
119872   char *aDoclist,                 /* Pointer to entire doclist */
119873   int nDoclist,                   /* Length of aDoclist in bytes */
119874   char **ppIter,                  /* IN/OUT: Iterator pointer */
119875   sqlcipher3_int64 *piDocid,         /* IN/OUT: Docid pointer */
119876   int *pnList,                    /* IN/OUT: List length pointer */
119877   u8 *pbEof                       /* OUT: End-of-file flag */
119878 ){
119879   char *p = *ppIter;
119880
119881   assert( nDoclist>0 );
119882   assert( *pbEof==0 );
119883   assert( p || *piDocid==0 );
119884   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
119885
119886   if( p==0 ){
119887     sqlcipher3_int64 iDocid = 0;
119888     char *pNext = 0;
119889     char *pDocid = aDoclist;
119890     char *pEnd = &aDoclist[nDoclist];
119891     int iMul = 1;
119892
119893     while( pDocid<pEnd ){
119894       sqlcipher3_int64 iDelta;
119895       pDocid += sqlcipher3Fts3GetVarint(pDocid, &iDelta);
119896       iDocid += (iMul * iDelta);
119897       pNext = pDocid;
119898       fts3PoslistCopy(0, &pDocid);
119899       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
119900       iMul = (bDescIdx ? -1 : 1);
119901     }
119902
119903     *pnList = pEnd - pNext;
119904     *ppIter = pNext;
119905     *piDocid = iDocid;
119906   }else{
119907     int iMul = (bDescIdx ? -1 : 1);
119908     sqlcipher3_int64 iDelta;
119909     fts3GetReverseVarint(&p, aDoclist, &iDelta);
119910     *piDocid -= (iMul * iDelta);
119911
119912     if( p==aDoclist ){
119913       *pbEof = 1;
119914     }else{
119915       char *pSave = p;
119916       fts3ReversePoslist(aDoclist, &p);
119917       *pnList = (pSave - p);
119918     }
119919     *ppIter = p;
119920   }
119921 }
119922
119923 /*
119924 ** Attempt to move the phrase iterator to point to the next matching docid. 
119925 ** If an error occurs, return an SQLite error code. Otherwise, return 
119926 ** SQLCIPHER_OK.
119927 **
119928 ** If there is no "next" entry and no error occurs, then *pbEof is set to
119929 ** 1 before returning. Otherwise, if no error occurs and the iterator is
119930 ** successfully advanced, *pbEof is set to 0.
119931 */
119932 static int fts3EvalPhraseNext(
119933   Fts3Cursor *pCsr,               /* FTS Cursor handle */
119934   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
119935   u8 *pbEof                       /* OUT: Set to 1 if EOF */
119936 ){
119937   int rc = SQLCIPHER_OK;
119938   Fts3Doclist *pDL = &p->doclist;
119939   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
119940
119941   if( p->bIncr ){
119942     assert( p->nToken==1 );
119943     assert( pDL->pNextDocid==0 );
119944     rc = sqlcipher3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
119945         &pDL->iDocid, &pDL->pList, &pDL->nList
119946     );
119947     if( rc==SQLCIPHER_OK && !pDL->pList ){
119948       *pbEof = 1;
119949     }
119950   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
119951     sqlcipher3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
119952         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
119953     );
119954     pDL->pList = pDL->pNextDocid;
119955   }else{
119956     char *pIter;                            /* Used to iterate through aAll */
119957     char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
119958     if( pDL->pNextDocid ){
119959       pIter = pDL->pNextDocid;
119960     }else{
119961       pIter = pDL->aAll;
119962     }
119963
119964     if( pIter>=pEnd ){
119965       /* We have already reached the end of this doclist. EOF. */
119966       *pbEof = 1;
119967     }else{
119968       sqlcipher3_int64 iDelta;
119969       pIter += sqlcipher3Fts3GetVarint(pIter, &iDelta);
119970       if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
119971         pDL->iDocid += iDelta;
119972       }else{
119973         pDL->iDocid -= iDelta;
119974       }
119975       pDL->pList = pIter;
119976       fts3PoslistCopy(0, &pIter);
119977       pDL->nList = (pIter - pDL->pList);
119978
119979       /* pIter now points just past the 0x00 that terminates the position-
119980       ** list for document pDL->iDocid. However, if this position-list was
119981       ** edited in place by fts3EvalNearTrim(), then pIter may not actually
119982       ** point to the start of the next docid value. The following line deals
119983       ** with this case by advancing pIter past the zero-padding added by
119984       ** fts3EvalNearTrim().  */
119985       while( pIter<pEnd && *pIter==0 ) pIter++;
119986
119987       pDL->pNextDocid = pIter;
119988       assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
119989       *pbEof = 0;
119990     }
119991   }
119992
119993   return rc;
119994 }
119995
119996 /*
119997 **
119998 ** If *pRc is not SQLCIPHER_OK when this function is called, it is a no-op.
119999 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
120000 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
120001 ** expressions for which all descendent tokens are deferred.
120002 **
120003 ** If parameter bOptOk is zero, then it is guaranteed that the
120004 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
120005 ** each phrase in the expression (subject to deferred token processing).
120006 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
120007 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
120008 **
120009 ** If an error occurs within this function, *pRc is set to an SQLite error
120010 ** code before returning.
120011 */
120012 static void fts3EvalStartReaders(
120013   Fts3Cursor *pCsr,               /* FTS Cursor handle */
120014   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
120015   int bOptOk,                     /* True to enable incremental loading */
120016   int *pRc                        /* IN/OUT: Error code */
120017 ){
120018   if( pExpr && SQLCIPHER_OK==*pRc ){
120019     if( pExpr->eType==FTSQUERY_PHRASE ){
120020       int i;
120021       int nToken = pExpr->pPhrase->nToken;
120022       for(i=0; i<nToken; i++){
120023         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
120024       }
120025       pExpr->bDeferred = (i==nToken);
120026       *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
120027     }else{
120028       fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
120029       fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
120030       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
120031     }
120032   }
120033 }
120034
120035 /*
120036 ** An array of the following structures is assembled as part of the process
120037 ** of selecting tokens to defer before the query starts executing (as part
120038 ** of the xFilter() method). There is one element in the array for each
120039 ** token in the FTS expression.
120040 **
120041 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
120042 ** to phrases that are connected only by AND and NEAR operators (not OR or
120043 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
120044 ** separately. The root of a tokens AND/NEAR cluster is stored in 
120045 ** Fts3TokenAndCost.pRoot.
120046 */
120047 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
120048 struct Fts3TokenAndCost {
120049   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
120050   int iToken;                     /* Position of token in phrase */
120051   Fts3PhraseToken *pToken;        /* The token itself */
120052   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
120053   int nOvfl;                      /* Number of overflow pages to load doclist */
120054   int iCol;                       /* The column the token must match */
120055 };
120056
120057 /*
120058 ** This function is used to populate an allocated Fts3TokenAndCost array.
120059 **
120060 ** If *pRc is not SQLCIPHER_OK when this function is called, it is a no-op.
120061 ** Otherwise, if an error occurs during execution, *pRc is set to an
120062 ** SQLite error code.
120063 */
120064 static void fts3EvalTokenCosts(
120065   Fts3Cursor *pCsr,               /* FTS Cursor handle */
120066   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
120067   Fts3Expr *pExpr,                /* Expression to consider */
120068   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
120069   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
120070   int *pRc                        /* IN/OUT: Error code */
120071 ){
120072   if( *pRc==SQLCIPHER_OK ){
120073     if( pExpr->eType==FTSQUERY_PHRASE ){
120074       Fts3Phrase *pPhrase = pExpr->pPhrase;
120075       int i;
120076       for(i=0; *pRc==SQLCIPHER_OK && i<pPhrase->nToken; i++){
120077         Fts3TokenAndCost *pTC = (*ppTC)++;
120078         pTC->pPhrase = pPhrase;
120079         pTC->iToken = i;
120080         pTC->pRoot = pRoot;
120081         pTC->pToken = &pPhrase->aToken[i];
120082         pTC->iCol = pPhrase->iColumn;
120083         *pRc = sqlcipher3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
120084       }
120085     }else if( pExpr->eType!=FTSQUERY_NOT ){
120086       assert( pExpr->eType==FTSQUERY_OR
120087            || pExpr->eType==FTSQUERY_AND
120088            || pExpr->eType==FTSQUERY_NEAR
120089       );
120090       assert( pExpr->pLeft && pExpr->pRight );
120091       if( pExpr->eType==FTSQUERY_OR ){
120092         pRoot = pExpr->pLeft;
120093         **ppOr = pRoot;
120094         (*ppOr)++;
120095       }
120096       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
120097       if( pExpr->eType==FTSQUERY_OR ){
120098         pRoot = pExpr->pRight;
120099         **ppOr = pRoot;
120100         (*ppOr)++;
120101       }
120102       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
120103     }
120104   }
120105 }
120106
120107 /*
120108 ** Determine the average document (row) size in pages. If successful,
120109 ** write this value to *pnPage and return SQLCIPHER_OK. Otherwise, return
120110 ** an SQLite error code.
120111 **
120112 ** The average document size in pages is calculated by first calculating 
120113 ** determining the average size in bytes, B. If B is less than the amount
120114 ** of data that will fit on a single leaf page of an intkey table in
120115 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
120116 ** the number of overflow pages consumed by a record B bytes in size.
120117 */
120118 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
120119   if( pCsr->nRowAvg==0 ){
120120     /* The average document size, which is required to calculate the cost
120121     ** of each doclist, has not yet been determined. Read the required 
120122     ** data from the %_stat table to calculate it.
120123     **
120124     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
120125     ** varints, where nCol is the number of columns in the FTS3 table.
120126     ** The first varint is the number of documents currently stored in
120127     ** the table. The following nCol varints contain the total amount of
120128     ** data stored in all rows of each column of the table, from left
120129     ** to right.
120130     */
120131     int rc;
120132     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
120133     sqlcipher3_stmt *pStmt;
120134     sqlcipher3_int64 nDoc = 0;
120135     sqlcipher3_int64 nByte = 0;
120136     const char *pEnd;
120137     const char *a;
120138
120139     rc = sqlcipher3Fts3SelectDoctotal(p, &pStmt);
120140     if( rc!=SQLCIPHER_OK ) return rc;
120141     a = sqlcipher3_column_blob(pStmt, 0);
120142     assert( a );
120143
120144     pEnd = &a[sqlcipher3_column_bytes(pStmt, 0)];
120145     a += sqlcipher3Fts3GetVarint(a, &nDoc);
120146     while( a<pEnd ){
120147       a += sqlcipher3Fts3GetVarint(a, &nByte);
120148     }
120149     if( nDoc==0 || nByte==0 ){
120150       sqlcipher3_reset(pStmt);
120151       return FTS_CORRUPT_VTAB;
120152     }
120153
120154     pCsr->nDoc = nDoc;
120155     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
120156     assert( pCsr->nRowAvg>0 ); 
120157     rc = sqlcipher3_reset(pStmt);
120158     if( rc!=SQLCIPHER_OK ) return rc;
120159   }
120160
120161   *pnPage = pCsr->nRowAvg;
120162   return SQLCIPHER_OK;
120163 }
120164
120165 /*
120166 ** This function is called to select the tokens (if any) that will be 
120167 ** deferred. The array aTC[] has already been populated when this is
120168 ** called.
120169 **
120170 ** This function is called once for each AND/NEAR cluster in the 
120171 ** expression. Each invocation determines which tokens to defer within
120172 ** the cluster with root node pRoot. See comments above the definition
120173 ** of struct Fts3TokenAndCost for more details.
120174 **
120175 ** If no error occurs, SQLCIPHER_OK is returned and sqlcipher3Fts3DeferToken()
120176 ** called on each token to defer. Otherwise, an SQLite error code is
120177 ** returned.
120178 */
120179 static int fts3EvalSelectDeferred(
120180   Fts3Cursor *pCsr,               /* FTS Cursor handle */
120181   Fts3Expr *pRoot,                /* Consider tokens with this root node */
120182   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
120183   int nTC                         /* Number of entries in aTC[] */
120184 ){
120185   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120186   int nDocSize = 0;               /* Number of pages per doc loaded */
120187   int rc = SQLCIPHER_OK;             /* Return code */
120188   int ii;                         /* Iterator variable for various purposes */
120189   int nOvfl = 0;                  /* Total overflow pages used by doclists */
120190   int nToken = 0;                 /* Total number of tokens in cluster */
120191
120192   int nMinEst = 0;                /* The minimum count for any phrase so far. */
120193   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
120194
120195   /* Tokens are never deferred for FTS tables created using the content=xxx
120196   ** option. The reason being that it is not guaranteed that the content
120197   ** table actually contains the same data as the index. To prevent this from
120198   ** causing any problems, the deferred token optimization is completely
120199   ** disabled for content=xxx tables. */
120200   if( pTab->zContentTbl ){
120201     return SQLCIPHER_OK;
120202   }
120203
120204   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
120205   ** associated with the tokens spill onto overflow pages, or if there is
120206   ** only 1 token, exit early. No tokens to defer in this case. */
120207   for(ii=0; ii<nTC; ii++){
120208     if( aTC[ii].pRoot==pRoot ){
120209       nOvfl += aTC[ii].nOvfl;
120210       nToken++;
120211     }
120212   }
120213   if( nOvfl==0 || nToken<2 ) return SQLCIPHER_OK;
120214
120215   /* Obtain the average docsize (in pages). */
120216   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
120217   assert( rc!=SQLCIPHER_OK || nDocSize>0 );
120218
120219
120220   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 
120221   ** of the number of overflow pages that will be loaded by the pager layer 
120222   ** to retrieve the entire doclist for the token from the full-text index.
120223   ** Load the doclists for tokens that are either:
120224   **
120225   **   a. The cheapest token in the entire query (i.e. the one visited by the
120226   **      first iteration of this loop), or
120227   **
120228   **   b. Part of a multi-token phrase.
120229   **
120230   ** After each token doclist is loaded, merge it with the others from the
120231   ** same phrase and count the number of documents that the merged doclist
120232   ** contains. Set variable "nMinEst" to the smallest number of documents in 
120233   ** any phrase doclist for which 1 or more token doclists have been loaded.
120234   ** Let nOther be the number of other phrases for which it is certain that
120235   ** one or more tokens will not be deferred.
120236   **
120237   ** Then, for each token, defer it if loading the doclist would result in
120238   ** loading N or more overflow pages into memory, where N is computed as:
120239   **
120240   **    (nMinEst + 4^nOther - 1) / (4^nOther)
120241   */
120242   for(ii=0; ii<nToken && rc==SQLCIPHER_OK; ii++){
120243     int iTC;                      /* Used to iterate through aTC[] array. */
120244     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
120245
120246     /* Set pTC to point to the cheapest remaining token. */
120247     for(iTC=0; iTC<nTC; iTC++){
120248       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot 
120249        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) 
120250       ){
120251         pTC = &aTC[iTC];
120252       }
120253     }
120254     assert( pTC );
120255
120256     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
120257       /* The number of overflow pages to load for this (and therefore all
120258       ** subsequent) tokens is greater than the estimated number of pages 
120259       ** that will be loaded if all subsequent tokens are deferred.
120260       */
120261       Fts3PhraseToken *pToken = pTC->pToken;
120262       rc = sqlcipher3Fts3DeferToken(pCsr, pToken, pTC->iCol);
120263       fts3SegReaderCursorFree(pToken->pSegcsr);
120264       pToken->pSegcsr = 0;
120265     }else{
120266       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
120267       ** for-loop. Except, limit the value to 2^24 to prevent it from 
120268       ** overflowing the 32-bit integer it is stored in. */
120269       if( ii<12 ) nLoad4 = nLoad4*4;
120270
120271       if( ii==0 || pTC->pPhrase->nToken>1 ){
120272         /* Either this is the cheapest token in the entire query, or it is
120273         ** part of a multi-token phrase. Either way, the entire doclist will
120274         ** (eventually) be loaded into memory. It may as well be now. */
120275         Fts3PhraseToken *pToken = pTC->pToken;
120276         int nList = 0;
120277         char *pList = 0;
120278         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
120279         assert( rc==SQLCIPHER_OK || pList==0 );
120280         if( rc==SQLCIPHER_OK ){
120281           int nCount;
120282           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
120283           nCount = fts3DoclistCountDocids(
120284               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
120285           );
120286           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
120287         }
120288       }
120289     }
120290     pTC->pToken = 0;
120291   }
120292
120293   return rc;
120294 }
120295
120296 /*
120297 ** This function is called from within the xFilter method. It initializes
120298 ** the full-text query currently stored in pCsr->pExpr. To iterate through
120299 ** the results of a query, the caller does:
120300 **
120301 **    fts3EvalStart(pCsr);
120302 **    while( 1 ){
120303 **      fts3EvalNext(pCsr);
120304 **      if( pCsr->bEof ) break;
120305 **      ... return row pCsr->iPrevId to the caller ...
120306 **    }
120307 */
120308 static int fts3EvalStart(Fts3Cursor *pCsr){
120309   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120310   int rc = SQLCIPHER_OK;
120311   int nToken = 0;
120312   int nOr = 0;
120313
120314   /* Allocate a MultiSegReader for each token in the expression. */
120315   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
120316
120317   /* Determine which, if any, tokens in the expression should be deferred. */
120318   if( rc==SQLCIPHER_OK && nToken>1 && pTab->bHasStat ){
120319     Fts3TokenAndCost *aTC;
120320     Fts3Expr **apOr;
120321     aTC = (Fts3TokenAndCost *)sqlcipher3_malloc(
120322         sizeof(Fts3TokenAndCost) * nToken
120323       + sizeof(Fts3Expr *) * nOr * 2
120324     );
120325     apOr = (Fts3Expr **)&aTC[nToken];
120326
120327     if( !aTC ){
120328       rc = SQLCIPHER_NOMEM;
120329     }else{
120330       int ii;
120331       Fts3TokenAndCost *pTC = aTC;
120332       Fts3Expr **ppOr = apOr;
120333
120334       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
120335       nToken = pTC-aTC;
120336       nOr = ppOr-apOr;
120337
120338       if( rc==SQLCIPHER_OK ){
120339         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
120340         for(ii=0; rc==SQLCIPHER_OK && ii<nOr; ii++){
120341           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
120342         }
120343       }
120344
120345       sqlcipher3_free(aTC);
120346     }
120347   }
120348
120349   fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
120350   return rc;
120351 }
120352
120353 /*
120354 ** Invalidate the current position list for phrase pPhrase.
120355 */
120356 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
120357   if( pPhrase->doclist.bFreeList ){
120358     sqlcipher3_free(pPhrase->doclist.pList);
120359   }
120360   pPhrase->doclist.pList = 0;
120361   pPhrase->doclist.nList = 0;
120362   pPhrase->doclist.bFreeList = 0;
120363 }
120364
120365 /*
120366 ** This function is called to edit the position list associated with
120367 ** the phrase object passed as the fifth argument according to a NEAR
120368 ** condition. For example:
120369 **
120370 **     abc NEAR/5 "def ghi"
120371 **
120372 ** Parameter nNear is passed the NEAR distance of the expression (5 in
120373 ** the example above). When this function is called, *paPoslist points to
120374 ** the position list, and *pnToken is the number of phrase tokens in, the
120375 ** phrase on the other side of the NEAR operator to pPhrase. For example,
120376 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
120377 ** the position list associated with phrase "abc".
120378 **
120379 ** All positions in the pPhrase position list that are not sufficiently
120380 ** close to a position in the *paPoslist position list are removed. If this
120381 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
120382 **
120383 ** Before returning, *paPoslist is set to point to the position lsit 
120384 ** associated with pPhrase. And *pnToken is set to the number of tokens in
120385 ** pPhrase.
120386 */
120387 static int fts3EvalNearTrim(
120388   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
120389   char *aTmp,                     /* Temporary space to use */
120390   char **paPoslist,               /* IN/OUT: Position list */
120391   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
120392   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
120393 ){
120394   int nParam1 = nNear + pPhrase->nToken;
120395   int nParam2 = nNear + *pnToken;
120396   int nNew;
120397   char *p2; 
120398   char *pOut; 
120399   int res;
120400
120401   assert( pPhrase->doclist.pList );
120402
120403   p2 = pOut = pPhrase->doclist.pList;
120404   res = fts3PoslistNearMerge(
120405     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
120406   );
120407   if( res ){
120408     nNew = (pOut - pPhrase->doclist.pList) - 1;
120409     assert( pPhrase->doclist.pList[nNew]=='\0' );
120410     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
120411     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
120412     pPhrase->doclist.nList = nNew;
120413     *paPoslist = pPhrase->doclist.pList;
120414     *pnToken = pPhrase->nToken;
120415   }
120416
120417   return res;
120418 }
120419
120420 /*
120421 ** This function is a no-op if *pRc is other than SQLCIPHER_OK when it is called.
120422 ** Otherwise, it advances the expression passed as the second argument to
120423 ** point to the next matching row in the database. Expressions iterate through
120424 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
120425 ** or descending if it is non-zero.
120426 **
120427 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
120428 ** successful, the following variables in pExpr are set:
120429 **
120430 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
120431 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
120432 **
120433 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
120434 ** at EOF, then the following variables are populated with the position list
120435 ** for the phrase for the visited row:
120436 **
120437 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
120438 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
120439 **
120440 ** It says above that this function advances the expression to the next
120441 ** matching row. This is usually true, but there are the following exceptions:
120442 **
120443 **   1. Deferred tokens are not taken into account. If a phrase consists
120444 **      entirely of deferred tokens, it is assumed to match every row in
120445 **      the db. In this case the position-list is not populated at all. 
120446 **
120447 **      Or, if a phrase contains one or more deferred tokens and one or
120448 **      more non-deferred tokens, then the expression is advanced to the 
120449 **      next possible match, considering only non-deferred tokens. In other
120450 **      words, if the phrase is "A B C", and "B" is deferred, the expression
120451 **      is advanced to the next row that contains an instance of "A * C", 
120452 **      where "*" may match any single token. The position list in this case
120453 **      is populated as for "A * C" before returning.
120454 **
120455 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is 
120456 **      advanced to point to the next row that matches "x AND y".
120457 ** 
120458 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
120459 ** really a match, taking into account deferred tokens and NEAR operators.
120460 */
120461 static void fts3EvalNextRow(
120462   Fts3Cursor *pCsr,               /* FTS Cursor handle */
120463   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
120464   int *pRc                        /* IN/OUT: Error code */
120465 ){
120466   if( *pRc==SQLCIPHER_OK ){
120467     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
120468     assert( pExpr->bEof==0 );
120469     pExpr->bStart = 1;
120470
120471     switch( pExpr->eType ){
120472       case FTSQUERY_NEAR:
120473       case FTSQUERY_AND: {
120474         Fts3Expr *pLeft = pExpr->pLeft;
120475         Fts3Expr *pRight = pExpr->pRight;
120476         assert( !pLeft->bDeferred || !pRight->bDeferred );
120477
120478         if( pLeft->bDeferred ){
120479           /* LHS is entirely deferred. So we assume it matches every row.
120480           ** Advance the RHS iterator to find the next row visited. */
120481           fts3EvalNextRow(pCsr, pRight, pRc);
120482           pExpr->iDocid = pRight->iDocid;
120483           pExpr->bEof = pRight->bEof;
120484         }else if( pRight->bDeferred ){
120485           /* RHS is entirely deferred. So we assume it matches every row.
120486           ** Advance the LHS iterator to find the next row visited. */
120487           fts3EvalNextRow(pCsr, pLeft, pRc);
120488           pExpr->iDocid = pLeft->iDocid;
120489           pExpr->bEof = pLeft->bEof;
120490         }else{
120491           /* Neither the RHS or LHS are deferred. */
120492           fts3EvalNextRow(pCsr, pLeft, pRc);
120493           fts3EvalNextRow(pCsr, pRight, pRc);
120494           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLCIPHER_OK ){
120495             sqlcipher3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
120496             if( iDiff==0 ) break;
120497             if( iDiff<0 ){
120498               fts3EvalNextRow(pCsr, pLeft, pRc);
120499             }else{
120500               fts3EvalNextRow(pCsr, pRight, pRc);
120501             }
120502           }
120503           pExpr->iDocid = pLeft->iDocid;
120504           pExpr->bEof = (pLeft->bEof || pRight->bEof);
120505         }
120506         break;
120507       }
120508   
120509       case FTSQUERY_OR: {
120510         Fts3Expr *pLeft = pExpr->pLeft;
120511         Fts3Expr *pRight = pExpr->pRight;
120512         sqlcipher3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
120513
120514         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
120515         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
120516
120517         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
120518           fts3EvalNextRow(pCsr, pLeft, pRc);
120519         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
120520           fts3EvalNextRow(pCsr, pRight, pRc);
120521         }else{
120522           fts3EvalNextRow(pCsr, pLeft, pRc);
120523           fts3EvalNextRow(pCsr, pRight, pRc);
120524         }
120525
120526         pExpr->bEof = (pLeft->bEof && pRight->bEof);
120527         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
120528         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
120529           pExpr->iDocid = pLeft->iDocid;
120530         }else{
120531           pExpr->iDocid = pRight->iDocid;
120532         }
120533
120534         break;
120535       }
120536
120537       case FTSQUERY_NOT: {
120538         Fts3Expr *pLeft = pExpr->pLeft;
120539         Fts3Expr *pRight = pExpr->pRight;
120540
120541         if( pRight->bStart==0 ){
120542           fts3EvalNextRow(pCsr, pRight, pRc);
120543           assert( *pRc!=SQLCIPHER_OK || pRight->bStart );
120544         }
120545
120546         fts3EvalNextRow(pCsr, pLeft, pRc);
120547         if( pLeft->bEof==0 ){
120548           while( !*pRc 
120549               && !pRight->bEof 
120550               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
120551           ){
120552             fts3EvalNextRow(pCsr, pRight, pRc);
120553           }
120554         }
120555         pExpr->iDocid = pLeft->iDocid;
120556         pExpr->bEof = pLeft->bEof;
120557         break;
120558       }
120559
120560       default: {
120561         Fts3Phrase *pPhrase = pExpr->pPhrase;
120562         fts3EvalInvalidatePoslist(pPhrase);
120563         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
120564         pExpr->iDocid = pPhrase->doclist.iDocid;
120565         break;
120566       }
120567     }
120568   }
120569 }
120570
120571 /*
120572 ** If *pRc is not SQLCIPHER_OK, or if pExpr is not the root node of a NEAR
120573 ** cluster, then this function returns 1 immediately.
120574 **
120575 ** Otherwise, it checks if the current row really does match the NEAR 
120576 ** expression, using the data currently stored in the position lists 
120577 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 
120578 **
120579 ** If the current row is a match, the position list associated with each
120580 ** phrase in the NEAR expression is edited in place to contain only those
120581 ** phrase instances sufficiently close to their peers to satisfy all NEAR
120582 ** constraints. In this case it returns 1. If the NEAR expression does not 
120583 ** match the current row, 0 is returned. The position lists may or may not
120584 ** be edited if 0 is returned.
120585 */
120586 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
120587   int res = 1;
120588
120589   /* The following block runs if pExpr is the root of a NEAR query.
120590   ** For example, the query:
120591   **
120592   **         "w" NEAR "x" NEAR "y" NEAR "z"
120593   **
120594   ** which is represented in tree form as:
120595   **
120596   **                               |
120597   **                          +--NEAR--+      <-- root of NEAR query
120598   **                          |        |
120599   **                     +--NEAR--+   "z"
120600   **                     |        |
120601   **                +--NEAR--+   "y"
120602   **                |        |
120603   **               "w"      "x"
120604   **
120605   ** The right-hand child of a NEAR node is always a phrase. The 
120606   ** left-hand child may be either a phrase or a NEAR node. There are
120607   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
120608   */
120609   if( *pRc==SQLCIPHER_OK 
120610    && pExpr->eType==FTSQUERY_NEAR 
120611    && pExpr->bEof==0
120612    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
120613   ){
120614     Fts3Expr *p; 
120615     int nTmp = 0;                 /* Bytes of temp space */
120616     char *aTmp;                   /* Temp space for PoslistNearMerge() */
120617
120618     /* Allocate temporary working space. */
120619     for(p=pExpr; p->pLeft; p=p->pLeft){
120620       nTmp += p->pRight->pPhrase->doclist.nList;
120621     }
120622     nTmp += p->pPhrase->doclist.nList;
120623     aTmp = sqlcipher3_malloc(nTmp*2);
120624     if( !aTmp ){
120625       *pRc = SQLCIPHER_NOMEM;
120626       res = 0;
120627     }else{
120628       char *aPoslist = p->pPhrase->doclist.pList;
120629       int nToken = p->pPhrase->nToken;
120630
120631       for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
120632         Fts3Phrase *pPhrase = p->pRight->pPhrase;
120633         int nNear = p->nNear;
120634         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
120635       }
120636   
120637       aPoslist = pExpr->pRight->pPhrase->doclist.pList;
120638       nToken = pExpr->pRight->pPhrase->nToken;
120639       for(p=pExpr->pLeft; p && res; p=p->pLeft){
120640         int nNear;
120641         Fts3Phrase *pPhrase;
120642         assert( p->pParent && p->pParent->pLeft==p );
120643         nNear = p->pParent->nNear;
120644         pPhrase = (
120645             p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
120646         );
120647         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
120648       }
120649     }
120650
120651     sqlcipher3_free(aTmp);
120652   }
120653
120654   return res;
120655 }
120656
120657 /*
120658 ** This function is a helper function for fts3EvalTestDeferredAndNear().
120659 ** Assuming no error occurs or has occurred, It returns non-zero if the
120660 ** expression passed as the second argument matches the row that pCsr 
120661 ** currently points to, or zero if it does not.
120662 **
120663 ** If *pRc is not SQLCIPHER_OK when this function is called, it is a no-op.
120664 ** If an error occurs during execution of this function, *pRc is set to 
120665 ** the appropriate SQLite error code. In this case the returned value is 
120666 ** undefined.
120667 */
120668 static int fts3EvalTestExpr(
120669   Fts3Cursor *pCsr,               /* FTS cursor handle */
120670   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
120671   int *pRc                        /* IN/OUT: Error code */
120672 ){
120673   int bHit = 1;                   /* Return value */
120674   if( *pRc==SQLCIPHER_OK ){
120675     switch( pExpr->eType ){
120676       case FTSQUERY_NEAR:
120677       case FTSQUERY_AND:
120678         bHit = (
120679             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
120680          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
120681          && fts3EvalNearTest(pExpr, pRc)
120682         );
120683
120684         /* If the NEAR expression does not match any rows, zero the doclist for 
120685         ** all phrases involved in the NEAR. This is because the snippet(),
120686         ** offsets() and matchinfo() functions are not supposed to recognize 
120687         ** any instances of phrases that are part of unmatched NEAR queries. 
120688         ** For example if this expression:
120689         **
120690         **    ... MATCH 'a OR (b NEAR c)'
120691         **
120692         ** is matched against a row containing:
120693         **
120694         **        'a b d e'
120695         **
120696         ** then any snippet() should ony highlight the "a" term, not the "b"
120697         ** (as "b" is part of a non-matching NEAR clause).
120698         */
120699         if( bHit==0 
120700          && pExpr->eType==FTSQUERY_NEAR 
120701          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
120702         ){
120703           Fts3Expr *p;
120704           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
120705             if( p->pRight->iDocid==pCsr->iPrevId ){
120706               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
120707             }
120708           }
120709           if( p->iDocid==pCsr->iPrevId ){
120710             fts3EvalInvalidatePoslist(p->pPhrase);
120711           }
120712         }
120713
120714         break;
120715
120716       case FTSQUERY_OR: {
120717         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
120718         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
120719         bHit = bHit1 || bHit2;
120720         break;
120721       }
120722
120723       case FTSQUERY_NOT:
120724         bHit = (
120725             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
120726          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
120727         );
120728         break;
120729
120730       default: {
120731         if( pCsr->pDeferred 
120732          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
120733         ){
120734           Fts3Phrase *pPhrase = pExpr->pPhrase;
120735           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
120736           if( pExpr->bDeferred ){
120737             fts3EvalInvalidatePoslist(pPhrase);
120738           }
120739           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
120740           bHit = (pPhrase->doclist.pList!=0);
120741           pExpr->iDocid = pCsr->iPrevId;
120742         }else{
120743           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
120744         }
120745         break;
120746       }
120747     }
120748   }
120749   return bHit;
120750 }
120751
120752 /*
120753 ** This function is called as the second part of each xNext operation when
120754 ** iterating through the results of a full-text query. At this point the
120755 ** cursor points to a row that matches the query expression, with the
120756 ** following caveats:
120757 **
120758 **   * Up until this point, "NEAR" operators in the expression have been
120759 **     treated as "AND".
120760 **
120761 **   * Deferred tokens have not yet been considered.
120762 **
120763 ** If *pRc is not SQLCIPHER_OK when this function is called, it immediately
120764 ** returns 0. Otherwise, it tests whether or not after considering NEAR
120765 ** operators and deferred tokens the current row is still a match for the
120766 ** expression. It returns 1 if both of the following are true:
120767 **
120768 **   1. *pRc is SQLCIPHER_OK when this function returns, and
120769 **
120770 **   2. After scanning the current FTS table row for the deferred tokens,
120771 **      it is determined that the row does *not* match the query.
120772 **
120773 ** Or, if no error occurs and it seems the current row does match the FTS
120774 ** query, return 0.
120775 */
120776 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
120777   int rc = *pRc;
120778   int bMiss = 0;
120779   if( rc==SQLCIPHER_OK ){
120780
120781     /* If there are one or more deferred tokens, load the current row into
120782     ** memory and scan it to determine the position list for each deferred
120783     ** token. Then, see if this row is really a match, considering deferred
120784     ** tokens and NEAR operators (neither of which were taken into account
120785     ** earlier, by fts3EvalNextRow()). 
120786     */
120787     if( pCsr->pDeferred ){
120788       rc = fts3CursorSeek(0, pCsr);
120789       if( rc==SQLCIPHER_OK ){
120790         rc = sqlcipher3Fts3CacheDeferredDoclists(pCsr);
120791       }
120792     }
120793     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
120794
120795     /* Free the position-lists accumulated for each deferred token above. */
120796     sqlcipher3Fts3FreeDeferredDoclists(pCsr);
120797     *pRc = rc;
120798   }
120799   return (rc==SQLCIPHER_OK && bMiss);
120800 }
120801
120802 /*
120803 ** Advance to the next document that matches the FTS expression in
120804 ** Fts3Cursor.pExpr.
120805 */
120806 static int fts3EvalNext(Fts3Cursor *pCsr){
120807   int rc = SQLCIPHER_OK;             /* Return Code */
120808   Fts3Expr *pExpr = pCsr->pExpr;
120809   assert( pCsr->isEof==0 );
120810   if( pExpr==0 ){
120811     pCsr->isEof = 1;
120812   }else{
120813     do {
120814       if( pCsr->isRequireSeek==0 ){
120815         sqlcipher3_reset(pCsr->pStmt);
120816       }
120817       assert( sqlcipher3_data_count(pCsr->pStmt)==0 );
120818       fts3EvalNextRow(pCsr, pExpr, &rc);
120819       pCsr->isEof = pExpr->bEof;
120820       pCsr->isRequireSeek = 1;
120821       pCsr->isMatchinfoNeeded = 1;
120822       pCsr->iPrevId = pExpr->iDocid;
120823     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
120824   }
120825   return rc;
120826 }
120827
120828 /*
120829 ** Restart interation for expression pExpr so that the next call to
120830 ** fts3EvalNext() visits the first row. Do not allow incremental 
120831 ** loading or merging of phrase doclists for this iteration.
120832 **
120833 ** If *pRc is other than SQLCIPHER_OK when this function is called, it is
120834 ** a no-op. If an error occurs within this function, *pRc is set to an
120835 ** SQLite error code before returning.
120836 */
120837 static void fts3EvalRestart(
120838   Fts3Cursor *pCsr,
120839   Fts3Expr *pExpr,
120840   int *pRc
120841 ){
120842   if( pExpr && *pRc==SQLCIPHER_OK ){
120843     Fts3Phrase *pPhrase = pExpr->pPhrase;
120844
120845     if( pPhrase ){
120846       fts3EvalInvalidatePoslist(pPhrase);
120847       if( pPhrase->bIncr ){
120848         assert( pPhrase->nToken==1 );
120849         assert( pPhrase->aToken[0].pSegcsr );
120850         sqlcipher3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
120851         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
120852       }
120853
120854       pPhrase->doclist.pNextDocid = 0;
120855       pPhrase->doclist.iDocid = 0;
120856     }
120857
120858     pExpr->iDocid = 0;
120859     pExpr->bEof = 0;
120860     pExpr->bStart = 0;
120861
120862     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
120863     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
120864   }
120865 }
120866
120867 /*
120868 ** After allocating the Fts3Expr.aMI[] array for each phrase in the 
120869 ** expression rooted at pExpr, the cursor iterates through all rows matched
120870 ** by pExpr, calling this function for each row. This function increments
120871 ** the values in Fts3Expr.aMI[] according to the position-list currently
120872 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
120873 ** expression nodes.
120874 */
120875 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
120876   if( pExpr ){
120877     Fts3Phrase *pPhrase = pExpr->pPhrase;
120878     if( pPhrase && pPhrase->doclist.pList ){
120879       int iCol = 0;
120880       char *p = pPhrase->doclist.pList;
120881
120882       assert( *p );
120883       while( 1 ){
120884         u8 c = 0;
120885         int iCnt = 0;
120886         while( 0xFE & (*p | c) ){
120887           if( (c&0x80)==0 ) iCnt++;
120888           c = *p++ & 0x80;
120889         }
120890
120891         /* aMI[iCol*3 + 1] = Number of occurrences
120892         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
120893         */
120894         pExpr->aMI[iCol*3 + 1] += iCnt;
120895         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
120896         if( *p==0x00 ) break;
120897         p++;
120898         p += sqlcipher3Fts3GetVarint32(p, &iCol);
120899       }
120900     }
120901
120902     fts3EvalUpdateCounts(pExpr->pLeft);
120903     fts3EvalUpdateCounts(pExpr->pRight);
120904   }
120905 }
120906
120907 /*
120908 ** Expression pExpr must be of type FTSQUERY_PHRASE.
120909 **
120910 ** If it is not already allocated and populated, this function allocates and
120911 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
120912 ** of a NEAR expression, then it also allocates and populates the same array
120913 ** for all other phrases that are part of the NEAR expression.
120914 **
120915 ** SQLCIPHER_OK is returned if the aMI[] array is successfully allocated and
120916 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
120917 */
120918 static int fts3EvalGatherStats(
120919   Fts3Cursor *pCsr,               /* Cursor object */
120920   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
120921 ){
120922   int rc = SQLCIPHER_OK;             /* Return code */
120923
120924   assert( pExpr->eType==FTSQUERY_PHRASE );
120925   if( pExpr->aMI==0 ){
120926     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120927     Fts3Expr *pRoot;                /* Root of NEAR expression */
120928     Fts3Expr *p;                    /* Iterator used for several purposes */
120929
120930     sqlcipher3_int64 iPrevId = pCsr->iPrevId;
120931     sqlcipher3_int64 iDocid;
120932     u8 bEof;
120933
120934     /* Find the root of the NEAR expression */
120935     pRoot = pExpr;
120936     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
120937       pRoot = pRoot->pParent;
120938     }
120939     iDocid = pRoot->iDocid;
120940     bEof = pRoot->bEof;
120941     assert( pRoot->bStart );
120942
120943     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
120944     for(p=pRoot; p; p=p->pLeft){
120945       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
120946       assert( pE->aMI==0 );
120947       pE->aMI = (u32 *)sqlcipher3_malloc(pTab->nColumn * 3 * sizeof(u32));
120948       if( !pE->aMI ) return SQLCIPHER_NOMEM;
120949       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
120950     }
120951
120952     fts3EvalRestart(pCsr, pRoot, &rc);
120953
120954     while( pCsr->isEof==0 && rc==SQLCIPHER_OK ){
120955
120956       do {
120957         /* Ensure the %_content statement is reset. */
120958         if( pCsr->isRequireSeek==0 ) sqlcipher3_reset(pCsr->pStmt);
120959         assert( sqlcipher3_data_count(pCsr->pStmt)==0 );
120960
120961         /* Advance to the next document */
120962         fts3EvalNextRow(pCsr, pRoot, &rc);
120963         pCsr->isEof = pRoot->bEof;
120964         pCsr->isRequireSeek = 1;
120965         pCsr->isMatchinfoNeeded = 1;
120966         pCsr->iPrevId = pRoot->iDocid;
120967       }while( pCsr->isEof==0 
120968            && pRoot->eType==FTSQUERY_NEAR 
120969            && fts3EvalTestDeferredAndNear(pCsr, &rc) 
120970       );
120971
120972       if( rc==SQLCIPHER_OK && pCsr->isEof==0 ){
120973         fts3EvalUpdateCounts(pRoot);
120974       }
120975     }
120976
120977     pCsr->isEof = 0;
120978     pCsr->iPrevId = iPrevId;
120979
120980     if( bEof ){
120981       pRoot->bEof = bEof;
120982     }else{
120983       /* Caution: pRoot may iterate through docids in ascending or descending
120984       ** order. For this reason, even though it seems more defensive, the 
120985       ** do loop can not be written:
120986       **
120987       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLCIPHER_OK );
120988       */
120989       fts3EvalRestart(pCsr, pRoot, &rc);
120990       do {
120991         fts3EvalNextRow(pCsr, pRoot, &rc);
120992         assert( pRoot->bEof==0 );
120993       }while( pRoot->iDocid!=iDocid && rc==SQLCIPHER_OK );
120994       fts3EvalTestDeferredAndNear(pCsr, &rc);
120995     }
120996   }
120997   return rc;
120998 }
120999
121000 /*
121001 ** This function is used by the matchinfo() module to query a phrase 
121002 ** expression node for the following information:
121003 **
121004 **   1. The total number of occurrences of the phrase in each column of 
121005 **      the FTS table (considering all rows), and
121006 **
121007 **   2. For each column, the number of rows in the table for which the
121008 **      column contains at least one instance of the phrase.
121009 **
121010 ** If no error occurs, SQLCIPHER_OK is returned and the values for each column
121011 ** written into the array aiOut as follows:
121012 **
121013 **   aiOut[iCol*3 + 1] = Number of occurrences
121014 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
121015 **
121016 ** Caveats:
121017 **
121018 **   * If a phrase consists entirely of deferred tokens, then all output 
121019 **     values are set to the number of documents in the table. In other
121020 **     words we assume that very common tokens occur exactly once in each 
121021 **     column of each row of the table.
121022 **
121023 **   * If a phrase contains some deferred tokens (and some non-deferred 
121024 **     tokens), count the potential occurrence identified by considering
121025 **     the non-deferred tokens instead of actual phrase occurrences.
121026 **
121027 **   * If the phrase is part of a NEAR expression, then only phrase instances
121028 **     that meet the NEAR constraint are included in the counts.
121029 */
121030 SQLCIPHER_PRIVATE int sqlcipher3Fts3EvalPhraseStats(
121031   Fts3Cursor *pCsr,               /* FTS cursor handle */
121032   Fts3Expr *pExpr,                /* Phrase expression */
121033   u32 *aiOut                      /* Array to write results into (see above) */
121034 ){
121035   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121036   int rc = SQLCIPHER_OK;
121037   int iCol;
121038
121039   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
121040     assert( pCsr->nDoc>0 );
121041     for(iCol=0; iCol<pTab->nColumn; iCol++){
121042       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
121043       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
121044     }
121045   }else{
121046     rc = fts3EvalGatherStats(pCsr, pExpr);
121047     if( rc==SQLCIPHER_OK ){
121048       assert( pExpr->aMI );
121049       for(iCol=0; iCol<pTab->nColumn; iCol++){
121050         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
121051         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
121052       }
121053     }
121054   }
121055
121056   return rc;
121057 }
121058
121059 /*
121060 ** The expression pExpr passed as the second argument to this function
121061 ** must be of type FTSQUERY_PHRASE. 
121062 **
121063 ** The returned value is either NULL or a pointer to a buffer containing
121064 ** a position-list indicating the occurrences of the phrase in column iCol
121065 ** of the current row. 
121066 **
121067 ** More specifically, the returned buffer contains 1 varint for each 
121068 ** occurence of the phrase in the column, stored using the normal (delta+2) 
121069 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
121070 ** if the requested column contains "a b X c d X X" and the position-list
121071 ** for 'X' is requested, the buffer returned may contain:
121072 **
121073 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
121074 **
121075 ** This function works regardless of whether or not the phrase is deferred,
121076 ** incremental, or neither.
121077 */
121078 SQLCIPHER_PRIVATE char *sqlcipher3Fts3EvalPhrasePoslist(
121079   Fts3Cursor *pCsr,               /* FTS3 cursor object */
121080   Fts3Expr *pExpr,                /* Phrase to return doclist for */
121081   int iCol                        /* Column to return position list for */
121082 ){
121083   Fts3Phrase *pPhrase = pExpr->pPhrase;
121084   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121085   char *pIter = pPhrase->doclist.pList;
121086   int iThis;
121087
121088   assert( iCol>=0 && iCol<pTab->nColumn );
121089   if( !pIter 
121090    || pExpr->bEof 
121091    || pExpr->iDocid!=pCsr->iPrevId
121092    || (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) 
121093   ){
121094     return 0;
121095   }
121096
121097   assert( pPhrase->doclist.nList>0 );
121098   if( *pIter==0x01 ){
121099     pIter++;
121100     pIter += sqlcipher3Fts3GetVarint32(pIter, &iThis);
121101   }else{
121102     iThis = 0;
121103   }
121104   while( iThis<iCol ){
121105     fts3ColumnlistCopy(0, &pIter);
121106     if( *pIter==0x00 ) return 0;
121107     pIter++;
121108     pIter += sqlcipher3Fts3GetVarint32(pIter, &iThis);
121109   }
121110
121111   return ((iCol==iThis)?pIter:0);
121112 }
121113
121114 /*
121115 ** Free all components of the Fts3Phrase structure that were allocated by
121116 ** the eval module. Specifically, this means to free:
121117 **
121118 **   * the contents of pPhrase->doclist, and
121119 **   * any Fts3MultiSegReader objects held by phrase tokens.
121120 */
121121 SQLCIPHER_PRIVATE void sqlcipher3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
121122   if( pPhrase ){
121123     int i;
121124     sqlcipher3_free(pPhrase->doclist.aAll);
121125     fts3EvalInvalidatePoslist(pPhrase);
121126     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
121127     for(i=0; i<pPhrase->nToken; i++){
121128       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
121129       pPhrase->aToken[i].pSegcsr = 0;
121130     }
121131   }
121132 }
121133
121134 /*
121135 ** Return SQLCIPHER_CORRUPT_VTAB.
121136 */
121137 #ifdef SQLCIPHER_DEBUG
121138 SQLCIPHER_PRIVATE int sqlcipher3Fts3Corrupt(){
121139   return SQLCIPHER_CORRUPT_VTAB;
121140 }
121141 #endif
121142
121143 #if !SQLCIPHER_CORE
121144 /*
121145 ** Initialize API pointer table, if required.
121146 */
121147 SQLCIPHER_API int sqlcipher3_extension_init(
121148   sqlcipher3 *db, 
121149   char **pzErrMsg,
121150   const sqlcipher3_api_routines *pApi
121151 ){
121152   SQLCIPHER_EXTENSION_INIT2(pApi)
121153   return sqlcipher3Fts3Init(db);
121154 }
121155 #endif
121156
121157 #endif
121158
121159 /************** End of fts3.c ************************************************/
121160 /************** Begin file fts3_aux.c ****************************************/
121161 /*
121162 ** 2011 Jan 27
121163 **
121164 ** The author disclaims copyright to this source code.  In place of
121165 ** a legal notice, here is a blessing:
121166 **
121167 **    May you do good and not evil.
121168 **    May you find forgiveness for yourself and forgive others.
121169 **    May you share freely, never taking more than you give.
121170 **
121171 ******************************************************************************
121172 **
121173 */
121174 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
121175
121176 /* #include <string.h> */
121177 /* #include <assert.h> */
121178
121179 typedef struct Fts3auxTable Fts3auxTable;
121180 typedef struct Fts3auxCursor Fts3auxCursor;
121181
121182 struct Fts3auxTable {
121183   sqlcipher3_vtab base;              /* Base class used by SQLite core */
121184   Fts3Table *pFts3Tab;
121185 };
121186
121187 struct Fts3auxCursor {
121188   sqlcipher3_vtab_cursor base;       /* Base class used by SQLite core */
121189   Fts3MultiSegReader csr;        /* Must be right after "base" */
121190   Fts3SegFilter filter;
121191   char *zStop;
121192   int nStop;                      /* Byte-length of string zStop */
121193   int isEof;                      /* True if cursor is at EOF */
121194   sqlcipher3_int64 iRowid;           /* Current rowid */
121195
121196   int iCol;                       /* Current value of 'col' column */
121197   int nStat;                      /* Size of aStat[] array */
121198   struct Fts3auxColstats {
121199     sqlcipher3_int64 nDoc;           /* 'documents' values for current csr row */
121200     sqlcipher3_int64 nOcc;           /* 'occurrences' values for current csr row */
121201   } *aStat;
121202 };
121203
121204 /*
121205 ** Schema of the terms table.
121206 */
121207 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
121208
121209 /*
121210 ** This function does all the work for both the xConnect and xCreate methods.
121211 ** These tables have no persistent representation of their own, so xConnect
121212 ** and xCreate are identical operations.
121213 */
121214 static int fts3auxConnectMethod(
121215   sqlcipher3 *db,                    /* Database connection */
121216   void *pUnused,                  /* Unused */
121217   int argc,                       /* Number of elements in argv array */
121218   const char * const *argv,       /* xCreate/xConnect argument array */
121219   sqlcipher3_vtab **ppVtab,          /* OUT: New sqlcipher3_vtab object */
121220   char **pzErr                    /* OUT: sqlcipher3_malloc'd error message */
121221 ){
121222   char const *zDb;                /* Name of database (e.g. "main") */
121223   char const *zFts3;              /* Name of fts3 table */
121224   int nDb;                        /* Result of strlen(zDb) */
121225   int nFts3;                      /* Result of strlen(zFts3) */
121226   int nByte;                      /* Bytes of space to allocate here */
121227   int rc;                         /* value returned by declare_vtab() */
121228   Fts3auxTable *p;                /* Virtual table object to return */
121229
121230   UNUSED_PARAMETER(pUnused);
121231
121232   /* The user should specify a single argument - the name of an fts3 table. */
121233   if( argc!=4 ){
121234     *pzErr = sqlcipher3_mprintf(
121235         "wrong number of arguments to fts4aux constructor"
121236     );
121237     return SQLCIPHER_ERROR;
121238   }
121239
121240   zDb = argv[1]; 
121241   nDb = strlen(zDb);
121242   zFts3 = argv[3];
121243   nFts3 = strlen(zFts3);
121244
121245   rc = sqlcipher3_declare_vtab(db, FTS3_TERMS_SCHEMA);
121246   if( rc!=SQLCIPHER_OK ) return rc;
121247
121248   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
121249   p = (Fts3auxTable *)sqlcipher3_malloc(nByte);
121250   if( !p ) return SQLCIPHER_NOMEM;
121251   memset(p, 0, nByte);
121252
121253   p->pFts3Tab = (Fts3Table *)&p[1];
121254   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
121255   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
121256   p->pFts3Tab->db = db;
121257   p->pFts3Tab->nIndex = 1;
121258
121259   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
121260   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
121261   sqlcipher3Fts3Dequote((char *)p->pFts3Tab->zName);
121262
121263   *ppVtab = (sqlcipher3_vtab *)p;
121264   return SQLCIPHER_OK;
121265 }
121266
121267 /*
121268 ** This function does the work for both the xDisconnect and xDestroy methods.
121269 ** These tables have no persistent representation of their own, so xDisconnect
121270 ** and xDestroy are identical operations.
121271 */
121272 static int fts3auxDisconnectMethod(sqlcipher3_vtab *pVtab){
121273   Fts3auxTable *p = (Fts3auxTable *)pVtab;
121274   Fts3Table *pFts3 = p->pFts3Tab;
121275   int i;
121276
121277   /* Free any prepared statements held */
121278   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
121279     sqlcipher3_finalize(pFts3->aStmt[i]);
121280   }
121281   sqlcipher3_free(pFts3->zSegmentsTbl);
121282   sqlcipher3_free(p);
121283   return SQLCIPHER_OK;
121284 }
121285
121286 #define FTS4AUX_EQ_CONSTRAINT 1
121287 #define FTS4AUX_GE_CONSTRAINT 2
121288 #define FTS4AUX_LE_CONSTRAINT 4
121289
121290 /*
121291 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
121292 */
121293 static int fts3auxBestIndexMethod(
121294   sqlcipher3_vtab *pVTab, 
121295   sqlcipher3_index_info *pInfo
121296 ){
121297   int i;
121298   int iEq = -1;
121299   int iGe = -1;
121300   int iLe = -1;
121301
121302   UNUSED_PARAMETER(pVTab);
121303
121304   /* This vtab delivers always results in "ORDER BY term ASC" order. */
121305   if( pInfo->nOrderBy==1 
121306    && pInfo->aOrderBy[0].iColumn==0 
121307    && pInfo->aOrderBy[0].desc==0
121308   ){
121309     pInfo->orderByConsumed = 1;
121310   }
121311
121312   /* Search for equality and range constraints on the "term" column. */
121313   for(i=0; i<pInfo->nConstraint; i++){
121314     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
121315       int op = pInfo->aConstraint[i].op;
121316       if( op==SQLCIPHER_INDEX_CONSTRAINT_EQ ) iEq = i;
121317       if( op==SQLCIPHER_INDEX_CONSTRAINT_LT ) iLe = i;
121318       if( op==SQLCIPHER_INDEX_CONSTRAINT_LE ) iLe = i;
121319       if( op==SQLCIPHER_INDEX_CONSTRAINT_GT ) iGe = i;
121320       if( op==SQLCIPHER_INDEX_CONSTRAINT_GE ) iGe = i;
121321     }
121322   }
121323
121324   if( iEq>=0 ){
121325     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
121326     pInfo->aConstraintUsage[iEq].argvIndex = 1;
121327     pInfo->estimatedCost = 5;
121328   }else{
121329     pInfo->idxNum = 0;
121330     pInfo->estimatedCost = 20000;
121331     if( iGe>=0 ){
121332       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
121333       pInfo->aConstraintUsage[iGe].argvIndex = 1;
121334       pInfo->estimatedCost /= 2;
121335     }
121336     if( iLe>=0 ){
121337       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
121338       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
121339       pInfo->estimatedCost /= 2;
121340     }
121341   }
121342
121343   return SQLCIPHER_OK;
121344 }
121345
121346 /*
121347 ** xOpen - Open a cursor.
121348 */
121349 static int fts3auxOpenMethod(sqlcipher3_vtab *pVTab, sqlcipher3_vtab_cursor **ppCsr){
121350   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
121351
121352   UNUSED_PARAMETER(pVTab);
121353
121354   pCsr = (Fts3auxCursor *)sqlcipher3_malloc(sizeof(Fts3auxCursor));
121355   if( !pCsr ) return SQLCIPHER_NOMEM;
121356   memset(pCsr, 0, sizeof(Fts3auxCursor));
121357
121358   *ppCsr = (sqlcipher3_vtab_cursor *)pCsr;
121359   return SQLCIPHER_OK;
121360 }
121361
121362 /*
121363 ** xClose - Close a cursor.
121364 */
121365 static int fts3auxCloseMethod(sqlcipher3_vtab_cursor *pCursor){
121366   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
121367   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121368
121369   sqlcipher3Fts3SegmentsClose(pFts3);
121370   sqlcipher3Fts3SegReaderFinish(&pCsr->csr);
121371   sqlcipher3_free((void *)pCsr->filter.zTerm);
121372   sqlcipher3_free(pCsr->zStop);
121373   sqlcipher3_free(pCsr->aStat);
121374   sqlcipher3_free(pCsr);
121375   return SQLCIPHER_OK;
121376 }
121377
121378 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
121379   if( nSize>pCsr->nStat ){
121380     struct Fts3auxColstats *aNew;
121381     aNew = (struct Fts3auxColstats *)sqlcipher3_realloc(pCsr->aStat, 
121382         sizeof(struct Fts3auxColstats) * nSize
121383     );
121384     if( aNew==0 ) return SQLCIPHER_NOMEM;
121385     memset(&aNew[pCsr->nStat], 0, 
121386         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
121387     );
121388     pCsr->aStat = aNew;
121389     pCsr->nStat = nSize;
121390   }
121391   return SQLCIPHER_OK;
121392 }
121393
121394 /*
121395 ** xNext - Advance the cursor to the next row, if any.
121396 */
121397 static int fts3auxNextMethod(sqlcipher3_vtab_cursor *pCursor){
121398   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121399   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
121400   int rc;
121401
121402   /* Increment our pretend rowid value. */
121403   pCsr->iRowid++;
121404
121405   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
121406     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLCIPHER_OK;
121407   }
121408
121409   rc = sqlcipher3Fts3SegReaderStep(pFts3, &pCsr->csr);
121410   if( rc==SQLCIPHER_ROW ){
121411     int i = 0;
121412     int nDoclist = pCsr->csr.nDoclist;
121413     char *aDoclist = pCsr->csr.aDoclist;
121414     int iCol;
121415
121416     int eState = 0;
121417
121418     if( pCsr->zStop ){
121419       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
121420       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
121421       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
121422         pCsr->isEof = 1;
121423         return SQLCIPHER_OK;
121424       }
121425     }
121426
121427     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLCIPHER_NOMEM;
121428     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
121429     iCol = 0;
121430
121431     while( i<nDoclist ){
121432       sqlcipher3_int64 v = 0;
121433
121434       i += sqlcipher3Fts3GetVarint(&aDoclist[i], &v);
121435       switch( eState ){
121436         /* State 0. In this state the integer just read was a docid. */
121437         case 0:
121438           pCsr->aStat[0].nDoc++;
121439           eState = 1;
121440           iCol = 0;
121441           break;
121442
121443         /* State 1. In this state we are expecting either a 1, indicating
121444         ** that the following integer will be a column number, or the
121445         ** start of a position list for column 0.  
121446         ** 
121447         ** The only difference between state 1 and state 2 is that if the
121448         ** integer encountered in state 1 is not 0 or 1, then we need to
121449         ** increment the column 0 "nDoc" count for this term.
121450         */
121451         case 1:
121452           assert( iCol==0 );
121453           if( v>1 ){
121454             pCsr->aStat[1].nDoc++;
121455           }
121456           eState = 2;
121457           /* fall through */
121458
121459         case 2:
121460           if( v==0 ){       /* 0x00. Next integer will be a docid. */
121461             eState = 0;
121462           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
121463             eState = 3;
121464           }else{            /* 2 or greater. A position. */
121465             pCsr->aStat[iCol+1].nOcc++;
121466             pCsr->aStat[0].nOcc++;
121467           }
121468           break;
121469
121470         /* State 3. The integer just read is a column number. */
121471         default: assert( eState==3 );
121472           iCol = (int)v;
121473           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLCIPHER_NOMEM;
121474           pCsr->aStat[iCol+1].nDoc++;
121475           eState = 2;
121476           break;
121477       }
121478     }
121479
121480     pCsr->iCol = 0;
121481     rc = SQLCIPHER_OK;
121482   }else{
121483     pCsr->isEof = 1;
121484   }
121485   return rc;
121486 }
121487
121488 /*
121489 ** xFilter - Initialize a cursor to point at the start of its data.
121490 */
121491 static int fts3auxFilterMethod(
121492   sqlcipher3_vtab_cursor *pCursor,   /* The cursor used for this query */
121493   int idxNum,                     /* Strategy index */
121494   const char *idxStr,             /* Unused */
121495   int nVal,                       /* Number of elements in apVal */
121496   sqlcipher3_value **apVal           /* Arguments for the indexing scheme */
121497 ){
121498   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121499   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
121500   int rc;
121501   int isScan;
121502
121503   UNUSED_PARAMETER(nVal);
121504   UNUSED_PARAMETER(idxStr);
121505
121506   assert( idxStr==0 );
121507   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
121508        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
121509        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
121510   );
121511   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
121512
121513   /* In case this cursor is being reused, close and zero it. */
121514   testcase(pCsr->filter.zTerm);
121515   sqlcipher3Fts3SegReaderFinish(&pCsr->csr);
121516   sqlcipher3_free((void *)pCsr->filter.zTerm);
121517   sqlcipher3_free(pCsr->aStat);
121518   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
121519
121520   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
121521   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
121522
121523   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
121524     const unsigned char *zStr = sqlcipher3_value_text(apVal[0]);
121525     if( zStr ){
121526       pCsr->filter.zTerm = sqlcipher3_mprintf("%s", zStr);
121527       pCsr->filter.nTerm = sqlcipher3_value_bytes(apVal[0]);
121528       if( pCsr->filter.zTerm==0 ) return SQLCIPHER_NOMEM;
121529     }
121530   }
121531   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
121532     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
121533     pCsr->zStop = sqlcipher3_mprintf("%s", sqlcipher3_value_text(apVal[iIdx]));
121534     pCsr->nStop = sqlcipher3_value_bytes(apVal[iIdx]);
121535     if( pCsr->zStop==0 ) return SQLCIPHER_NOMEM;
121536   }
121537
121538   rc = sqlcipher3Fts3SegReaderCursor(pFts3, 0, FTS3_SEGCURSOR_ALL,
121539       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
121540   );
121541   if( rc==SQLCIPHER_OK ){
121542     rc = sqlcipher3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
121543   }
121544
121545   if( rc==SQLCIPHER_OK ) rc = fts3auxNextMethod(pCursor);
121546   return rc;
121547 }
121548
121549 /*
121550 ** xEof - Return true if the cursor is at EOF, or false otherwise.
121551 */
121552 static int fts3auxEofMethod(sqlcipher3_vtab_cursor *pCursor){
121553   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121554   return pCsr->isEof;
121555 }
121556
121557 /*
121558 ** xColumn - Return a column value.
121559 */
121560 static int fts3auxColumnMethod(
121561   sqlcipher3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
121562   sqlcipher3_context *pContext,      /* Context for sqlcipher3_result_xxx() calls */
121563   int iCol                        /* Index of column to read value from */
121564 ){
121565   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
121566
121567   assert( p->isEof==0 );
121568   if( iCol==0 ){        /* Column "term" */
121569     sqlcipher3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLCIPHER_TRANSIENT);
121570   }else if( iCol==1 ){  /* Column "col" */
121571     if( p->iCol ){
121572       sqlcipher3_result_int(pContext, p->iCol-1);
121573     }else{
121574       sqlcipher3_result_text(pContext, "*", -1, SQLCIPHER_STATIC);
121575     }
121576   }else if( iCol==2 ){  /* Column "documents" */
121577     sqlcipher3_result_int64(pContext, p->aStat[p->iCol].nDoc);
121578   }else{                /* Column "occurrences" */
121579     sqlcipher3_result_int64(pContext, p->aStat[p->iCol].nOcc);
121580   }
121581
121582   return SQLCIPHER_OK;
121583 }
121584
121585 /*
121586 ** xRowid - Return the current rowid for the cursor.
121587 */
121588 static int fts3auxRowidMethod(
121589   sqlcipher3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
121590   sqlcipher_int64 *pRowid            /* OUT: Rowid value */
121591 ){
121592   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121593   *pRowid = pCsr->iRowid;
121594   return SQLCIPHER_OK;
121595 }
121596
121597 /*
121598 ** Register the fts3aux module with database connection db. Return SQLCIPHER_OK
121599 ** if successful or an error code if sqlcipher3_create_module() fails.
121600 */
121601 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitAux(sqlcipher3 *db){
121602   static const sqlcipher3_module fts3aux_module = {
121603      0,                           /* iVersion      */
121604      fts3auxConnectMethod,        /* xCreate       */
121605      fts3auxConnectMethod,        /* xConnect      */
121606      fts3auxBestIndexMethod,      /* xBestIndex    */
121607      fts3auxDisconnectMethod,     /* xDisconnect   */
121608      fts3auxDisconnectMethod,     /* xDestroy      */
121609      fts3auxOpenMethod,           /* xOpen         */
121610      fts3auxCloseMethod,          /* xClose        */
121611      fts3auxFilterMethod,         /* xFilter       */
121612      fts3auxNextMethod,           /* xNext         */
121613      fts3auxEofMethod,            /* xEof          */
121614      fts3auxColumnMethod,         /* xColumn       */
121615      fts3auxRowidMethod,          /* xRowid        */
121616      0,                           /* xUpdate       */
121617      0,                           /* xBegin        */
121618      0,                           /* xSync         */
121619      0,                           /* xCommit       */
121620      0,                           /* xRollback     */
121621      0,                           /* xFindFunction */
121622      0,                           /* xRename       */
121623      0,                           /* xSavepoint    */
121624      0,                           /* xRelease      */
121625      0                            /* xRollbackTo   */
121626   };
121627   int rc;                         /* Return code */
121628
121629   rc = sqlcipher3_create_module(db, "fts4aux", &fts3aux_module, 0);
121630   return rc;
121631 }
121632
121633 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
121634
121635 /************** End of fts3_aux.c ********************************************/
121636 /************** Begin file fts3_expr.c ***************************************/
121637 /*
121638 ** 2008 Nov 28
121639 **
121640 ** The author disclaims copyright to this source code.  In place of
121641 ** a legal notice, here is a blessing:
121642 **
121643 **    May you do good and not evil.
121644 **    May you find forgiveness for yourself and forgive others.
121645 **    May you share freely, never taking more than you give.
121646 **
121647 ******************************************************************************
121648 **
121649 ** This module contains code that implements a parser for fts3 query strings
121650 ** (the right-hand argument to the MATCH operator). Because the supported 
121651 ** syntax is relatively simple, the whole tokenizer/parser system is
121652 ** hand-coded. 
121653 */
121654 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
121655
121656 /*
121657 ** By default, this module parses the legacy syntax that has been 
121658 ** traditionally used by fts3. Or, if SQLCIPHER_ENABLE_FTS3_PARENTHESIS
121659 ** is defined, then it uses the new syntax. The differences between
121660 ** the new and the old syntaxes are:
121661 **
121662 **  a) The new syntax supports parenthesis. The old does not.
121663 **
121664 **  b) The new syntax supports the AND and NOT operators. The old does not.
121665 **
121666 **  c) The old syntax supports the "-" token qualifier. This is not 
121667 **     supported by the new syntax (it is replaced by the NOT operator).
121668 **
121669 **  d) When using the old syntax, the OR operator has a greater precedence
121670 **     than an implicit AND. When using the new, both implicity and explicit
121671 **     AND operators have a higher precedence than OR.
121672 **
121673 ** If compiled with SQLCIPHER_TEST defined, then this module exports the
121674 ** symbol "int sqlcipher3_fts3_enable_parentheses". Setting this variable
121675 ** to zero causes the module to use the old syntax. If it is set to 
121676 ** non-zero the new syntax is activated. This is so both syntaxes can
121677 ** be tested using a single build of testfixture.
121678 **
121679 ** The following describes the syntax supported by the fts3 MATCH
121680 ** operator in a similar format to that used by the lemon parser
121681 ** generator. This module does not use actually lemon, it uses a
121682 ** custom parser.
121683 **
121684 **   query ::= andexpr (OR andexpr)*.
121685 **
121686 **   andexpr ::= notexpr (AND? notexpr)*.
121687 **
121688 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
121689 **   notexpr ::= LP query RP.
121690 **
121691 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
121692 **
121693 **   distance_opt ::= .
121694 **   distance_opt ::= / INTEGER.
121695 **
121696 **   phrase ::= TOKEN.
121697 **   phrase ::= COLUMN:TOKEN.
121698 **   phrase ::= "TOKEN TOKEN TOKEN...".
121699 */
121700
121701 #ifdef SQLCIPHER_TEST
121702 SQLCIPHER_API int sqlcipher3_fts3_enable_parentheses = 0;
121703 #else
121704 # ifdef SQLCIPHER_ENABLE_FTS3_PARENTHESIS 
121705 #  define sqlcipher3_fts3_enable_parentheses 1
121706 # else
121707 #  define sqlcipher3_fts3_enable_parentheses 0
121708 # endif
121709 #endif
121710
121711 /*
121712 ** Default span for NEAR operators.
121713 */
121714 #define SQLCIPHER_FTS3_DEFAULT_NEAR_PARAM 10
121715
121716 /* #include <string.h> */
121717 /* #include <assert.h> */
121718
121719 /*
121720 ** isNot:
121721 **   This variable is used by function getNextNode(). When getNextNode() is
121722 **   called, it sets ParseContext.isNot to true if the 'next node' is a 
121723 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
121724 **   FTS3 query "sqlcipher -mysql". Otherwise, ParseContext.isNot is set to
121725 **   zero.
121726 */
121727 typedef struct ParseContext ParseContext;
121728 struct ParseContext {
121729   sqlcipher3_tokenizer *pTokenizer;      /* Tokenizer module */
121730   const char **azCol;                 /* Array of column names for fts3 table */
121731   int bFts4;                          /* True to allow FTS4-only syntax */
121732   int nCol;                           /* Number of entries in azCol[] */
121733   int iDefaultCol;                    /* Default column to query */
121734   int isNot;                          /* True if getNextNode() sees a unary - */
121735   sqlcipher3_context *pCtx;              /* Write error message here */
121736   int nNest;                          /* Number of nested brackets */
121737 };
121738
121739 /*
121740 ** This function is equivalent to the standard isspace() function. 
121741 **
121742 ** The standard isspace() can be awkward to use safely, because although it
121743 ** is defined to accept an argument of type int, its behaviour when passed
121744 ** an integer that falls outside of the range of the unsigned char type
121745 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
121746 ** is defined to accept an argument of type char, and always returns 0 for
121747 ** any values that fall outside of the range of the unsigned char type (i.e.
121748 ** negative values).
121749 */
121750 static int fts3isspace(char c){
121751   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
121752 }
121753
121754 /*
121755 ** Allocate nByte bytes of memory using sqlcipher3_malloc(). If successful,
121756 ** zero the memory before returning a pointer to it. If unsuccessful, 
121757 ** return NULL.
121758 */
121759 static void *fts3MallocZero(int nByte){
121760   void *pRet = sqlcipher3_malloc(nByte);
121761   if( pRet ) memset(pRet, 0, nByte);
121762   return pRet;
121763 }
121764
121765
121766 /*
121767 ** Extract the next token from buffer z (length n) using the tokenizer
121768 ** and other information (column names etc.) in pParse. Create an Fts3Expr
121769 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
121770 ** single token and set *ppExpr to point to it. If the end of the buffer is
121771 ** reached before a token is found, set *ppExpr to zero. It is the
121772 ** responsibility of the caller to eventually deallocate the allocated 
121773 ** Fts3Expr structure (if any) by passing it to sqlcipher3_free().
121774 **
121775 ** Return SQLCIPHER_OK if successful, or SQLCIPHER_NOMEM if a memory allocation
121776 ** fails.
121777 */
121778 static int getNextToken(
121779   ParseContext *pParse,                   /* fts3 query parse context */
121780   int iCol,                               /* Value for Fts3Phrase.iColumn */
121781   const char *z, int n,                   /* Input string */
121782   Fts3Expr **ppExpr,                      /* OUT: expression */
121783   int *pnConsumed                         /* OUT: Number of bytes consumed */
121784 ){
121785   sqlcipher3_tokenizer *pTokenizer = pParse->pTokenizer;
121786   sqlcipher3_tokenizer_module const *pModule = pTokenizer->pModule;
121787   int rc;
121788   sqlcipher3_tokenizer_cursor *pCursor;
121789   Fts3Expr *pRet = 0;
121790   int nConsumed = 0;
121791
121792   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
121793   if( rc==SQLCIPHER_OK ){
121794     const char *zToken;
121795     int nToken, iStart, iEnd, iPosition;
121796     int nByte;                               /* total space to allocate */
121797
121798     pCursor->pTokenizer = pTokenizer;
121799     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
121800
121801     if( rc==SQLCIPHER_OK ){
121802       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
121803       pRet = (Fts3Expr *)fts3MallocZero(nByte);
121804       if( !pRet ){
121805         rc = SQLCIPHER_NOMEM;
121806       }else{
121807         pRet->eType = FTSQUERY_PHRASE;
121808         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
121809         pRet->pPhrase->nToken = 1;
121810         pRet->pPhrase->iColumn = iCol;
121811         pRet->pPhrase->aToken[0].n = nToken;
121812         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
121813         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
121814
121815         if( iEnd<n && z[iEnd]=='*' ){
121816           pRet->pPhrase->aToken[0].isPrefix = 1;
121817           iEnd++;
121818         }
121819
121820         while( 1 ){
121821           if( !sqlcipher3_fts3_enable_parentheses 
121822            && iStart>0 && z[iStart-1]=='-' 
121823           ){
121824             pParse->isNot = 1;
121825             iStart--;
121826           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
121827             pRet->pPhrase->aToken[0].bFirst = 1;
121828             iStart--;
121829           }else{
121830             break;
121831           }
121832         }
121833
121834       }
121835       nConsumed = iEnd;
121836     }
121837
121838     pModule->xClose(pCursor);
121839   }
121840   
121841   *pnConsumed = nConsumed;
121842   *ppExpr = pRet;
121843   return rc;
121844 }
121845
121846
121847 /*
121848 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
121849 ** then free the old allocation.
121850 */
121851 static void *fts3ReallocOrFree(void *pOrig, int nNew){
121852   void *pRet = sqlcipher3_realloc(pOrig, nNew);
121853   if( !pRet ){
121854     sqlcipher3_free(pOrig);
121855   }
121856   return pRet;
121857 }
121858
121859 /*
121860 ** Buffer zInput, length nInput, contains the contents of a quoted string
121861 ** that appeared as part of an fts3 query expression. Neither quote character
121862 ** is included in the buffer. This function attempts to tokenize the entire
121863 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
121864 ** containing the results.
121865 **
121866 ** If successful, SQLCIPHER_OK is returned and *ppExpr set to point at the
121867 ** allocated Fts3Expr structure. Otherwise, either SQLCIPHER_NOMEM (out of memory
121868 ** error) or SQLCIPHER_ERROR (tokenization error) is returned and *ppExpr set
121869 ** to 0.
121870 */
121871 static int getNextString(
121872   ParseContext *pParse,                   /* fts3 query parse context */
121873   const char *zInput, int nInput,         /* Input string */
121874   Fts3Expr **ppExpr                       /* OUT: expression */
121875 ){
121876   sqlcipher3_tokenizer *pTokenizer = pParse->pTokenizer;
121877   sqlcipher3_tokenizer_module const *pModule = pTokenizer->pModule;
121878   int rc;
121879   Fts3Expr *p = 0;
121880   sqlcipher3_tokenizer_cursor *pCursor = 0;
121881   char *zTemp = 0;
121882   int nTemp = 0;
121883
121884   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
121885   int nToken = 0;
121886
121887   /* The final Fts3Expr data structure, including the Fts3Phrase,
121888   ** Fts3PhraseToken structures token buffers are all stored as a single 
121889   ** allocation so that the expression can be freed with a single call to
121890   ** sqlcipher3_free(). Setting this up requires a two pass approach.
121891   **
121892   ** The first pass, in the block below, uses a tokenizer cursor to iterate
121893   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
121894   ** to assemble data in two dynamic buffers:
121895   **
121896   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
121897   **             structure, followed by the array of Fts3PhraseToken 
121898   **             structures. This pass only populates the Fts3PhraseToken array.
121899   **
121900   **   Buffer zTemp: Contains copies of all tokens.
121901   **
121902   ** The second pass, in the block that begins "if( rc==SQLCIPHER_DONE )" below,
121903   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
121904   ** structures.
121905   */
121906   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
121907   if( rc==SQLCIPHER_OK ){
121908     int ii;
121909     pCursor->pTokenizer = pTokenizer;
121910     for(ii=0; rc==SQLCIPHER_OK; ii++){
121911       const char *zByte;
121912       int nByte, iBegin, iEnd, iPos;
121913       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
121914       if( rc==SQLCIPHER_OK ){
121915         Fts3PhraseToken *pToken;
121916
121917         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
121918         if( !p ) goto no_mem;
121919
121920         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
121921         if( !zTemp ) goto no_mem;
121922
121923         assert( nToken==ii );
121924         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
121925         memset(pToken, 0, sizeof(Fts3PhraseToken));
121926
121927         memcpy(&zTemp[nTemp], zByte, nByte);
121928         nTemp += nByte;
121929
121930         pToken->n = nByte;
121931         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
121932         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
121933         nToken = ii+1;
121934       }
121935     }
121936
121937     pModule->xClose(pCursor);
121938     pCursor = 0;
121939   }
121940
121941   if( rc==SQLCIPHER_DONE ){
121942     int jj;
121943     char *zBuf = 0;
121944
121945     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
121946     if( !p ) goto no_mem;
121947     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
121948     p->eType = FTSQUERY_PHRASE;
121949     p->pPhrase = (Fts3Phrase *)&p[1];
121950     p->pPhrase->iColumn = pParse->iDefaultCol;
121951     p->pPhrase->nToken = nToken;
121952
121953     zBuf = (char *)&p->pPhrase->aToken[nToken];
121954     if( zTemp ){
121955       memcpy(zBuf, zTemp, nTemp);
121956       sqlcipher3_free(zTemp);
121957     }else{
121958       assert( nTemp==0 );
121959     }
121960
121961     for(jj=0; jj<p->pPhrase->nToken; jj++){
121962       p->pPhrase->aToken[jj].z = zBuf;
121963       zBuf += p->pPhrase->aToken[jj].n;
121964     }
121965     rc = SQLCIPHER_OK;
121966   }
121967
121968   *ppExpr = p;
121969   return rc;
121970 no_mem:
121971
121972   if( pCursor ){
121973     pModule->xClose(pCursor);
121974   }
121975   sqlcipher3_free(zTemp);
121976   sqlcipher3_free(p);
121977   *ppExpr = 0;
121978   return SQLCIPHER_NOMEM;
121979 }
121980
121981 /*
121982 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
121983 ** call fts3ExprParse(). So this forward declaration is required.
121984 */
121985 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
121986
121987 /*
121988 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
121989 ** structure, or set to 0 if the end of the input buffer is reached.
121990 **
121991 ** Returns an SQLite error code. SQLCIPHER_OK if everything works, SQLCIPHER_NOMEM
121992 ** if a malloc failure occurs, or SQLCIPHER_ERROR if a parse error is encountered.
121993 ** If SQLCIPHER_ERROR is returned, pContext is populated with an error message.
121994 */
121995 static int getNextNode(
121996   ParseContext *pParse,                   /* fts3 query parse context */
121997   const char *z, int n,                   /* Input string */
121998   Fts3Expr **ppExpr,                      /* OUT: expression */
121999   int *pnConsumed                         /* OUT: Number of bytes consumed */
122000 ){
122001   static const struct Fts3Keyword {
122002     char *z;                              /* Keyword text */
122003     unsigned char n;                      /* Length of the keyword */
122004     unsigned char parenOnly;              /* Only valid in paren mode */
122005     unsigned char eType;                  /* Keyword code */
122006   } aKeyword[] = {
122007     { "OR" ,  2, 0, FTSQUERY_OR   },
122008     { "AND",  3, 1, FTSQUERY_AND  },
122009     { "NOT",  3, 1, FTSQUERY_NOT  },
122010     { "NEAR", 4, 0, FTSQUERY_NEAR }
122011   };
122012   int ii;
122013   int iCol;
122014   int iColLen;
122015   int rc;
122016   Fts3Expr *pRet = 0;
122017
122018   const char *zInput = z;
122019   int nInput = n;
122020
122021   pParse->isNot = 0;
122022
122023   /* Skip over any whitespace before checking for a keyword, an open or
122024   ** close bracket, or a quoted string. 
122025   */
122026   while( nInput>0 && fts3isspace(*zInput) ){
122027     nInput--;
122028     zInput++;
122029   }
122030   if( nInput==0 ){
122031     return SQLCIPHER_DONE;
122032   }
122033
122034   /* See if we are dealing with a keyword. */
122035   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
122036     const struct Fts3Keyword *pKey = &aKeyword[ii];
122037
122038     if( (pKey->parenOnly & ~sqlcipher3_fts3_enable_parentheses)!=0 ){
122039       continue;
122040     }
122041
122042     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
122043       int nNear = SQLCIPHER_FTS3_DEFAULT_NEAR_PARAM;
122044       int nKey = pKey->n;
122045       char cNext;
122046
122047       /* If this is a "NEAR" keyword, check for an explicit nearness. */
122048       if( pKey->eType==FTSQUERY_NEAR ){
122049         assert( nKey==4 );
122050         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
122051           nNear = 0;
122052           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
122053             nNear = nNear * 10 + (zInput[nKey] - '0');
122054           }
122055         }
122056       }
122057
122058       /* At this point this is probably a keyword. But for that to be true,
122059       ** the next byte must contain either whitespace, an open or close
122060       ** parenthesis, a quote character, or EOF. 
122061       */
122062       cNext = zInput[nKey];
122063       if( fts3isspace(cNext) 
122064        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
122065       ){
122066         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
122067         if( !pRet ){
122068           return SQLCIPHER_NOMEM;
122069         }
122070         pRet->eType = pKey->eType;
122071         pRet->nNear = nNear;
122072         *ppExpr = pRet;
122073         *pnConsumed = (int)((zInput - z) + nKey);
122074         return SQLCIPHER_OK;
122075       }
122076
122077       /* Turns out that wasn't a keyword after all. This happens if the
122078       ** user has supplied a token such as "ORacle". Continue.
122079       */
122080     }
122081   }
122082
122083   /* Check for an open bracket. */
122084   if( sqlcipher3_fts3_enable_parentheses ){
122085     if( *zInput=='(' ){
122086       int nConsumed;
122087       pParse->nNest++;
122088       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
122089       if( rc==SQLCIPHER_OK && !*ppExpr ){
122090         rc = SQLCIPHER_DONE;
122091       }
122092       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
122093       return rc;
122094     }
122095   
122096     /* Check for a close bracket. */
122097     if( *zInput==')' ){
122098       pParse->nNest--;
122099       *pnConsumed = (int)((zInput - z) + 1);
122100       return SQLCIPHER_DONE;
122101     }
122102   }
122103
122104   /* See if we are dealing with a quoted phrase. If this is the case, then
122105   ** search for the closing quote and pass the whole string to getNextString()
122106   ** for processing. This is easy to do, as fts3 has no syntax for escaping
122107   ** a quote character embedded in a string.
122108   */
122109   if( *zInput=='"' ){
122110     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
122111     *pnConsumed = (int)((zInput - z) + ii + 1);
122112     if( ii==nInput ){
122113       return SQLCIPHER_ERROR;
122114     }
122115     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
122116   }
122117
122118
122119   /* If control flows to this point, this must be a regular token, or 
122120   ** the end of the input. Read a regular token using the sqlcipher3_tokenizer
122121   ** interface. Before doing so, figure out if there is an explicit
122122   ** column specifier for the token. 
122123   **
122124   ** TODO: Strangely, it is not possible to associate a column specifier
122125   ** with a quoted phrase, only with a single token. Not sure if this was
122126   ** an implementation artifact or an intentional decision when fts3 was
122127   ** first implemented. Whichever it was, this module duplicates the 
122128   ** limitation.
122129   */
122130   iCol = pParse->iDefaultCol;
122131   iColLen = 0;
122132   for(ii=0; ii<pParse->nCol; ii++){
122133     const char *zStr = pParse->azCol[ii];
122134     int nStr = (int)strlen(zStr);
122135     if( nInput>nStr && zInput[nStr]==':' 
122136      && sqlcipher3_strnicmp(zStr, zInput, nStr)==0 
122137     ){
122138       iCol = ii;
122139       iColLen = (int)((zInput - z) + nStr + 1);
122140       break;
122141     }
122142   }
122143   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
122144   *pnConsumed += iColLen;
122145   return rc;
122146 }
122147
122148 /*
122149 ** The argument is an Fts3Expr structure for a binary operator (any type
122150 ** except an FTSQUERY_PHRASE). Return an integer value representing the
122151 ** precedence of the operator. Lower values have a higher precedence (i.e.
122152 ** group more tightly). For example, in the C language, the == operator
122153 ** groups more tightly than ||, and would therefore have a higher precedence.
122154 **
122155 ** When using the new fts3 query syntax (when SQLCIPHER_ENABLE_FTS3_PARENTHESIS
122156 ** is defined), the order of the operators in precedence from highest to
122157 ** lowest is:
122158 **
122159 **   NEAR
122160 **   NOT
122161 **   AND (including implicit ANDs)
122162 **   OR
122163 **
122164 ** Note that when using the old query syntax, the OR operator has a higher
122165 ** precedence than the AND operator.
122166 */
122167 static int opPrecedence(Fts3Expr *p){
122168   assert( p->eType!=FTSQUERY_PHRASE );
122169   if( sqlcipher3_fts3_enable_parentheses ){
122170     return p->eType;
122171   }else if( p->eType==FTSQUERY_NEAR ){
122172     return 1;
122173   }else if( p->eType==FTSQUERY_OR ){
122174     return 2;
122175   }
122176   assert( p->eType==FTSQUERY_AND );
122177   return 3;
122178 }
122179
122180 /*
122181 ** Argument ppHead contains a pointer to the current head of a query 
122182 ** expression tree being parsed. pPrev is the expression node most recently
122183 ** inserted into the tree. This function adds pNew, which is always a binary
122184 ** operator node, into the expression tree based on the relative precedence
122185 ** of pNew and the existing nodes of the tree. This may result in the head
122186 ** of the tree changing, in which case *ppHead is set to the new root node.
122187 */
122188 static void insertBinaryOperator(
122189   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
122190   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
122191   Fts3Expr *pNew           /* New binary node to insert into expression tree */
122192 ){
122193   Fts3Expr *pSplit = pPrev;
122194   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
122195     pSplit = pSplit->pParent;
122196   }
122197
122198   if( pSplit->pParent ){
122199     assert( pSplit->pParent->pRight==pSplit );
122200     pSplit->pParent->pRight = pNew;
122201     pNew->pParent = pSplit->pParent;
122202   }else{
122203     *ppHead = pNew;
122204   }
122205   pNew->pLeft = pSplit;
122206   pSplit->pParent = pNew;
122207 }
122208
122209 /*
122210 ** Parse the fts3 query expression found in buffer z, length n. This function
122211 ** returns either when the end of the buffer is reached or an unmatched 
122212 ** closing bracket - ')' - is encountered.
122213 **
122214 ** If successful, SQLCIPHER_OK is returned, *ppExpr is set to point to the
122215 ** parsed form of the expression and *pnConsumed is set to the number of
122216 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLCIPHER_NOMEM
122217 ** (out of memory error) or SQLCIPHER_ERROR (parse error) is returned.
122218 */
122219 static int fts3ExprParse(
122220   ParseContext *pParse,                   /* fts3 query parse context */
122221   const char *z, int n,                   /* Text of MATCH query */
122222   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
122223   int *pnConsumed                         /* OUT: Number of bytes consumed */
122224 ){
122225   Fts3Expr *pRet = 0;
122226   Fts3Expr *pPrev = 0;
122227   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
122228   int nIn = n;
122229   const char *zIn = z;
122230   int rc = SQLCIPHER_OK;
122231   int isRequirePhrase = 1;
122232
122233   while( rc==SQLCIPHER_OK ){
122234     Fts3Expr *p = 0;
122235     int nByte = 0;
122236     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
122237     if( rc==SQLCIPHER_OK ){
122238       int isPhrase;
122239
122240       if( !sqlcipher3_fts3_enable_parentheses 
122241        && p->eType==FTSQUERY_PHRASE && pParse->isNot 
122242       ){
122243         /* Create an implicit NOT operator. */
122244         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
122245         if( !pNot ){
122246           sqlcipher3Fts3ExprFree(p);
122247           rc = SQLCIPHER_NOMEM;
122248           goto exprparse_out;
122249         }
122250         pNot->eType = FTSQUERY_NOT;
122251         pNot->pRight = p;
122252         if( pNotBranch ){
122253           pNot->pLeft = pNotBranch;
122254         }
122255         pNotBranch = pNot;
122256         p = pPrev;
122257       }else{
122258         int eType = p->eType;
122259         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
122260
122261         /* The isRequirePhrase variable is set to true if a phrase or
122262         ** an expression contained in parenthesis is required. If a
122263         ** binary operator (AND, OR, NOT or NEAR) is encounted when
122264         ** isRequirePhrase is set, this is a syntax error.
122265         */
122266         if( !isPhrase && isRequirePhrase ){
122267           sqlcipher3Fts3ExprFree(p);
122268           rc = SQLCIPHER_ERROR;
122269           goto exprparse_out;
122270         }
122271   
122272         if( isPhrase && !isRequirePhrase ){
122273           /* Insert an implicit AND operator. */
122274           Fts3Expr *pAnd;
122275           assert( pRet && pPrev );
122276           pAnd = fts3MallocZero(sizeof(Fts3Expr));
122277           if( !pAnd ){
122278             sqlcipher3Fts3ExprFree(p);
122279             rc = SQLCIPHER_NOMEM;
122280             goto exprparse_out;
122281           }
122282           pAnd->eType = FTSQUERY_AND;
122283           insertBinaryOperator(&pRet, pPrev, pAnd);
122284           pPrev = pAnd;
122285         }
122286
122287         /* This test catches attempts to make either operand of a NEAR
122288         ** operator something other than a phrase. For example, either of
122289         ** the following:
122290         **
122291         **    (bracketed expression) NEAR phrase
122292         **    phrase NEAR (bracketed expression)
122293         **
122294         ** Return an error in either case.
122295         */
122296         if( pPrev && (
122297             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
122298          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
122299         )){
122300           sqlcipher3Fts3ExprFree(p);
122301           rc = SQLCIPHER_ERROR;
122302           goto exprparse_out;
122303         }
122304   
122305         if( isPhrase ){
122306           if( pRet ){
122307             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
122308             pPrev->pRight = p;
122309             p->pParent = pPrev;
122310           }else{
122311             pRet = p;
122312           }
122313         }else{
122314           insertBinaryOperator(&pRet, pPrev, p);
122315         }
122316         isRequirePhrase = !isPhrase;
122317       }
122318       assert( nByte>0 );
122319     }
122320     assert( rc!=SQLCIPHER_OK || (nByte>0 && nByte<=nIn) );
122321     nIn -= nByte;
122322     zIn += nByte;
122323     pPrev = p;
122324   }
122325
122326   if( rc==SQLCIPHER_DONE && pRet && isRequirePhrase ){
122327     rc = SQLCIPHER_ERROR;
122328   }
122329
122330   if( rc==SQLCIPHER_DONE ){
122331     rc = SQLCIPHER_OK;
122332     if( !sqlcipher3_fts3_enable_parentheses && pNotBranch ){
122333       if( !pRet ){
122334         rc = SQLCIPHER_ERROR;
122335       }else{
122336         Fts3Expr *pIter = pNotBranch;
122337         while( pIter->pLeft ){
122338           pIter = pIter->pLeft;
122339         }
122340         pIter->pLeft = pRet;
122341         pRet = pNotBranch;
122342       }
122343     }
122344   }
122345   *pnConsumed = n - nIn;
122346
122347 exprparse_out:
122348   if( rc!=SQLCIPHER_OK ){
122349     sqlcipher3Fts3ExprFree(pRet);
122350     sqlcipher3Fts3ExprFree(pNotBranch);
122351     pRet = 0;
122352   }
122353   *ppExpr = pRet;
122354   return rc;
122355 }
122356
122357 /*
122358 ** Parameters z and n contain a pointer to and length of a buffer containing
122359 ** an fts3 query expression, respectively. This function attempts to parse the
122360 ** query expression and create a tree of Fts3Expr structures representing the
122361 ** parsed expression. If successful, *ppExpr is set to point to the head
122362 ** of the parsed expression tree and SQLCIPHER_OK is returned. If an error
122363 ** occurs, either SQLCIPHER_NOMEM (out-of-memory error) or SQLCIPHER_ERROR (parse
122364 ** error) is returned and *ppExpr is set to 0.
122365 **
122366 ** If parameter n is a negative number, then z is assumed to point to a
122367 ** nul-terminated string and the length is determined using strlen().
122368 **
122369 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
122370 ** use to normalize query tokens while parsing the expression. The azCol[]
122371 ** array, which is assumed to contain nCol entries, should contain the names
122372 ** of each column in the target fts3 table, in order from left to right. 
122373 ** Column names must be nul-terminated strings.
122374 **
122375 ** The iDefaultCol parameter should be passed the index of the table column
122376 ** that appears on the left-hand-side of the MATCH operator (the default
122377 ** column to match against for tokens for which a column name is not explicitly
122378 ** specified as part of the query string), or -1 if tokens may by default
122379 ** match any table column.
122380 */
122381 SQLCIPHER_PRIVATE int sqlcipher3Fts3ExprParse(
122382   sqlcipher3_tokenizer *pTokenizer,      /* Tokenizer module */
122383   char **azCol,                       /* Array of column names for fts3 table */
122384   int bFts4,                          /* True to allow FTS4-only syntax */
122385   int nCol,                           /* Number of entries in azCol[] */
122386   int iDefaultCol,                    /* Default column to query */
122387   const char *z, int n,               /* Text of MATCH query */
122388   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
122389 ){
122390   int nParsed;
122391   int rc;
122392   ParseContext sParse;
122393   sParse.pTokenizer = pTokenizer;
122394   sParse.azCol = (const char **)azCol;
122395   sParse.nCol = nCol;
122396   sParse.iDefaultCol = iDefaultCol;
122397   sParse.nNest = 0;
122398   sParse.bFts4 = bFts4;
122399   if( z==0 ){
122400     *ppExpr = 0;
122401     return SQLCIPHER_OK;
122402   }
122403   if( n<0 ){
122404     n = (int)strlen(z);
122405   }
122406   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
122407
122408   /* Check for mismatched parenthesis */
122409   if( rc==SQLCIPHER_OK && sParse.nNest ){
122410     rc = SQLCIPHER_ERROR;
122411     sqlcipher3Fts3ExprFree(*ppExpr);
122412     *ppExpr = 0;
122413   }
122414
122415   return rc;
122416 }
122417
122418 /*
122419 ** Free a parsed fts3 query expression allocated by sqlcipher3Fts3ExprParse().
122420 */
122421 SQLCIPHER_PRIVATE void sqlcipher3Fts3ExprFree(Fts3Expr *p){
122422   if( p ){
122423     assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
122424     sqlcipher3Fts3ExprFree(p->pLeft);
122425     sqlcipher3Fts3ExprFree(p->pRight);
122426     sqlcipher3Fts3EvalPhraseCleanup(p->pPhrase);
122427     sqlcipher3_free(p->aMI);
122428     sqlcipher3_free(p);
122429   }
122430 }
122431
122432 /****************************************************************************
122433 *****************************************************************************
122434 ** Everything after this point is just test code.
122435 */
122436
122437 #ifdef SQLCIPHER_TEST
122438
122439 /* #include <stdio.h> */
122440
122441 /*
122442 ** Function to query the hash-table of tokenizers (see README.tokenizers).
122443 */
122444 static int queryTestTokenizer(
122445   sqlcipher3 *db, 
122446   const char *zName,  
122447   const sqlcipher3_tokenizer_module **pp
122448 ){
122449   int rc;
122450   sqlcipher3_stmt *pStmt;
122451   const char zSql[] = "SELECT fts3_tokenizer(?)";
122452
122453   *pp = 0;
122454   rc = sqlcipher3_prepare_v2(db, zSql, -1, &pStmt, 0);
122455   if( rc!=SQLCIPHER_OK ){
122456     return rc;
122457   }
122458
122459   sqlcipher3_bind_text(pStmt, 1, zName, -1, SQLCIPHER_STATIC);
122460   if( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
122461     if( sqlcipher3_column_type(pStmt, 0)==SQLCIPHER_BLOB ){
122462       memcpy((void *)pp, sqlcipher3_column_blob(pStmt, 0), sizeof(*pp));
122463     }
122464   }
122465
122466   return sqlcipher3_finalize(pStmt);
122467 }
122468
122469 /*
122470 ** Return a pointer to a buffer containing a text representation of the
122471 ** expression passed as the first argument. The buffer is obtained from
122472 ** sqlcipher3_malloc(). It is the responsibility of the caller to use 
122473 ** sqlcipher3_free() to release the memory. If an OOM condition is encountered,
122474 ** NULL is returned.
122475 **
122476 ** If the second argument is not NULL, then its contents are prepended to 
122477 ** the returned expression text and then freed using sqlcipher3_free().
122478 */
122479 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
122480   switch( pExpr->eType ){
122481     case FTSQUERY_PHRASE: {
122482       Fts3Phrase *pPhrase = pExpr->pPhrase;
122483       int i;
122484       zBuf = sqlcipher3_mprintf(
122485           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
122486       for(i=0; zBuf && i<pPhrase->nToken; i++){
122487         zBuf = sqlcipher3_mprintf("%z %.*s%s", zBuf, 
122488             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
122489             (pPhrase->aToken[i].isPrefix?"+":"")
122490         );
122491       }
122492       return zBuf;
122493     }
122494
122495     case FTSQUERY_NEAR:
122496       zBuf = sqlcipher3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
122497       break;
122498     case FTSQUERY_NOT:
122499       zBuf = sqlcipher3_mprintf("%zNOT ", zBuf);
122500       break;
122501     case FTSQUERY_AND:
122502       zBuf = sqlcipher3_mprintf("%zAND ", zBuf);
122503       break;
122504     case FTSQUERY_OR:
122505       zBuf = sqlcipher3_mprintf("%zOR ", zBuf);
122506       break;
122507   }
122508
122509   if( zBuf ) zBuf = sqlcipher3_mprintf("%z{", zBuf);
122510   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
122511   if( zBuf ) zBuf = sqlcipher3_mprintf("%z} {", zBuf);
122512
122513   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
122514   if( zBuf ) zBuf = sqlcipher3_mprintf("%z}", zBuf);
122515
122516   return zBuf;
122517 }
122518
122519 /*
122520 ** This is the implementation of a scalar SQL function used to test the 
122521 ** expression parser. It should be called as follows:
122522 **
122523 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
122524 **
122525 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
122526 ** to parse the query expression (see README.tokenizers). The second argument
122527 ** is the query expression to parse. Each subsequent argument is the name
122528 ** of a column of the fts3 table that the query expression may refer to.
122529 ** For example:
122530 **
122531 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
122532 */
122533 static void fts3ExprTest(
122534   sqlcipher3_context *context,
122535   int argc,
122536   sqlcipher3_value **argv
122537 ){
122538   sqlcipher3_tokenizer_module const *pModule = 0;
122539   sqlcipher3_tokenizer *pTokenizer = 0;
122540   int rc;
122541   char **azCol = 0;
122542   const char *zExpr;
122543   int nExpr;
122544   int nCol;
122545   int ii;
122546   Fts3Expr *pExpr;
122547   char *zBuf = 0;
122548   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
122549
122550   if( argc<3 ){
122551     sqlcipher3_result_error(context, 
122552         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
122553     );
122554     return;
122555   }
122556
122557   rc = queryTestTokenizer(db,
122558                           (const char *)sqlcipher3_value_text(argv[0]), &pModule);
122559   if( rc==SQLCIPHER_NOMEM ){
122560     sqlcipher3_result_error_nomem(context);
122561     goto exprtest_out;
122562   }else if( !pModule ){
122563     sqlcipher3_result_error(context, "No such tokenizer module", -1);
122564     goto exprtest_out;
122565   }
122566
122567   rc = pModule->xCreate(0, 0, &pTokenizer);
122568   assert( rc==SQLCIPHER_NOMEM || rc==SQLCIPHER_OK );
122569   if( rc==SQLCIPHER_NOMEM ){
122570     sqlcipher3_result_error_nomem(context);
122571     goto exprtest_out;
122572   }
122573   pTokenizer->pModule = pModule;
122574
122575   zExpr = (const char *)sqlcipher3_value_text(argv[1]);
122576   nExpr = sqlcipher3_value_bytes(argv[1]);
122577   nCol = argc-2;
122578   azCol = (char **)sqlcipher3_malloc(nCol*sizeof(char *));
122579   if( !azCol ){
122580     sqlcipher3_result_error_nomem(context);
122581     goto exprtest_out;
122582   }
122583   for(ii=0; ii<nCol; ii++){
122584     azCol[ii] = (char *)sqlcipher3_value_text(argv[ii+2]);
122585   }
122586
122587   rc = sqlcipher3Fts3ExprParse(
122588       pTokenizer, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
122589   );
122590   if( rc!=SQLCIPHER_OK && rc!=SQLCIPHER_NOMEM ){
122591     sqlcipher3_result_error(context, "Error parsing expression", -1);
122592   }else if( rc==SQLCIPHER_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
122593     sqlcipher3_result_error_nomem(context);
122594   }else{
122595     sqlcipher3_result_text(context, zBuf, -1, SQLCIPHER_TRANSIENT);
122596     sqlcipher3_free(zBuf);
122597   }
122598
122599   sqlcipher3Fts3ExprFree(pExpr);
122600
122601 exprtest_out:
122602   if( pModule && pTokenizer ){
122603     rc = pModule->xDestroy(pTokenizer);
122604   }
122605   sqlcipher3_free(azCol);
122606 }
122607
122608 /*
122609 ** Register the query expression parser test function fts3_exprtest() 
122610 ** with database connection db. 
122611 */
122612 SQLCIPHER_PRIVATE int sqlcipher3Fts3ExprInitTestInterface(sqlcipher3* db){
122613   return sqlcipher3_create_function(
122614       db, "fts3_exprtest", -1, SQLCIPHER_UTF8, 0, fts3ExprTest, 0, 0
122615   );
122616 }
122617
122618 #endif
122619 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
122620
122621 /************** End of fts3_expr.c *******************************************/
122622 /************** Begin file fts3_hash.c ***************************************/
122623 /*
122624 ** 2001 September 22
122625 **
122626 ** The author disclaims copyright to this source code.  In place of
122627 ** a legal notice, here is a blessing:
122628 **
122629 **    May you do good and not evil.
122630 **    May you find forgiveness for yourself and forgive others.
122631 **    May you share freely, never taking more than you give.
122632 **
122633 *************************************************************************
122634 ** This is the implementation of generic hash-tables used in SQLite.
122635 ** We've modified it slightly to serve as a standalone hash table
122636 ** implementation for the full-text indexing module.
122637 */
122638
122639 /*
122640 ** The code in this file is only compiled if:
122641 **
122642 **     * The FTS3 module is being built as an extension
122643 **       (in which case SQLCIPHER_CORE is not defined), or
122644 **
122645 **     * The FTS3 module is being built into the core of
122646 **       SQLite (in which case SQLCIPHER_ENABLE_FTS3 is defined).
122647 */
122648 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
122649
122650 /* #include <assert.h> */
122651 /* #include <stdlib.h> */
122652 /* #include <string.h> */
122653
122654
122655 /*
122656 ** Malloc and Free functions
122657 */
122658 static void *fts3HashMalloc(int n){
122659   void *p = sqlcipher3_malloc(n);
122660   if( p ){
122661     memset(p, 0, n);
122662   }
122663   return p;
122664 }
122665 static void fts3HashFree(void *p){
122666   sqlcipher3_free(p);
122667 }
122668
122669 /* Turn bulk memory into a hash table object by initializing the
122670 ** fields of the Hash structure.
122671 **
122672 ** "pNew" is a pointer to the hash table that is to be initialized.
122673 ** keyClass is one of the constants 
122674 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
122675 ** determines what kind of key the hash table will use.  "copyKey" is
122676 ** true if the hash table should make its own private copy of keys and
122677 ** false if it should just use the supplied pointer.
122678 */
122679 SQLCIPHER_PRIVATE void sqlcipher3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
122680   assert( pNew!=0 );
122681   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
122682   pNew->keyClass = keyClass;
122683   pNew->copyKey = copyKey;
122684   pNew->first = 0;
122685   pNew->count = 0;
122686   pNew->htsize = 0;
122687   pNew->ht = 0;
122688 }
122689
122690 /* Remove all entries from a hash table.  Reclaim all memory.
122691 ** Call this routine to delete a hash table or to reset a hash table
122692 ** to the empty state.
122693 */
122694 SQLCIPHER_PRIVATE void sqlcipher3Fts3HashClear(Fts3Hash *pH){
122695   Fts3HashElem *elem;         /* For looping over all elements of the table */
122696
122697   assert( pH!=0 );
122698   elem = pH->first;
122699   pH->first = 0;
122700   fts3HashFree(pH->ht);
122701   pH->ht = 0;
122702   pH->htsize = 0;
122703   while( elem ){
122704     Fts3HashElem *next_elem = elem->next;
122705     if( pH->copyKey && elem->pKey ){
122706       fts3HashFree(elem->pKey);
122707     }
122708     fts3HashFree(elem);
122709     elem = next_elem;
122710   }
122711   pH->count = 0;
122712 }
122713
122714 /*
122715 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
122716 */
122717 static int fts3StrHash(const void *pKey, int nKey){
122718   const char *z = (const char *)pKey;
122719   int h = 0;
122720   if( nKey<=0 ) nKey = (int) strlen(z);
122721   while( nKey > 0  ){
122722     h = (h<<3) ^ h ^ *z++;
122723     nKey--;
122724   }
122725   return h & 0x7fffffff;
122726 }
122727 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
122728   if( n1!=n2 ) return 1;
122729   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
122730 }
122731
122732 /*
122733 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
122734 */
122735 static int fts3BinHash(const void *pKey, int nKey){
122736   int h = 0;
122737   const char *z = (const char *)pKey;
122738   while( nKey-- > 0 ){
122739     h = (h<<3) ^ h ^ *(z++);
122740   }
122741   return h & 0x7fffffff;
122742 }
122743 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
122744   if( n1!=n2 ) return 1;
122745   return memcmp(pKey1,pKey2,n1);
122746 }
122747
122748 /*
122749 ** Return a pointer to the appropriate hash function given the key class.
122750 **
122751 ** The C syntax in this function definition may be unfamilar to some 
122752 ** programmers, so we provide the following additional explanation:
122753 **
122754 ** The name of the function is "ftsHashFunction".  The function takes a
122755 ** single parameter "keyClass".  The return value of ftsHashFunction()
122756 ** is a pointer to another function.  Specifically, the return value
122757 ** of ftsHashFunction() is a pointer to a function that takes two parameters
122758 ** with types "const void*" and "int" and returns an "int".
122759 */
122760 static int (*ftsHashFunction(int keyClass))(const void*,int){
122761   if( keyClass==FTS3_HASH_STRING ){
122762     return &fts3StrHash;
122763   }else{
122764     assert( keyClass==FTS3_HASH_BINARY );
122765     return &fts3BinHash;
122766   }
122767 }
122768
122769 /*
122770 ** Return a pointer to the appropriate hash function given the key class.
122771 **
122772 ** For help in interpreted the obscure C code in the function definition,
122773 ** see the header comment on the previous function.
122774 */
122775 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
122776   if( keyClass==FTS3_HASH_STRING ){
122777     return &fts3StrCompare;
122778   }else{
122779     assert( keyClass==FTS3_HASH_BINARY );
122780     return &fts3BinCompare;
122781   }
122782 }
122783
122784 /* Link an element into the hash table
122785 */
122786 static void fts3HashInsertElement(
122787   Fts3Hash *pH,            /* The complete hash table */
122788   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
122789   Fts3HashElem *pNew       /* The element to be inserted */
122790 ){
122791   Fts3HashElem *pHead;     /* First element already in pEntry */
122792   pHead = pEntry->chain;
122793   if( pHead ){
122794     pNew->next = pHead;
122795     pNew->prev = pHead->prev;
122796     if( pHead->prev ){ pHead->prev->next = pNew; }
122797     else             { pH->first = pNew; }
122798     pHead->prev = pNew;
122799   }else{
122800     pNew->next = pH->first;
122801     if( pH->first ){ pH->first->prev = pNew; }
122802     pNew->prev = 0;
122803     pH->first = pNew;
122804   }
122805   pEntry->count++;
122806   pEntry->chain = pNew;
122807 }
122808
122809
122810 /* Resize the hash table so that it cantains "new_size" buckets.
122811 ** "new_size" must be a power of 2.  The hash table might fail 
122812 ** to resize if sqlcipherMalloc() fails.
122813 **
122814 ** Return non-zero if a memory allocation error occurs.
122815 */
122816 static int fts3Rehash(Fts3Hash *pH, int new_size){
122817   struct _fts3ht *new_ht;          /* The new hash table */
122818   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
122819   int (*xHash)(const void*,int);   /* The hash function */
122820
122821   assert( (new_size & (new_size-1))==0 );
122822   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
122823   if( new_ht==0 ) return 1;
122824   fts3HashFree(pH->ht);
122825   pH->ht = new_ht;
122826   pH->htsize = new_size;
122827   xHash = ftsHashFunction(pH->keyClass);
122828   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
122829     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
122830     next_elem = elem->next;
122831     fts3HashInsertElement(pH, &new_ht[h], elem);
122832   }
122833   return 0;
122834 }
122835
122836 /* This function (for internal use only) locates an element in an
122837 ** hash table that matches the given key.  The hash for this key has
122838 ** already been computed and is passed as the 4th parameter.
122839 */
122840 static Fts3HashElem *fts3FindElementByHash(
122841   const Fts3Hash *pH, /* The pH to be searched */
122842   const void *pKey,   /* The key we are searching for */
122843   int nKey,
122844   int h               /* The hash for this key. */
122845 ){
122846   Fts3HashElem *elem;            /* Used to loop thru the element list */
122847   int count;                     /* Number of elements left to test */
122848   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
122849
122850   if( pH->ht ){
122851     struct _fts3ht *pEntry = &pH->ht[h];
122852     elem = pEntry->chain;
122853     count = pEntry->count;
122854     xCompare = ftsCompareFunction(pH->keyClass);
122855     while( count-- && elem ){
122856       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
122857         return elem;
122858       }
122859       elem = elem->next;
122860     }
122861   }
122862   return 0;
122863 }
122864
122865 /* Remove a single entry from the hash table given a pointer to that
122866 ** element and a hash on the element's key.
122867 */
122868 static void fts3RemoveElementByHash(
122869   Fts3Hash *pH,         /* The pH containing "elem" */
122870   Fts3HashElem* elem,   /* The element to be removed from the pH */
122871   int h                 /* Hash value for the element */
122872 ){
122873   struct _fts3ht *pEntry;
122874   if( elem->prev ){
122875     elem->prev->next = elem->next; 
122876   }else{
122877     pH->first = elem->next;
122878   }
122879   if( elem->next ){
122880     elem->next->prev = elem->prev;
122881   }
122882   pEntry = &pH->ht[h];
122883   if( pEntry->chain==elem ){
122884     pEntry->chain = elem->next;
122885   }
122886   pEntry->count--;
122887   if( pEntry->count<=0 ){
122888     pEntry->chain = 0;
122889   }
122890   if( pH->copyKey && elem->pKey ){
122891     fts3HashFree(elem->pKey);
122892   }
122893   fts3HashFree( elem );
122894   pH->count--;
122895   if( pH->count<=0 ){
122896     assert( pH->first==0 );
122897     assert( pH->count==0 );
122898     fts3HashClear(pH);
122899   }
122900 }
122901
122902 SQLCIPHER_PRIVATE Fts3HashElem *sqlcipher3Fts3HashFindElem(
122903   const Fts3Hash *pH, 
122904   const void *pKey, 
122905   int nKey
122906 ){
122907   int h;                          /* A hash on key */
122908   int (*xHash)(const void*,int);  /* The hash function */
122909
122910   if( pH==0 || pH->ht==0 ) return 0;
122911   xHash = ftsHashFunction(pH->keyClass);
122912   assert( xHash!=0 );
122913   h = (*xHash)(pKey,nKey);
122914   assert( (pH->htsize & (pH->htsize-1))==0 );
122915   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
122916 }
122917
122918 /* 
122919 ** Attempt to locate an element of the hash table pH with a key
122920 ** that matches pKey,nKey.  Return the data for this element if it is
122921 ** found, or NULL if there is no match.
122922 */
122923 SQLCIPHER_PRIVATE void *sqlcipher3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
122924   Fts3HashElem *pElem;            /* The element that matches key (if any) */
122925
122926   pElem = sqlcipher3Fts3HashFindElem(pH, pKey, nKey);
122927   return pElem ? pElem->data : 0;
122928 }
122929
122930 /* Insert an element into the hash table pH.  The key is pKey,nKey
122931 ** and the data is "data".
122932 **
122933 ** If no element exists with a matching key, then a new
122934 ** element is created.  A copy of the key is made if the copyKey
122935 ** flag is set.  NULL is returned.
122936 **
122937 ** If another element already exists with the same key, then the
122938 ** new data replaces the old data and the old data is returned.
122939 ** The key is not copied in this instance.  If a malloc fails, then
122940 ** the new data is returned and the hash table is unchanged.
122941 **
122942 ** If the "data" parameter to this function is NULL, then the
122943 ** element corresponding to "key" is removed from the hash table.
122944 */
122945 SQLCIPHER_PRIVATE void *sqlcipher3Fts3HashInsert(
122946   Fts3Hash *pH,        /* The hash table to insert into */
122947   const void *pKey,    /* The key */
122948   int nKey,            /* Number of bytes in the key */
122949   void *data           /* The data */
122950 ){
122951   int hraw;                 /* Raw hash value of the key */
122952   int h;                    /* the hash of the key modulo hash table size */
122953   Fts3HashElem *elem;       /* Used to loop thru the element list */
122954   Fts3HashElem *new_elem;   /* New element added to the pH */
122955   int (*xHash)(const void*,int);  /* The hash function */
122956
122957   assert( pH!=0 );
122958   xHash = ftsHashFunction(pH->keyClass);
122959   assert( xHash!=0 );
122960   hraw = (*xHash)(pKey, nKey);
122961   assert( (pH->htsize & (pH->htsize-1))==0 );
122962   h = hraw & (pH->htsize-1);
122963   elem = fts3FindElementByHash(pH,pKey,nKey,h);
122964   if( elem ){
122965     void *old_data = elem->data;
122966     if( data==0 ){
122967       fts3RemoveElementByHash(pH,elem,h);
122968     }else{
122969       elem->data = data;
122970     }
122971     return old_data;
122972   }
122973   if( data==0 ) return 0;
122974   if( (pH->htsize==0 && fts3Rehash(pH,8))
122975    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
122976   ){
122977     pH->count = 0;
122978     return data;
122979   }
122980   assert( pH->htsize>0 );
122981   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
122982   if( new_elem==0 ) return data;
122983   if( pH->copyKey && pKey!=0 ){
122984     new_elem->pKey = fts3HashMalloc( nKey );
122985     if( new_elem->pKey==0 ){
122986       fts3HashFree(new_elem);
122987       return data;
122988     }
122989     memcpy((void*)new_elem->pKey, pKey, nKey);
122990   }else{
122991     new_elem->pKey = (void*)pKey;
122992   }
122993   new_elem->nKey = nKey;
122994   pH->count++;
122995   assert( pH->htsize>0 );
122996   assert( (pH->htsize & (pH->htsize-1))==0 );
122997   h = hraw & (pH->htsize-1);
122998   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
122999   new_elem->data = data;
123000   return 0;
123001 }
123002
123003 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
123004
123005 /************** End of fts3_hash.c *******************************************/
123006 /************** Begin file fts3_porter.c *************************************/
123007 /*
123008 ** 2006 September 30
123009 **
123010 ** The author disclaims copyright to this source code.  In place of
123011 ** a legal notice, here is a blessing:
123012 **
123013 **    May you do good and not evil.
123014 **    May you find forgiveness for yourself and forgive others.
123015 **    May you share freely, never taking more than you give.
123016 **
123017 *************************************************************************
123018 ** Implementation of the full-text-search tokenizer that implements
123019 ** a Porter stemmer.
123020 */
123021
123022 /*
123023 ** The code in this file is only compiled if:
123024 **
123025 **     * The FTS3 module is being built as an extension
123026 **       (in which case SQLCIPHER_CORE is not defined), or
123027 **
123028 **     * The FTS3 module is being built into the core of
123029 **       SQLite (in which case SQLCIPHER_ENABLE_FTS3 is defined).
123030 */
123031 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
123032
123033 /* #include <assert.h> */
123034 /* #include <stdlib.h> */
123035 /* #include <stdio.h> */
123036 /* #include <string.h> */
123037
123038
123039 /*
123040 ** Class derived from sqlcipher3_tokenizer
123041 */
123042 typedef struct porter_tokenizer {
123043   sqlcipher3_tokenizer base;      /* Base class */
123044 } porter_tokenizer;
123045
123046 /*
123047 ** Class derived from sqlit3_tokenizer_cursor
123048 */
123049 typedef struct porter_tokenizer_cursor {
123050   sqlcipher3_tokenizer_cursor base;
123051   const char *zInput;          /* input we are tokenizing */
123052   int nInput;                  /* size of the input */
123053   int iOffset;                 /* current position in zInput */
123054   int iToken;                  /* index of next token to be returned */
123055   char *zToken;                /* storage for current token */
123056   int nAllocated;              /* space allocated to zToken buffer */
123057 } porter_tokenizer_cursor;
123058
123059
123060 /*
123061 ** Create a new tokenizer instance.
123062 */
123063 static int porterCreate(
123064   int argc, const char * const *argv,
123065   sqlcipher3_tokenizer **ppTokenizer
123066 ){
123067   porter_tokenizer *t;
123068
123069   UNUSED_PARAMETER(argc);
123070   UNUSED_PARAMETER(argv);
123071
123072   t = (porter_tokenizer *) sqlcipher3_malloc(sizeof(*t));
123073   if( t==NULL ) return SQLCIPHER_NOMEM;
123074   memset(t, 0, sizeof(*t));
123075   *ppTokenizer = &t->base;
123076   return SQLCIPHER_OK;
123077 }
123078
123079 /*
123080 ** Destroy a tokenizer
123081 */
123082 static int porterDestroy(sqlcipher3_tokenizer *pTokenizer){
123083   sqlcipher3_free(pTokenizer);
123084   return SQLCIPHER_OK;
123085 }
123086
123087 /*
123088 ** Prepare to begin tokenizing a particular string.  The input
123089 ** string to be tokenized is zInput[0..nInput-1].  A cursor
123090 ** used to incrementally tokenize this string is returned in 
123091 ** *ppCursor.
123092 */
123093 static int porterOpen(
123094   sqlcipher3_tokenizer *pTokenizer,         /* The tokenizer */
123095   const char *zInput, int nInput,        /* String to be tokenized */
123096   sqlcipher3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
123097 ){
123098   porter_tokenizer_cursor *c;
123099
123100   UNUSED_PARAMETER(pTokenizer);
123101
123102   c = (porter_tokenizer_cursor *) sqlcipher3_malloc(sizeof(*c));
123103   if( c==NULL ) return SQLCIPHER_NOMEM;
123104
123105   c->zInput = zInput;
123106   if( zInput==0 ){
123107     c->nInput = 0;
123108   }else if( nInput<0 ){
123109     c->nInput = (int)strlen(zInput);
123110   }else{
123111     c->nInput = nInput;
123112   }
123113   c->iOffset = 0;                 /* start tokenizing at the beginning */
123114   c->iToken = 0;
123115   c->zToken = NULL;               /* no space allocated, yet. */
123116   c->nAllocated = 0;
123117
123118   *ppCursor = &c->base;
123119   return SQLCIPHER_OK;
123120 }
123121
123122 /*
123123 ** Close a tokenization cursor previously opened by a call to
123124 ** porterOpen() above.
123125 */
123126 static int porterClose(sqlcipher3_tokenizer_cursor *pCursor){
123127   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
123128   sqlcipher3_free(c->zToken);
123129   sqlcipher3_free(c);
123130   return SQLCIPHER_OK;
123131 }
123132 /*
123133 ** Vowel or consonant
123134 */
123135 static const char cType[] = {
123136    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
123137    1, 1, 1, 2, 1
123138 };
123139
123140 /*
123141 ** isConsonant() and isVowel() determine if their first character in
123142 ** the string they point to is a consonant or a vowel, according
123143 ** to Porter ruls.  
123144 **
123145 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
123146 ** 'Y' is a consonant unless it follows another consonant,
123147 ** in which case it is a vowel.
123148 **
123149 ** In these routine, the letters are in reverse order.  So the 'y' rule
123150 ** is that 'y' is a consonant unless it is followed by another
123151 ** consonent.
123152 */
123153 static int isVowel(const char*);
123154 static int isConsonant(const char *z){
123155   int j;
123156   char x = *z;
123157   if( x==0 ) return 0;
123158   assert( x>='a' && x<='z' );
123159   j = cType[x-'a'];
123160   if( j<2 ) return j;
123161   return z[1]==0 || isVowel(z + 1);
123162 }
123163 static int isVowel(const char *z){
123164   int j;
123165   char x = *z;
123166   if( x==0 ) return 0;
123167   assert( x>='a' && x<='z' );
123168   j = cType[x-'a'];
123169   if( j<2 ) return 1-j;
123170   return isConsonant(z + 1);
123171 }
123172
123173 /*
123174 ** Let any sequence of one or more vowels be represented by V and let
123175 ** C be sequence of one or more consonants.  Then every word can be
123176 ** represented as:
123177 **
123178 **           [C] (VC){m} [V]
123179 **
123180 ** In prose:  A word is an optional consonant followed by zero or
123181 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
123182 ** number of vowel consonant pairs.  This routine computes the value
123183 ** of m for the first i bytes of a word.
123184 **
123185 ** Return true if the m-value for z is 1 or more.  In other words,
123186 ** return true if z contains at least one vowel that is followed
123187 ** by a consonant.
123188 **
123189 ** In this routine z[] is in reverse order.  So we are really looking
123190 ** for an instance of of a consonant followed by a vowel.
123191 */
123192 static int m_gt_0(const char *z){
123193   while( isVowel(z) ){ z++; }
123194   if( *z==0 ) return 0;
123195   while( isConsonant(z) ){ z++; }
123196   return *z!=0;
123197 }
123198
123199 /* Like mgt0 above except we are looking for a value of m which is
123200 ** exactly 1
123201 */
123202 static int m_eq_1(const char *z){
123203   while( isVowel(z) ){ z++; }
123204   if( *z==0 ) return 0;
123205   while( isConsonant(z) ){ z++; }
123206   if( *z==0 ) return 0;
123207   while( isVowel(z) ){ z++; }
123208   if( *z==0 ) return 1;
123209   while( isConsonant(z) ){ z++; }
123210   return *z==0;
123211 }
123212
123213 /* Like mgt0 above except we are looking for a value of m>1 instead
123214 ** or m>0
123215 */
123216 static int m_gt_1(const char *z){
123217   while( isVowel(z) ){ z++; }
123218   if( *z==0 ) return 0;
123219   while( isConsonant(z) ){ z++; }
123220   if( *z==0 ) return 0;
123221   while( isVowel(z) ){ z++; }
123222   if( *z==0 ) return 0;
123223   while( isConsonant(z) ){ z++; }
123224   return *z!=0;
123225 }
123226
123227 /*
123228 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
123229 */
123230 static int hasVowel(const char *z){
123231   while( isConsonant(z) ){ z++; }
123232   return *z!=0;
123233 }
123234
123235 /*
123236 ** Return TRUE if the word ends in a double consonant.
123237 **
123238 ** The text is reversed here. So we are really looking at
123239 ** the first two characters of z[].
123240 */
123241 static int doubleConsonant(const char *z){
123242   return isConsonant(z) && z[0]==z[1];
123243 }
123244
123245 /*
123246 ** Return TRUE if the word ends with three letters which
123247 ** are consonant-vowel-consonent and where the final consonant
123248 ** is not 'w', 'x', or 'y'.
123249 **
123250 ** The word is reversed here.  So we are really checking the
123251 ** first three letters and the first one cannot be in [wxy].
123252 */
123253 static int star_oh(const char *z){
123254   return
123255     isConsonant(z) &&
123256     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
123257     isVowel(z+1) &&
123258     isConsonant(z+2);
123259 }
123260
123261 /*
123262 ** If the word ends with zFrom and xCond() is true for the stem
123263 ** of the word that preceeds the zFrom ending, then change the 
123264 ** ending to zTo.
123265 **
123266 ** The input word *pz and zFrom are both in reverse order.  zTo
123267 ** is in normal order. 
123268 **
123269 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
123270 ** match.  Not that TRUE is returned even if xCond() fails and
123271 ** no substitution occurs.
123272 */
123273 static int stem(
123274   char **pz,             /* The word being stemmed (Reversed) */
123275   const char *zFrom,     /* If the ending matches this... (Reversed) */
123276   const char *zTo,       /* ... change the ending to this (not reversed) */
123277   int (*xCond)(const char*)   /* Condition that must be true */
123278 ){
123279   char *z = *pz;
123280   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
123281   if( *zFrom!=0 ) return 0;
123282   if( xCond && !xCond(z) ) return 1;
123283   while( *zTo ){
123284     *(--z) = *(zTo++);
123285   }
123286   *pz = z;
123287   return 1;
123288 }
123289
123290 /*
123291 ** This is the fallback stemmer used when the porter stemmer is
123292 ** inappropriate.  The input word is copied into the output with
123293 ** US-ASCII case folding.  If the input word is too long (more
123294 ** than 20 bytes if it contains no digits or more than 6 bytes if
123295 ** it contains digits) then word is truncated to 20 or 6 bytes
123296 ** by taking 10 or 3 bytes from the beginning and end.
123297 */
123298 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
123299   int i, mx, j;
123300   int hasDigit = 0;
123301   for(i=0; i<nIn; i++){
123302     char c = zIn[i];
123303     if( c>='A' && c<='Z' ){
123304       zOut[i] = c - 'A' + 'a';
123305     }else{
123306       if( c>='0' && c<='9' ) hasDigit = 1;
123307       zOut[i] = c;
123308     }
123309   }
123310   mx = hasDigit ? 3 : 10;
123311   if( nIn>mx*2 ){
123312     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
123313       zOut[j] = zOut[i];
123314     }
123315     i = j;
123316   }
123317   zOut[i] = 0;
123318   *pnOut = i;
123319 }
123320
123321
123322 /*
123323 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
123324 ** zOut is at least big enough to hold nIn bytes.  Write the actual
123325 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
123326 **
123327 ** Any upper-case characters in the US-ASCII character set ([A-Z])
123328 ** are converted to lower case.  Upper-case UTF characters are
123329 ** unchanged.
123330 **
123331 ** Words that are longer than about 20 bytes are stemmed by retaining
123332 ** a few bytes from the beginning and the end of the word.  If the
123333 ** word contains digits, 3 bytes are taken from the beginning and
123334 ** 3 bytes from the end.  For long words without digits, 10 bytes
123335 ** are taken from each end.  US-ASCII case folding still applies.
123336 ** 
123337 ** If the input word contains not digits but does characters not 
123338 ** in [a-zA-Z] then no stemming is attempted and this routine just 
123339 ** copies the input into the input into the output with US-ASCII
123340 ** case folding.
123341 **
123342 ** Stemming never increases the length of the word.  So there is
123343 ** no chance of overflowing the zOut buffer.
123344 */
123345 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
123346   int i, j;
123347   char zReverse[28];
123348   char *z, *z2;
123349   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
123350     /* The word is too big or too small for the porter stemmer.
123351     ** Fallback to the copy stemmer */
123352     copy_stemmer(zIn, nIn, zOut, pnOut);
123353     return;
123354   }
123355   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
123356     char c = zIn[i];
123357     if( c>='A' && c<='Z' ){
123358       zReverse[j] = c + 'a' - 'A';
123359     }else if( c>='a' && c<='z' ){
123360       zReverse[j] = c;
123361     }else{
123362       /* The use of a character not in [a-zA-Z] means that we fallback
123363       ** to the copy stemmer */
123364       copy_stemmer(zIn, nIn, zOut, pnOut);
123365       return;
123366     }
123367   }
123368   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
123369   z = &zReverse[j+1];
123370
123371
123372   /* Step 1a */
123373   if( z[0]=='s' ){
123374     if(
123375      !stem(&z, "sess", "ss", 0) &&
123376      !stem(&z, "sei", "i", 0)  &&
123377      !stem(&z, "ss", "ss", 0)
123378     ){
123379       z++;
123380     }
123381   }
123382
123383   /* Step 1b */  
123384   z2 = z;
123385   if( stem(&z, "dee", "ee", m_gt_0) ){
123386     /* Do nothing.  The work was all in the test */
123387   }else if( 
123388      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
123389       && z!=z2
123390   ){
123391      if( stem(&z, "ta", "ate", 0) ||
123392          stem(&z, "lb", "ble", 0) ||
123393          stem(&z, "zi", "ize", 0) ){
123394        /* Do nothing.  The work was all in the test */
123395      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
123396        z++;
123397      }else if( m_eq_1(z) && star_oh(z) ){
123398        *(--z) = 'e';
123399      }
123400   }
123401
123402   /* Step 1c */
123403   if( z[0]=='y' && hasVowel(z+1) ){
123404     z[0] = 'i';
123405   }
123406
123407   /* Step 2 */
123408   switch( z[1] ){
123409    case 'a':
123410      stem(&z, "lanoita", "ate", m_gt_0) ||
123411      stem(&z, "lanoit", "tion", m_gt_0);
123412      break;
123413    case 'c':
123414      stem(&z, "icne", "ence", m_gt_0) ||
123415      stem(&z, "icna", "ance", m_gt_0);
123416      break;
123417    case 'e':
123418      stem(&z, "rezi", "ize", m_gt_0);
123419      break;
123420    case 'g':
123421      stem(&z, "igol", "log", m_gt_0);
123422      break;
123423    case 'l':
123424      stem(&z, "ilb", "ble", m_gt_0) ||
123425      stem(&z, "illa", "al", m_gt_0) ||
123426      stem(&z, "iltne", "ent", m_gt_0) ||
123427      stem(&z, "ile", "e", m_gt_0) ||
123428      stem(&z, "ilsuo", "ous", m_gt_0);
123429      break;
123430    case 'o':
123431      stem(&z, "noitazi", "ize", m_gt_0) ||
123432      stem(&z, "noita", "ate", m_gt_0) ||
123433      stem(&z, "rota", "ate", m_gt_0);
123434      break;
123435    case 's':
123436      stem(&z, "msila", "al", m_gt_0) ||
123437      stem(&z, "ssenevi", "ive", m_gt_0) ||
123438      stem(&z, "ssenluf", "ful", m_gt_0) ||
123439      stem(&z, "ssensuo", "ous", m_gt_0);
123440      break;
123441    case 't':
123442      stem(&z, "itila", "al", m_gt_0) ||
123443      stem(&z, "itivi", "ive", m_gt_0) ||
123444      stem(&z, "itilib", "ble", m_gt_0);
123445      break;
123446   }
123447
123448   /* Step 3 */
123449   switch( z[0] ){
123450    case 'e':
123451      stem(&z, "etaci", "ic", m_gt_0) ||
123452      stem(&z, "evita", "", m_gt_0)   ||
123453      stem(&z, "ezila", "al", m_gt_0);
123454      break;
123455    case 'i':
123456      stem(&z, "itici", "ic", m_gt_0);
123457      break;
123458    case 'l':
123459      stem(&z, "laci", "ic", m_gt_0) ||
123460      stem(&z, "luf", "", m_gt_0);
123461      break;
123462    case 's':
123463      stem(&z, "ssen", "", m_gt_0);
123464      break;
123465   }
123466
123467   /* Step 4 */
123468   switch( z[1] ){
123469    case 'a':
123470      if( z[0]=='l' && m_gt_1(z+2) ){
123471        z += 2;
123472      }
123473      break;
123474    case 'c':
123475      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
123476        z += 4;
123477      }
123478      break;
123479    case 'e':
123480      if( z[0]=='r' && m_gt_1(z+2) ){
123481        z += 2;
123482      }
123483      break;
123484    case 'i':
123485      if( z[0]=='c' && m_gt_1(z+2) ){
123486        z += 2;
123487      }
123488      break;
123489    case 'l':
123490      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
123491        z += 4;
123492      }
123493      break;
123494    case 'n':
123495      if( z[0]=='t' ){
123496        if( z[2]=='a' ){
123497          if( m_gt_1(z+3) ){
123498            z += 3;
123499          }
123500        }else if( z[2]=='e' ){
123501          stem(&z, "tneme", "", m_gt_1) ||
123502          stem(&z, "tnem", "", m_gt_1) ||
123503          stem(&z, "tne", "", m_gt_1);
123504        }
123505      }
123506      break;
123507    case 'o':
123508      if( z[0]=='u' ){
123509        if( m_gt_1(z+2) ){
123510          z += 2;
123511        }
123512      }else if( z[3]=='s' || z[3]=='t' ){
123513        stem(&z, "noi", "", m_gt_1);
123514      }
123515      break;
123516    case 's':
123517      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
123518        z += 3;
123519      }
123520      break;
123521    case 't':
123522      stem(&z, "eta", "", m_gt_1) ||
123523      stem(&z, "iti", "", m_gt_1);
123524      break;
123525    case 'u':
123526      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
123527        z += 3;
123528      }
123529      break;
123530    case 'v':
123531    case 'z':
123532      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
123533        z += 3;
123534      }
123535      break;
123536   }
123537
123538   /* Step 5a */
123539   if( z[0]=='e' ){
123540     if( m_gt_1(z+1) ){
123541       z++;
123542     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
123543       z++;
123544     }
123545   }
123546
123547   /* Step 5b */
123548   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
123549     z++;
123550   }
123551
123552   /* z[] is now the stemmed word in reverse order.  Flip it back
123553   ** around into forward order and return.
123554   */
123555   *pnOut = i = (int)strlen(z);
123556   zOut[i] = 0;
123557   while( *z ){
123558     zOut[--i] = *(z++);
123559   }
123560 }
123561
123562 /*
123563 ** Characters that can be part of a token.  We assume any character
123564 ** whose value is greater than 0x80 (any UTF character) can be
123565 ** part of a token.  In other words, delimiters all must have
123566 ** values of 0x7f or lower.
123567 */
123568 static const char porterIdChar[] = {
123569 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
123570     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
123571     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
123572     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
123573     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
123574     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
123575 };
123576 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
123577
123578 /*
123579 ** Extract the next token from a tokenization cursor.  The cursor must
123580 ** have been opened by a prior call to porterOpen().
123581 */
123582 static int porterNext(
123583   sqlcipher3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
123584   const char **pzToken,               /* OUT: *pzToken is the token text */
123585   int *pnBytes,                       /* OUT: Number of bytes in token */
123586   int *piStartOffset,                 /* OUT: Starting offset of token */
123587   int *piEndOffset,                   /* OUT: Ending offset of token */
123588   int *piPosition                     /* OUT: Position integer of token */
123589 ){
123590   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
123591   const char *z = c->zInput;
123592
123593   while( c->iOffset<c->nInput ){
123594     int iStartOffset, ch;
123595
123596     /* Scan past delimiter characters */
123597     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
123598       c->iOffset++;
123599     }
123600
123601     /* Count non-delimiter characters. */
123602     iStartOffset = c->iOffset;
123603     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
123604       c->iOffset++;
123605     }
123606
123607     if( c->iOffset>iStartOffset ){
123608       int n = c->iOffset-iStartOffset;
123609       if( n>c->nAllocated ){
123610         char *pNew;
123611         c->nAllocated = n+20;
123612         pNew = sqlcipher3_realloc(c->zToken, c->nAllocated);
123613         if( !pNew ) return SQLCIPHER_NOMEM;
123614         c->zToken = pNew;
123615       }
123616       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
123617       *pzToken = c->zToken;
123618       *piStartOffset = iStartOffset;
123619       *piEndOffset = c->iOffset;
123620       *piPosition = c->iToken++;
123621       return SQLCIPHER_OK;
123622     }
123623   }
123624   return SQLCIPHER_DONE;
123625 }
123626
123627 /*
123628 ** The set of routines that implement the porter-stemmer tokenizer
123629 */
123630 static const sqlcipher3_tokenizer_module porterTokenizerModule = {
123631   0,
123632   porterCreate,
123633   porterDestroy,
123634   porterOpen,
123635   porterClose,
123636   porterNext,
123637 };
123638
123639 /*
123640 ** Allocate a new porter tokenizer.  Return a pointer to the new
123641 ** tokenizer in *ppModule
123642 */
123643 SQLCIPHER_PRIVATE void sqlcipher3Fts3PorterTokenizerModule(
123644   sqlcipher3_tokenizer_module const**ppModule
123645 ){
123646   *ppModule = &porterTokenizerModule;
123647 }
123648
123649 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
123650
123651 /************** End of fts3_porter.c *****************************************/
123652 /************** Begin file fts3_tokenizer.c **********************************/
123653 /*
123654 ** 2007 June 22
123655 **
123656 ** The author disclaims copyright to this source code.  In place of
123657 ** a legal notice, here is a blessing:
123658 **
123659 **    May you do good and not evil.
123660 **    May you find forgiveness for yourself and forgive others.
123661 **    May you share freely, never taking more than you give.
123662 **
123663 ******************************************************************************
123664 **
123665 ** This is part of an SQLite module implementing full-text search.
123666 ** This particular file implements the generic tokenizer interface.
123667 */
123668
123669 /*
123670 ** The code in this file is only compiled if:
123671 **
123672 **     * The FTS3 module is being built as an extension
123673 **       (in which case SQLCIPHER_CORE is not defined), or
123674 **
123675 **     * The FTS3 module is being built into the core of
123676 **       SQLite (in which case SQLCIPHER_ENABLE_FTS3 is defined).
123677 */
123678 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
123679
123680 /* #include <assert.h> */
123681 /* #include <string.h> */
123682
123683 /*
123684 ** Implementation of the SQL scalar function for accessing the underlying 
123685 ** hash table. This function may be called as follows:
123686 **
123687 **   SELECT <function-name>(<key-name>);
123688 **   SELECT <function-name>(<key-name>, <pointer>);
123689 **
123690 ** where <function-name> is the name passed as the second argument
123691 ** to the sqlcipher3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
123692 **
123693 ** If the <pointer> argument is specified, it must be a blob value
123694 ** containing a pointer to be stored as the hash data corresponding
123695 ** to the string <key-name>. If <pointer> is not specified, then
123696 ** the string <key-name> must already exist in the has table. Otherwise,
123697 ** an error is returned.
123698 **
123699 ** Whether or not the <pointer> argument is specified, the value returned
123700 ** is a blob containing the pointer stored as the hash data corresponding
123701 ** to string <key-name> (after the hash-table is updated, if applicable).
123702 */
123703 static void scalarFunc(
123704   sqlcipher3_context *context,
123705   int argc,
123706   sqlcipher3_value **argv
123707 ){
123708   Fts3Hash *pHash;
123709   void *pPtr = 0;
123710   const unsigned char *zName;
123711   int nName;
123712
123713   assert( argc==1 || argc==2 );
123714
123715   pHash = (Fts3Hash *)sqlcipher3_user_data(context);
123716
123717   zName = sqlcipher3_value_text(argv[0]);
123718   nName = sqlcipher3_value_bytes(argv[0])+1;
123719
123720   if( argc==2 ){
123721     void *pOld;
123722     int n = sqlcipher3_value_bytes(argv[1]);
123723     if( n!=sizeof(pPtr) ){
123724       sqlcipher3_result_error(context, "argument type mismatch", -1);
123725       return;
123726     }
123727     pPtr = *(void **)sqlcipher3_value_blob(argv[1]);
123728     pOld = sqlcipher3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
123729     if( pOld==pPtr ){
123730       sqlcipher3_result_error(context, "out of memory", -1);
123731       return;
123732     }
123733   }else{
123734     pPtr = sqlcipher3Fts3HashFind(pHash, zName, nName);
123735     if( !pPtr ){
123736       char *zErr = sqlcipher3_mprintf("unknown tokenizer: %s", zName);
123737       sqlcipher3_result_error(context, zErr, -1);
123738       sqlcipher3_free(zErr);
123739       return;
123740     }
123741   }
123742
123743   sqlcipher3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLCIPHER_TRANSIENT);
123744 }
123745
123746 SQLCIPHER_PRIVATE int sqlcipher3Fts3IsIdChar(char c){
123747   static const char isFtsIdChar[] = {
123748       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
123749       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
123750       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
123751       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
123752       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
123753       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
123754       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
123755       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
123756   };
123757   return (c&0x80 || isFtsIdChar[(int)(c)]);
123758 }
123759
123760 SQLCIPHER_PRIVATE const char *sqlcipher3Fts3NextToken(const char *zStr, int *pn){
123761   const char *z1;
123762   const char *z2 = 0;
123763
123764   /* Find the start of the next token. */
123765   z1 = zStr;
123766   while( z2==0 ){
123767     char c = *z1;
123768     switch( c ){
123769       case '\0': return 0;        /* No more tokens here */
123770       case '\'':
123771       case '"':
123772       case '`': {
123773         z2 = z1;
123774         while( *++z2 && (*z2!=c || *++z2==c) );
123775         break;
123776       }
123777       case '[':
123778         z2 = &z1[1];
123779         while( *z2 && z2[0]!=']' ) z2++;
123780         if( *z2 ) z2++;
123781         break;
123782
123783       default:
123784         if( sqlcipher3Fts3IsIdChar(*z1) ){
123785           z2 = &z1[1];
123786           while( sqlcipher3Fts3IsIdChar(*z2) ) z2++;
123787         }else{
123788           z1++;
123789         }
123790     }
123791   }
123792
123793   *pn = (int)(z2-z1);
123794   return z1;
123795 }
123796
123797 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitTokenizer(
123798   Fts3Hash *pHash,                /* Tokenizer hash table */
123799   const char *zArg,               /* Tokenizer name */
123800   sqlcipher3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
123801   char **pzErr                    /* OUT: Set to malloced error message */
123802 ){
123803   int rc;
123804   char *z = (char *)zArg;
123805   int n = 0;
123806   char *zCopy;
123807   char *zEnd;                     /* Pointer to nul-term of zCopy */
123808   sqlcipher3_tokenizer_module *m;
123809
123810   zCopy = sqlcipher3_mprintf("%s", zArg);
123811   if( !zCopy ) return SQLCIPHER_NOMEM;
123812   zEnd = &zCopy[strlen(zCopy)];
123813
123814   z = (char *)sqlcipher3Fts3NextToken(zCopy, &n);
123815   z[n] = '\0';
123816   sqlcipher3Fts3Dequote(z);
123817
123818   m = (sqlcipher3_tokenizer_module *)sqlcipher3Fts3HashFind(pHash,z,(int)strlen(z)+1);
123819   if( !m ){
123820     *pzErr = sqlcipher3_mprintf("unknown tokenizer: %s", z);
123821     rc = SQLCIPHER_ERROR;
123822   }else{
123823     char const **aArg = 0;
123824     int iArg = 0;
123825     z = &z[n+1];
123826     while( z<zEnd && (NULL!=(z = (char *)sqlcipher3Fts3NextToken(z, &n))) ){
123827       int nNew = sizeof(char *)*(iArg+1);
123828       char const **aNew = (const char **)sqlcipher3_realloc((void *)aArg, nNew);
123829       if( !aNew ){
123830         sqlcipher3_free(zCopy);
123831         sqlcipher3_free((void *)aArg);
123832         return SQLCIPHER_NOMEM;
123833       }
123834       aArg = aNew;
123835       aArg[iArg++] = z;
123836       z[n] = '\0';
123837       sqlcipher3Fts3Dequote(z);
123838       z = &z[n+1];
123839     }
123840     rc = m->xCreate(iArg, aArg, ppTok);
123841     assert( rc!=SQLCIPHER_OK || *ppTok );
123842     if( rc!=SQLCIPHER_OK ){
123843       *pzErr = sqlcipher3_mprintf("unknown tokenizer");
123844     }else{
123845       (*ppTok)->pModule = m; 
123846     }
123847     sqlcipher3_free((void *)aArg);
123848   }
123849
123850   sqlcipher3_free(zCopy);
123851   return rc;
123852 }
123853
123854
123855 #ifdef SQLCIPHER_TEST
123856
123857 /* #include <tcl.h> */
123858 /* #include <string.h> */
123859
123860 /*
123861 ** Implementation of a special SQL scalar function for testing tokenizers 
123862 ** designed to be used in concert with the Tcl testing framework. This
123863 ** function must be called with two arguments:
123864 **
123865 **   SELECT <function-name>(<key-name>, <input-string>);
123866 **   SELECT <function-name>(<key-name>, <pointer>);
123867 **
123868 ** where <function-name> is the name passed as the second argument
123869 ** to the sqlcipher3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
123870 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
123871 **
123872 ** The return value is a string that may be interpreted as a Tcl
123873 ** list. For each token in the <input-string>, three elements are
123874 ** added to the returned list. The first is the token position, the 
123875 ** second is the token text (folded, stemmed, etc.) and the third is the
123876 ** substring of <input-string> associated with the token. For example, 
123877 ** using the built-in "simple" tokenizer:
123878 **
123879 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
123880 **
123881 ** will return the string:
123882 **
123883 **   "{0 i I 1 dont don't 2 see see 3 how how}"
123884 **   
123885 */
123886 static void testFunc(
123887   sqlcipher3_context *context,
123888   int argc,
123889   sqlcipher3_value **argv
123890 ){
123891   Fts3Hash *pHash;
123892   sqlcipher3_tokenizer_module *p;
123893   sqlcipher3_tokenizer *pTokenizer = 0;
123894   sqlcipher3_tokenizer_cursor *pCsr = 0;
123895
123896   const char *zErr = 0;
123897
123898   const char *zName;
123899   int nName;
123900   const char *zInput;
123901   int nInput;
123902
123903   const char *zArg = 0;
123904
123905   const char *zToken;
123906   int nToken;
123907   int iStart;
123908   int iEnd;
123909   int iPos;
123910
123911   Tcl_Obj *pRet;
123912
123913   assert( argc==2 || argc==3 );
123914
123915   nName = sqlcipher3_value_bytes(argv[0]);
123916   zName = (const char *)sqlcipher3_value_text(argv[0]);
123917   nInput = sqlcipher3_value_bytes(argv[argc-1]);
123918   zInput = (const char *)sqlcipher3_value_text(argv[argc-1]);
123919
123920   if( argc==3 ){
123921     zArg = (const char *)sqlcipher3_value_text(argv[1]);
123922   }
123923
123924   pHash = (Fts3Hash *)sqlcipher3_user_data(context);
123925   p = (sqlcipher3_tokenizer_module *)sqlcipher3Fts3HashFind(pHash, zName, nName+1);
123926
123927   if( !p ){
123928     char *zErr = sqlcipher3_mprintf("unknown tokenizer: %s", zName);
123929     sqlcipher3_result_error(context, zErr, -1);
123930     sqlcipher3_free(zErr);
123931     return;
123932   }
123933
123934   pRet = Tcl_NewObj();
123935   Tcl_IncrRefCount(pRet);
123936
123937   if( SQLCIPHER_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
123938     zErr = "error in xCreate()";
123939     goto finish;
123940   }
123941   pTokenizer->pModule = p;
123942   if( SQLCIPHER_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
123943     zErr = "error in xOpen()";
123944     goto finish;
123945   }
123946   pCsr->pTokenizer = pTokenizer;
123947
123948   while( SQLCIPHER_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
123949     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
123950     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
123951     zToken = &zInput[iStart];
123952     nToken = iEnd-iStart;
123953     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
123954   }
123955
123956   if( SQLCIPHER_OK!=p->xClose(pCsr) ){
123957     zErr = "error in xClose()";
123958     goto finish;
123959   }
123960   if( SQLCIPHER_OK!=p->xDestroy(pTokenizer) ){
123961     zErr = "error in xDestroy()";
123962     goto finish;
123963   }
123964
123965 finish:
123966   if( zErr ){
123967     sqlcipher3_result_error(context, zErr, -1);
123968   }else{
123969     sqlcipher3_result_text(context, Tcl_GetString(pRet), -1, SQLCIPHER_TRANSIENT);
123970   }
123971   Tcl_DecrRefCount(pRet);
123972 }
123973
123974 static
123975 int registerTokenizer(
123976   sqlcipher3 *db, 
123977   char *zName, 
123978   const sqlcipher3_tokenizer_module *p
123979 ){
123980   int rc;
123981   sqlcipher3_stmt *pStmt;
123982   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
123983
123984   rc = sqlcipher3_prepare_v2(db, zSql, -1, &pStmt, 0);
123985   if( rc!=SQLCIPHER_OK ){
123986     return rc;
123987   }
123988
123989   sqlcipher3_bind_text(pStmt, 1, zName, -1, SQLCIPHER_STATIC);
123990   sqlcipher3_bind_blob(pStmt, 2, &p, sizeof(p), SQLCIPHER_STATIC);
123991   sqlcipher3_step(pStmt);
123992
123993   return sqlcipher3_finalize(pStmt);
123994 }
123995
123996 static
123997 int queryTokenizer(
123998   sqlcipher3 *db, 
123999   char *zName,  
124000   const sqlcipher3_tokenizer_module **pp
124001 ){
124002   int rc;
124003   sqlcipher3_stmt *pStmt;
124004   const char zSql[] = "SELECT fts3_tokenizer(?)";
124005
124006   *pp = 0;
124007   rc = sqlcipher3_prepare_v2(db, zSql, -1, &pStmt, 0);
124008   if( rc!=SQLCIPHER_OK ){
124009     return rc;
124010   }
124011
124012   sqlcipher3_bind_text(pStmt, 1, zName, -1, SQLCIPHER_STATIC);
124013   if( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
124014     if( sqlcipher3_column_type(pStmt, 0)==SQLCIPHER_BLOB ){
124015       memcpy((void *)pp, sqlcipher3_column_blob(pStmt, 0), sizeof(*pp));
124016     }
124017   }
124018
124019   return sqlcipher3_finalize(pStmt);
124020 }
124021
124022 SQLCIPHER_PRIVATE void sqlcipher3Fts3SimpleTokenizerModule(sqlcipher3_tokenizer_module const**ppModule);
124023
124024 /*
124025 ** Implementation of the scalar function fts3_tokenizer_internal_test().
124026 ** This function is used for testing only, it is not included in the
124027 ** build unless SQLCIPHER_TEST is defined.
124028 **
124029 ** The purpose of this is to test that the fts3_tokenizer() function
124030 ** can be used as designed by the C-code in the queryTokenizer and
124031 ** registerTokenizer() functions above. These two functions are repeated
124032 ** in the README.tokenizer file as an example, so it is important to
124033 ** test them.
124034 **
124035 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
124036 ** function with no arguments. An assert() will fail if a problem is
124037 ** detected. i.e.:
124038 **
124039 **     SELECT fts3_tokenizer_internal_test();
124040 **
124041 */
124042 static void intTestFunc(
124043   sqlcipher3_context *context,
124044   int argc,
124045   sqlcipher3_value **argv
124046 ){
124047   int rc;
124048   const sqlcipher3_tokenizer_module *p1;
124049   const sqlcipher3_tokenizer_module *p2;
124050   sqlcipher3 *db = (sqlcipher3 *)sqlcipher3_user_data(context);
124051
124052   UNUSED_PARAMETER(argc);
124053   UNUSED_PARAMETER(argv);
124054
124055   /* Test the query function */
124056   sqlcipher3Fts3SimpleTokenizerModule(&p1);
124057   rc = queryTokenizer(db, "simple", &p2);
124058   assert( rc==SQLCIPHER_OK );
124059   assert( p1==p2 );
124060   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
124061   assert( rc==SQLCIPHER_ERROR );
124062   assert( p2==0 );
124063   assert( 0==strcmp(sqlcipher3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
124064
124065   /* Test the storage function */
124066   rc = registerTokenizer(db, "nosuchtokenizer", p1);
124067   assert( rc==SQLCIPHER_OK );
124068   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
124069   assert( rc==SQLCIPHER_OK );
124070   assert( p2==p1 );
124071
124072   sqlcipher3_result_text(context, "ok", -1, SQLCIPHER_STATIC);
124073 }
124074
124075 #endif
124076
124077 /*
124078 ** Set up SQL objects in database db used to access the contents of
124079 ** the hash table pointed to by argument pHash. The hash table must
124080 ** been initialised to use string keys, and to take a private copy 
124081 ** of the key when a value is inserted. i.e. by a call similar to:
124082 **
124083 **    sqlcipher3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
124084 **
124085 ** This function adds a scalar function (see header comment above
124086 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
124087 ** defined at compilation time, a temporary virtual table (see header 
124088 ** comment above struct HashTableVtab) to the database schema. Both 
124089 ** provide read/write access to the contents of *pHash.
124090 **
124091 ** The third argument to this function, zName, is used as the name
124092 ** of both the scalar and, if created, the virtual table.
124093 */
124094 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitHashTable(
124095   sqlcipher3 *db, 
124096   Fts3Hash *pHash, 
124097   const char *zName
124098 ){
124099   int rc = SQLCIPHER_OK;
124100   void *p = (void *)pHash;
124101   const int any = SQLCIPHER_ANY;
124102
124103 #ifdef SQLCIPHER_TEST
124104   char *zTest = 0;
124105   char *zTest2 = 0;
124106   void *pdb = (void *)db;
124107   zTest = sqlcipher3_mprintf("%s_test", zName);
124108   zTest2 = sqlcipher3_mprintf("%s_internal_test", zName);
124109   if( !zTest || !zTest2 ){
124110     rc = SQLCIPHER_NOMEM;
124111   }
124112 #endif
124113
124114   if( SQLCIPHER_OK==rc ){
124115     rc = sqlcipher3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
124116   }
124117   if( SQLCIPHER_OK==rc ){
124118     rc = sqlcipher3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
124119   }
124120 #ifdef SQLCIPHER_TEST
124121   if( SQLCIPHER_OK==rc ){
124122     rc = sqlcipher3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
124123   }
124124   if( SQLCIPHER_OK==rc ){
124125     rc = sqlcipher3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
124126   }
124127   if( SQLCIPHER_OK==rc ){
124128     rc = sqlcipher3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
124129   }
124130 #endif
124131
124132 #ifdef SQLCIPHER_TEST
124133   sqlcipher3_free(zTest);
124134   sqlcipher3_free(zTest2);
124135 #endif
124136
124137   return rc;
124138 }
124139
124140 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
124141
124142 /************** End of fts3_tokenizer.c **************************************/
124143 /************** Begin file fts3_tokenizer1.c *********************************/
124144 /*
124145 ** 2006 Oct 10
124146 **
124147 ** The author disclaims copyright to this source code.  In place of
124148 ** a legal notice, here is a blessing:
124149 **
124150 **    May you do good and not evil.
124151 **    May you find forgiveness for yourself and forgive others.
124152 **    May you share freely, never taking more than you give.
124153 **
124154 ******************************************************************************
124155 **
124156 ** Implementation of the "simple" full-text-search tokenizer.
124157 */
124158
124159 /*
124160 ** The code in this file is only compiled if:
124161 **
124162 **     * The FTS3 module is being built as an extension
124163 **       (in which case SQLCIPHER_CORE is not defined), or
124164 **
124165 **     * The FTS3 module is being built into the core of
124166 **       SQLite (in which case SQLCIPHER_ENABLE_FTS3 is defined).
124167 */
124168 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
124169
124170 /* #include <assert.h> */
124171 /* #include <stdlib.h> */
124172 /* #include <stdio.h> */
124173 /* #include <string.h> */
124174
124175
124176 typedef struct simple_tokenizer {
124177   sqlcipher3_tokenizer base;
124178   char delim[128];             /* flag ASCII delimiters */
124179 } simple_tokenizer;
124180
124181 typedef struct simple_tokenizer_cursor {
124182   sqlcipher3_tokenizer_cursor base;
124183   const char *pInput;          /* input we are tokenizing */
124184   int nBytes;                  /* size of the input */
124185   int iOffset;                 /* current position in pInput */
124186   int iToken;                  /* index of next token to be returned */
124187   char *pToken;                /* storage for current token */
124188   int nTokenAllocated;         /* space allocated to zToken buffer */
124189 } simple_tokenizer_cursor;
124190
124191
124192 static int simpleDelim(simple_tokenizer *t, unsigned char c){
124193   return c<0x80 && t->delim[c];
124194 }
124195 static int fts3_isalnum(int x){
124196   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
124197 }
124198
124199 /*
124200 ** Create a new tokenizer instance.
124201 */
124202 static int simpleCreate(
124203   int argc, const char * const *argv,
124204   sqlcipher3_tokenizer **ppTokenizer
124205 ){
124206   simple_tokenizer *t;
124207
124208   t = (simple_tokenizer *) sqlcipher3_malloc(sizeof(*t));
124209   if( t==NULL ) return SQLCIPHER_NOMEM;
124210   memset(t, 0, sizeof(*t));
124211
124212   /* TODO(shess) Delimiters need to remain the same from run to run,
124213   ** else we need to reindex.  One solution would be a meta-table to
124214   ** track such information in the database, then we'd only want this
124215   ** information on the initial create.
124216   */
124217   if( argc>1 ){
124218     int i, n = (int)strlen(argv[1]);
124219     for(i=0; i<n; i++){
124220       unsigned char ch = argv[1][i];
124221       /* We explicitly don't support UTF-8 delimiters for now. */
124222       if( ch>=0x80 ){
124223         sqlcipher3_free(t);
124224         return SQLCIPHER_ERROR;
124225       }
124226       t->delim[ch] = 1;
124227     }
124228   } else {
124229     /* Mark non-alphanumeric ASCII characters as delimiters */
124230     int i;
124231     for(i=1; i<0x80; i++){
124232       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
124233     }
124234   }
124235
124236   *ppTokenizer = &t->base;
124237   return SQLCIPHER_OK;
124238 }
124239
124240 /*
124241 ** Destroy a tokenizer
124242 */
124243 static int simpleDestroy(sqlcipher3_tokenizer *pTokenizer){
124244   sqlcipher3_free(pTokenizer);
124245   return SQLCIPHER_OK;
124246 }
124247
124248 /*
124249 ** Prepare to begin tokenizing a particular string.  The input
124250 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
124251 ** used to incrementally tokenize this string is returned in 
124252 ** *ppCursor.
124253 */
124254 static int simpleOpen(
124255   sqlcipher3_tokenizer *pTokenizer,         /* The tokenizer */
124256   const char *pInput, int nBytes,        /* String to be tokenized */
124257   sqlcipher3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
124258 ){
124259   simple_tokenizer_cursor *c;
124260
124261   UNUSED_PARAMETER(pTokenizer);
124262
124263   c = (simple_tokenizer_cursor *) sqlcipher3_malloc(sizeof(*c));
124264   if( c==NULL ) return SQLCIPHER_NOMEM;
124265
124266   c->pInput = pInput;
124267   if( pInput==0 ){
124268     c->nBytes = 0;
124269   }else if( nBytes<0 ){
124270     c->nBytes = (int)strlen(pInput);
124271   }else{
124272     c->nBytes = nBytes;
124273   }
124274   c->iOffset = 0;                 /* start tokenizing at the beginning */
124275   c->iToken = 0;
124276   c->pToken = NULL;               /* no space allocated, yet. */
124277   c->nTokenAllocated = 0;
124278
124279   *ppCursor = &c->base;
124280   return SQLCIPHER_OK;
124281 }
124282
124283 /*
124284 ** Close a tokenization cursor previously opened by a call to
124285 ** simpleOpen() above.
124286 */
124287 static int simpleClose(sqlcipher3_tokenizer_cursor *pCursor){
124288   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
124289   sqlcipher3_free(c->pToken);
124290   sqlcipher3_free(c);
124291   return SQLCIPHER_OK;
124292 }
124293
124294 /*
124295 ** Extract the next token from a tokenization cursor.  The cursor must
124296 ** have been opened by a prior call to simpleOpen().
124297 */
124298 static int simpleNext(
124299   sqlcipher3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
124300   const char **ppToken,               /* OUT: *ppToken is the token text */
124301   int *pnBytes,                       /* OUT: Number of bytes in token */
124302   int *piStartOffset,                 /* OUT: Starting offset of token */
124303   int *piEndOffset,                   /* OUT: Ending offset of token */
124304   int *piPosition                     /* OUT: Position integer of token */
124305 ){
124306   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
124307   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
124308   unsigned char *p = (unsigned char *)c->pInput;
124309
124310   while( c->iOffset<c->nBytes ){
124311     int iStartOffset;
124312
124313     /* Scan past delimiter characters */
124314     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
124315       c->iOffset++;
124316     }
124317
124318     /* Count non-delimiter characters. */
124319     iStartOffset = c->iOffset;
124320     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
124321       c->iOffset++;
124322     }
124323
124324     if( c->iOffset>iStartOffset ){
124325       int i, n = c->iOffset-iStartOffset;
124326       if( n>c->nTokenAllocated ){
124327         char *pNew;
124328         c->nTokenAllocated = n+20;
124329         pNew = sqlcipher3_realloc(c->pToken, c->nTokenAllocated);
124330         if( !pNew ) return SQLCIPHER_NOMEM;
124331         c->pToken = pNew;
124332       }
124333       for(i=0; i<n; i++){
124334         /* TODO(shess) This needs expansion to handle UTF-8
124335         ** case-insensitivity.
124336         */
124337         unsigned char ch = p[iStartOffset+i];
124338         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
124339       }
124340       *ppToken = c->pToken;
124341       *pnBytes = n;
124342       *piStartOffset = iStartOffset;
124343       *piEndOffset = c->iOffset;
124344       *piPosition = c->iToken++;
124345
124346       return SQLCIPHER_OK;
124347     }
124348   }
124349   return SQLCIPHER_DONE;
124350 }
124351
124352 /*
124353 ** The set of routines that implement the simple tokenizer
124354 */
124355 static const sqlcipher3_tokenizer_module simpleTokenizerModule = {
124356   0,
124357   simpleCreate,
124358   simpleDestroy,
124359   simpleOpen,
124360   simpleClose,
124361   simpleNext,
124362 };
124363
124364 /*
124365 ** Allocate a new simple tokenizer.  Return a pointer to the new
124366 ** tokenizer in *ppModule
124367 */
124368 SQLCIPHER_PRIVATE void sqlcipher3Fts3SimpleTokenizerModule(
124369   sqlcipher3_tokenizer_module const**ppModule
124370 ){
124371   *ppModule = &simpleTokenizerModule;
124372 }
124373
124374 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
124375
124376 /************** End of fts3_tokenizer1.c *************************************/
124377 /************** Begin file fts3_write.c **************************************/
124378 /*
124379 ** 2009 Oct 23
124380 **
124381 ** The author disclaims copyright to this source code.  In place of
124382 ** a legal notice, here is a blessing:
124383 **
124384 **    May you do good and not evil.
124385 **    May you find forgiveness for yourself and forgive others.
124386 **    May you share freely, never taking more than you give.
124387 **
124388 ******************************************************************************
124389 **
124390 ** This file is part of the SQLite FTS3 extension module. Specifically,
124391 ** this file contains code to insert, update and delete rows from FTS3
124392 ** tables. It also contains code to merge FTS3 b-tree segments. Some
124393 ** of the sub-routines used to merge segments are also used by the query 
124394 ** code in fts3.c.
124395 */
124396
124397 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
124398
124399 /* #include <string.h> */
124400 /* #include <assert.h> */
124401 /* #include <stdlib.h> */
124402
124403 /*
124404 ** When full-text index nodes are loaded from disk, the buffer that they
124405 ** are loaded into has the following number of bytes of padding at the end 
124406 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
124407 ** of 920 bytes is allocated for it.
124408 **
124409 ** This means that if we have a pointer into a buffer containing node data,
124410 ** it is always safe to read up to two varints from it without risking an
124411 ** overread, even if the node data is corrupted.
124412 */
124413 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
124414
124415 /*
124416 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
124417 ** memory incrementally instead of all at once. This can be a big performance
124418 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
124419 ** method before retrieving all query results (as may happen, for example,
124420 ** if a query has a LIMIT clause).
124421 **
124422 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
124423 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
124424 ** The code is written so that the hard lower-limit for each of these values 
124425 ** is 1. Clearly such small values would be inefficient, but can be useful 
124426 ** for testing purposes.
124427 **
124428 ** If this module is built with SQLCIPHER_TEST defined, these constants may
124429 ** be overridden at runtime for testing purposes. File fts3_test.c contains
124430 ** a Tcl interface to read and write the values.
124431 */
124432 #ifdef SQLCIPHER_TEST
124433 int test_fts3_node_chunksize = (4*1024);
124434 int test_fts3_node_chunk_threshold = (4*1024)*4;
124435 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
124436 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
124437 #else
124438 # define FTS3_NODE_CHUNKSIZE (4*1024) 
124439 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
124440 #endif
124441
124442 typedef struct PendingList PendingList;
124443 typedef struct SegmentNode SegmentNode;
124444 typedef struct SegmentWriter SegmentWriter;
124445
124446 /*
124447 ** An instance of the following data structure is used to build doclists
124448 ** incrementally. See function fts3PendingListAppend() for details.
124449 */
124450 struct PendingList {
124451   int nData;
124452   char *aData;
124453   int nSpace;
124454   sqlcipher3_int64 iLastDocid;
124455   sqlcipher3_int64 iLastCol;
124456   sqlcipher3_int64 iLastPos;
124457 };
124458
124459
124460 /*
124461 ** Each cursor has a (possibly empty) linked list of the following objects.
124462 */
124463 struct Fts3DeferredToken {
124464   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
124465   int iCol;                       /* Column token must occur in */
124466   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
124467   PendingList *pList;             /* Doclist is assembled here */
124468 };
124469
124470 /*
124471 ** An instance of this structure is used to iterate through the terms on
124472 ** a contiguous set of segment b-tree leaf nodes. Although the details of
124473 ** this structure are only manipulated by code in this file, opaque handles
124474 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
124475 ** terms when querying the full-text index. See functions:
124476 **
124477 **   sqlcipher3Fts3SegReaderNew()
124478 **   sqlcipher3Fts3SegReaderFree()
124479 **   sqlcipher3Fts3SegReaderIterate()
124480 **
124481 ** Methods used to manipulate Fts3SegReader structures:
124482 **
124483 **   fts3SegReaderNext()
124484 **   fts3SegReaderFirstDocid()
124485 **   fts3SegReaderNextDocid()
124486 */
124487 struct Fts3SegReader {
124488   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
124489
124490   sqlcipher3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
124491   sqlcipher3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
124492   sqlcipher3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
124493   sqlcipher3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
124494
124495   char *aNode;                    /* Pointer to node data (or NULL) */
124496   int nNode;                      /* Size of buffer at aNode (or 0) */
124497   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
124498   sqlcipher3_blob *pBlob;            /* If not NULL, blob handle to read node */
124499
124500   Fts3HashElem **ppNextElem;
124501
124502   /* Variables set by fts3SegReaderNext(). These may be read directly
124503   ** by the caller. They are valid from the time SegmentReaderNew() returns
124504   ** until SegmentReaderNext() returns something other than SQLCIPHER_OK
124505   ** (i.e. SQLCIPHER_DONE).
124506   */
124507   int nTerm;                      /* Number of bytes in current term */
124508   char *zTerm;                    /* Pointer to current term */
124509   int nTermAlloc;                 /* Allocated size of zTerm buffer */
124510   char *aDoclist;                 /* Pointer to doclist of current entry */
124511   int nDoclist;                   /* Size of doclist in current entry */
124512
124513   /* The following variables are used by fts3SegReaderNextDocid() to iterate 
124514   ** through the current doclist (aDoclist/nDoclist).
124515   */
124516   char *pOffsetList;
124517   int nOffsetList;                /* For descending pending seg-readers only */
124518   sqlcipher3_int64 iDocid;
124519 };
124520
124521 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
124522 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
124523
124524 /*
124525 ** An instance of this structure is used to create a segment b-tree in the
124526 ** database. The internal details of this type are only accessed by the
124527 ** following functions:
124528 **
124529 **   fts3SegWriterAdd()
124530 **   fts3SegWriterFlush()
124531 **   fts3SegWriterFree()
124532 */
124533 struct SegmentWriter {
124534   SegmentNode *pTree;             /* Pointer to interior tree structure */
124535   sqlcipher3_int64 iFirst;           /* First slot in %_segments written */
124536   sqlcipher3_int64 iFree;            /* Next free slot in %_segments */
124537   char *zTerm;                    /* Pointer to previous term buffer */
124538   int nTerm;                      /* Number of bytes in zTerm */
124539   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
124540   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
124541   int nSize;                      /* Size of allocation at aData */
124542   int nData;                      /* Bytes of data in aData */
124543   char *aData;                    /* Pointer to block from malloc() */
124544 };
124545
124546 /*
124547 ** Type SegmentNode is used by the following three functions to create
124548 ** the interior part of the segment b+-tree structures (everything except
124549 ** the leaf nodes). These functions and type are only ever used by code
124550 ** within the fts3SegWriterXXX() family of functions described above.
124551 **
124552 **   fts3NodeAddTerm()
124553 **   fts3NodeWrite()
124554 **   fts3NodeFree()
124555 **
124556 ** When a b+tree is written to the database (either as a result of a merge
124557 ** or the pending-terms table being flushed), leaves are written into the 
124558 ** database file as soon as they are completely populated. The interior of
124559 ** the tree is assembled in memory and written out only once all leaves have
124560 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
124561 ** very large, meaning that the interior of the tree consumes relatively 
124562 ** little memory.
124563 */
124564 struct SegmentNode {
124565   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
124566   SegmentNode *pRight;            /* Pointer to right-sibling */
124567   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
124568   int nEntry;                     /* Number of terms written to node so far */
124569   char *zTerm;                    /* Pointer to previous term buffer */
124570   int nTerm;                      /* Number of bytes in zTerm */
124571   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
124572   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
124573   int nData;                      /* Bytes of valid data so far */
124574   char *aData;                    /* Node data */
124575 };
124576
124577 /*
124578 ** Valid values for the second argument to fts3SqlStmt().
124579 */
124580 #define SQL_DELETE_CONTENT             0
124581 #define SQL_IS_EMPTY                   1
124582 #define SQL_DELETE_ALL_CONTENT         2 
124583 #define SQL_DELETE_ALL_SEGMENTS        3
124584 #define SQL_DELETE_ALL_SEGDIR          4
124585 #define SQL_DELETE_ALL_DOCSIZE         5
124586 #define SQL_DELETE_ALL_STAT            6
124587 #define SQL_SELECT_CONTENT_BY_ROWID    7
124588 #define SQL_NEXT_SEGMENT_INDEX         8
124589 #define SQL_INSERT_SEGMENTS            9
124590 #define SQL_NEXT_SEGMENTS_ID          10
124591 #define SQL_INSERT_SEGDIR             11
124592 #define SQL_SELECT_LEVEL              12
124593 #define SQL_SELECT_LEVEL_RANGE        13
124594 #define SQL_SELECT_LEVEL_COUNT        14
124595 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
124596 #define SQL_DELETE_SEGDIR_LEVEL       16
124597 #define SQL_DELETE_SEGMENTS_RANGE     17
124598 #define SQL_CONTENT_INSERT            18
124599 #define SQL_DELETE_DOCSIZE            19
124600 #define SQL_REPLACE_DOCSIZE           20
124601 #define SQL_SELECT_DOCSIZE            21
124602 #define SQL_SELECT_DOCTOTAL           22
124603 #define SQL_REPLACE_DOCTOTAL          23
124604
124605 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
124606 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
124607
124608 #define SQL_DELETE_SEGDIR_RANGE       26
124609
124610 /*
124611 ** This function is used to obtain an SQLite prepared statement handle
124612 ** for the statement identified by the second argument. If successful,
124613 ** *pp is set to the requested statement handle and SQLCIPHER_OK returned.
124614 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
124615 **
124616 ** If argument apVal is not NULL, then it must point to an array with
124617 ** at least as many entries as the requested statement has bound 
124618 ** parameters. The values are bound to the statements parameters before
124619 ** returning.
124620 */
124621 static int fts3SqlStmt(
124622   Fts3Table *p,                   /* Virtual table handle */
124623   int eStmt,                      /* One of the SQL_XXX constants above */
124624   sqlcipher3_stmt **pp,              /* OUT: Statement handle */
124625   sqlcipher3_value **apVal           /* Values to bind to statement */
124626 ){
124627   const char *azSql[] = {
124628 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
124629 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
124630 /* 2  */  "DELETE FROM %Q.'%q_content'",
124631 /* 3  */  "DELETE FROM %Q.'%q_segments'",
124632 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
124633 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
124634 /* 6  */  "DELETE FROM %Q.'%q_stat'",
124635 /* 7  */  "SELECT %s WHERE rowid=?",
124636 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
124637 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
124638 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
124639 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
124640
124641           /* Return segments in order from oldest to newest.*/ 
124642 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
124643             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
124644 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
124645             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
124646             "ORDER BY level DESC, idx ASC",
124647
124648 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
124649 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
124650
124651 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
124652 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
124653 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
124654 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
124655 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
124656 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
124657 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
124658 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
124659 /* 24 */  "",
124660 /* 25 */  "",
124661
124662 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
124663
124664   };
124665   int rc = SQLCIPHER_OK;
124666   sqlcipher3_stmt *pStmt;
124667
124668   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
124669   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
124670   
124671   pStmt = p->aStmt[eStmt];
124672   if( !pStmt ){
124673     char *zSql;
124674     if( eStmt==SQL_CONTENT_INSERT ){
124675       zSql = sqlcipher3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
124676     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
124677       zSql = sqlcipher3_mprintf(azSql[eStmt], p->zReadExprlist);
124678     }else{
124679       zSql = sqlcipher3_mprintf(azSql[eStmt], p->zDb, p->zName);
124680     }
124681     if( !zSql ){
124682       rc = SQLCIPHER_NOMEM;
124683     }else{
124684       rc = sqlcipher3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
124685       sqlcipher3_free(zSql);
124686       assert( rc==SQLCIPHER_OK || pStmt==0 );
124687       p->aStmt[eStmt] = pStmt;
124688     }
124689   }
124690   if( apVal ){
124691     int i;
124692     int nParam = sqlcipher3_bind_parameter_count(pStmt);
124693     for(i=0; rc==SQLCIPHER_OK && i<nParam; i++){
124694       rc = sqlcipher3_bind_value(pStmt, i+1, apVal[i]);
124695     }
124696   }
124697   *pp = pStmt;
124698   return rc;
124699 }
124700
124701 static int fts3SelectDocsize(
124702   Fts3Table *pTab,                /* FTS3 table handle */
124703   int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
124704   sqlcipher3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
124705   sqlcipher3_stmt **ppStmt           /* OUT: Statement handle */
124706 ){
124707   sqlcipher3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
124708   int rc;                         /* Return code */
124709
124710   assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
124711
124712   rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
124713   if( rc==SQLCIPHER_OK ){
124714     if( eStmt==SQL_SELECT_DOCSIZE ){
124715       sqlcipher3_bind_int64(pStmt, 1, iDocid);
124716     }
124717     rc = sqlcipher3_step(pStmt);
124718     if( rc!=SQLCIPHER_ROW || sqlcipher3_column_type(pStmt, 0)!=SQLCIPHER_BLOB ){
124719       rc = sqlcipher3_reset(pStmt);
124720       if( rc==SQLCIPHER_OK ) rc = FTS_CORRUPT_VTAB;
124721       pStmt = 0;
124722     }else{
124723       rc = SQLCIPHER_OK;
124724     }
124725   }
124726
124727   *ppStmt = pStmt;
124728   return rc;
124729 }
124730
124731 SQLCIPHER_PRIVATE int sqlcipher3Fts3SelectDoctotal(
124732   Fts3Table *pTab,                /* Fts3 table handle */
124733   sqlcipher3_stmt **ppStmt           /* OUT: Statement handle */
124734 ){
124735   return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
124736 }
124737
124738 SQLCIPHER_PRIVATE int sqlcipher3Fts3SelectDocsize(
124739   Fts3Table *pTab,                /* Fts3 table handle */
124740   sqlcipher3_int64 iDocid,           /* Docid to read size data for */
124741   sqlcipher3_stmt **ppStmt           /* OUT: Statement handle */
124742 ){
124743   return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
124744 }
124745
124746 /*
124747 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
124748 ** array apVal[] to the SQL statement identified by eStmt, the statement
124749 ** is executed.
124750 **
124751 ** Returns SQLCIPHER_OK if the statement is successfully executed, or an
124752 ** SQLite error code otherwise.
124753 */
124754 static void fts3SqlExec(
124755   int *pRC,                /* Result code */
124756   Fts3Table *p,            /* The FTS3 table */
124757   int eStmt,               /* Index of statement to evaluate */
124758   sqlcipher3_value **apVal    /* Parameters to bind */
124759 ){
124760   sqlcipher3_stmt *pStmt;
124761   int rc;
124762   if( *pRC ) return;
124763   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
124764   if( rc==SQLCIPHER_OK ){
124765     sqlcipher3_step(pStmt);
124766     rc = sqlcipher3_reset(pStmt);
124767   }
124768   *pRC = rc;
124769 }
124770
124771
124772 /*
124773 ** This function ensures that the caller has obtained a shared-cache
124774 ** table-lock on the %_content table. This is required before reading
124775 ** data from the fts3 table. If this lock is not acquired first, then
124776 ** the caller may end up holding read-locks on the %_segments and %_segdir
124777 ** tables, but no read-lock on the %_content table. If this happens 
124778 ** a second connection will be able to write to the fts3 table, but
124779 ** attempting to commit those writes might return SQLCIPHER_LOCKED or
124780 ** SQLCIPHER_LOCKED_SHAREDCACHE (because the commit attempts to obtain 
124781 ** write-locks on the %_segments and %_segdir ** tables). 
124782 **
124783 ** We try to avoid this because if FTS3 returns any error when committing
124784 ** a transaction, the whole transaction will be rolled back. And this is
124785 ** not what users expect when they get SQLCIPHER_LOCKED_SHAREDCACHE. It can
124786 ** still happen if the user reads data directly from the %_segments or
124787 ** %_segdir tables instead of going through FTS3 though.
124788 **
124789 ** This reasoning does not apply to a content=xxx table.
124790 */
124791 SQLCIPHER_PRIVATE int sqlcipher3Fts3ReadLock(Fts3Table *p){
124792   int rc;                         /* Return code */
124793   sqlcipher3_stmt *pStmt;            /* Statement used to obtain lock */
124794
124795   if( p->zContentTbl==0 ){
124796     rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
124797     if( rc==SQLCIPHER_OK ){
124798       sqlcipher3_bind_null(pStmt, 1);
124799       sqlcipher3_step(pStmt);
124800       rc = sqlcipher3_reset(pStmt);
124801     }
124802   }else{
124803     rc = SQLCIPHER_OK;
124804   }
124805
124806   return rc;
124807 }
124808
124809 /*
124810 ** Set *ppStmt to a statement handle that may be used to iterate through
124811 ** all rows in the %_segdir table, from oldest to newest. If successful,
124812 ** return SQLCIPHER_OK. If an error occurs while preparing the statement, 
124813 ** return an SQLite error code.
124814 **
124815 ** There is only ever one instance of this SQL statement compiled for
124816 ** each FTS3 table.
124817 **
124818 ** The statement returns the following columns from the %_segdir table:
124819 **
124820 **   0: idx
124821 **   1: start_block
124822 **   2: leaves_end_block
124823 **   3: end_block
124824 **   4: root
124825 */
124826 SQLCIPHER_PRIVATE int sqlcipher3Fts3AllSegdirs(
124827   Fts3Table *p,                   /* FTS3 table */
124828   int iIndex,                     /* Index for p->aIndex[] */
124829   int iLevel,                     /* Level to select */
124830   sqlcipher3_stmt **ppStmt           /* OUT: Compiled statement */
124831 ){
124832   int rc;
124833   sqlcipher3_stmt *pStmt = 0;
124834
124835   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
124836   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
124837   assert( iIndex>=0 && iIndex<p->nIndex );
124838
124839   if( iLevel<0 ){
124840     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
124841     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
124842     if( rc==SQLCIPHER_OK ){ 
124843       sqlcipher3_bind_int(pStmt, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
124844       sqlcipher3_bind_int(pStmt, 2, (iIndex+1)*FTS3_SEGDIR_MAXLEVEL-1);
124845     }
124846   }else{
124847     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
124848     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
124849     if( rc==SQLCIPHER_OK ){ 
124850       sqlcipher3_bind_int(pStmt, 1, iLevel+iIndex*FTS3_SEGDIR_MAXLEVEL);
124851     }
124852   }
124853   *ppStmt = pStmt;
124854   return rc;
124855 }
124856
124857
124858 /*
124859 ** Append a single varint to a PendingList buffer. SQLCIPHER_OK is returned
124860 ** if successful, or an SQLite error code otherwise.
124861 **
124862 ** This function also serves to allocate the PendingList structure itself.
124863 ** For example, to create a new PendingList structure containing two
124864 ** varints:
124865 **
124866 **   PendingList *p = 0;
124867 **   fts3PendingListAppendVarint(&p, 1);
124868 **   fts3PendingListAppendVarint(&p, 2);
124869 */
124870 static int fts3PendingListAppendVarint(
124871   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
124872   sqlcipher3_int64 i                 /* Value to append to data */
124873 ){
124874   PendingList *p = *pp;
124875
124876   /* Allocate or grow the PendingList as required. */
124877   if( !p ){
124878     p = sqlcipher3_malloc(sizeof(*p) + 100);
124879     if( !p ){
124880       return SQLCIPHER_NOMEM;
124881     }
124882     p->nSpace = 100;
124883     p->aData = (char *)&p[1];
124884     p->nData = 0;
124885   }
124886   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
124887     int nNew = p->nSpace * 2;
124888     p = sqlcipher3_realloc(p, sizeof(*p) + nNew);
124889     if( !p ){
124890       sqlcipher3_free(*pp);
124891       *pp = 0;
124892       return SQLCIPHER_NOMEM;
124893     }
124894     p->nSpace = nNew;
124895     p->aData = (char *)&p[1];
124896   }
124897
124898   /* Append the new serialized varint to the end of the list. */
124899   p->nData += sqlcipher3Fts3PutVarint(&p->aData[p->nData], i);
124900   p->aData[p->nData] = '\0';
124901   *pp = p;
124902   return SQLCIPHER_OK;
124903 }
124904
124905 /*
124906 ** Add a docid/column/position entry to a PendingList structure. Non-zero
124907 ** is returned if the structure is sqlcipher3_realloced as part of adding
124908 ** the entry. Otherwise, zero.
124909 **
124910 ** If an OOM error occurs, *pRc is set to SQLCIPHER_NOMEM before returning.
124911 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
124912 ** it is set to SQLCIPHER_OK.
124913 */
124914 static int fts3PendingListAppend(
124915   PendingList **pp,               /* IN/OUT: PendingList structure */
124916   sqlcipher3_int64 iDocid,           /* Docid for entry to add */
124917   sqlcipher3_int64 iCol,             /* Column for entry to add */
124918   sqlcipher3_int64 iPos,             /* Position of term for entry to add */
124919   int *pRc                        /* OUT: Return code */
124920 ){
124921   PendingList *p = *pp;
124922   int rc = SQLCIPHER_OK;
124923
124924   assert( !p || p->iLastDocid<=iDocid );
124925
124926   if( !p || p->iLastDocid!=iDocid ){
124927     sqlcipher3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
124928     if( p ){
124929       assert( p->nData<p->nSpace );
124930       assert( p->aData[p->nData]==0 );
124931       p->nData++;
124932     }
124933     if( SQLCIPHER_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
124934       goto pendinglistappend_out;
124935     }
124936     p->iLastCol = -1;
124937     p->iLastPos = 0;
124938     p->iLastDocid = iDocid;
124939   }
124940   if( iCol>0 && p->iLastCol!=iCol ){
124941     if( SQLCIPHER_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
124942      || SQLCIPHER_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
124943     ){
124944       goto pendinglistappend_out;
124945     }
124946     p->iLastCol = iCol;
124947     p->iLastPos = 0;
124948   }
124949   if( iCol>=0 ){
124950     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
124951     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
124952     if( rc==SQLCIPHER_OK ){
124953       p->iLastPos = iPos;
124954     }
124955   }
124956
124957  pendinglistappend_out:
124958   *pRc = rc;
124959   if( p!=*pp ){
124960     *pp = p;
124961     return 1;
124962   }
124963   return 0;
124964 }
124965
124966 /*
124967 ** Free a PendingList object allocated by fts3PendingListAppend().
124968 */
124969 static void fts3PendingListDelete(PendingList *pList){
124970   sqlcipher3_free(pList);
124971 }
124972
124973 /*
124974 ** Add an entry to one of the pending-terms hash tables.
124975 */
124976 static int fts3PendingTermsAddOne(
124977   Fts3Table *p,
124978   int iCol,
124979   int iPos,
124980   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
124981   const char *zToken,
124982   int nToken
124983 ){
124984   PendingList *pList;
124985   int rc = SQLCIPHER_OK;
124986
124987   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
124988   if( pList ){
124989     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
124990   }
124991   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
124992     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
124993       /* Malloc failed while inserting the new entry. This can only 
124994       ** happen if there was no previous entry for this token.
124995       */
124996       assert( 0==fts3HashFind(pHash, zToken, nToken) );
124997       sqlcipher3_free(pList);
124998       rc = SQLCIPHER_NOMEM;
124999     }
125000   }
125001   if( rc==SQLCIPHER_OK ){
125002     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
125003   }
125004   return rc;
125005 }
125006
125007 /*
125008 ** Tokenize the nul-terminated string zText and add all tokens to the
125009 ** pending-terms hash-table. The docid used is that currently stored in
125010 ** p->iPrevDocid, and the column is specified by argument iCol.
125011 **
125012 ** If successful, SQLCIPHER_OK is returned. Otherwise, an SQLite error code.
125013 */
125014 static int fts3PendingTermsAdd(
125015   Fts3Table *p,                   /* Table into which text will be inserted */
125016   const char *zText,              /* Text of document to be inserted */
125017   int iCol,                       /* Column into which text is being inserted */
125018   u32 *pnWord                     /* OUT: Number of tokens inserted */
125019 ){
125020   int rc;
125021   int iStart;
125022   int iEnd;
125023   int iPos;
125024   int nWord = 0;
125025
125026   char const *zToken;
125027   int nToken;
125028
125029   sqlcipher3_tokenizer *pTokenizer = p->pTokenizer;
125030   sqlcipher3_tokenizer_module const *pModule = pTokenizer->pModule;
125031   sqlcipher3_tokenizer_cursor *pCsr;
125032   int (*xNext)(sqlcipher3_tokenizer_cursor *pCursor,
125033       const char**,int*,int*,int*,int*);
125034
125035   assert( pTokenizer && pModule );
125036
125037   /* If the user has inserted a NULL value, this function may be called with
125038   ** zText==0. In this case, add zero token entries to the hash table and 
125039   ** return early. */
125040   if( zText==0 ){
125041     *pnWord = 0;
125042     return SQLCIPHER_OK;
125043   }
125044
125045   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
125046   if( rc!=SQLCIPHER_OK ){
125047     return rc;
125048   }
125049   pCsr->pTokenizer = pTokenizer;
125050
125051   xNext = pModule->xNext;
125052   while( SQLCIPHER_OK==rc
125053       && SQLCIPHER_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
125054   ){
125055     int i;
125056     if( iPos>=nWord ) nWord = iPos+1;
125057
125058     /* Positions cannot be negative; we use -1 as a terminator internally.
125059     ** Tokens must have a non-zero length.
125060     */
125061     if( iPos<0 || !zToken || nToken<=0 ){
125062       rc = SQLCIPHER_ERROR;
125063       break;
125064     }
125065
125066     /* Add the term to the terms index */
125067     rc = fts3PendingTermsAddOne(
125068         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
125069     );
125070     
125071     /* Add the term to each of the prefix indexes that it is not too 
125072     ** short for. */
125073     for(i=1; rc==SQLCIPHER_OK && i<p->nIndex; i++){
125074       struct Fts3Index *pIndex = &p->aIndex[i];
125075       if( nToken<pIndex->nPrefix ) continue;
125076       rc = fts3PendingTermsAddOne(
125077           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
125078       );
125079     }
125080   }
125081
125082   pModule->xClose(pCsr);
125083   *pnWord = nWord;
125084   return (rc==SQLCIPHER_DONE ? SQLCIPHER_OK : rc);
125085 }
125086
125087 /* 
125088 ** Calling this function indicates that subsequent calls to 
125089 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
125090 ** contents of the document with docid iDocid.
125091 */
125092 static int fts3PendingTermsDocid(Fts3Table *p, sqlcipher_int64 iDocid){
125093   /* TODO(shess) Explore whether partially flushing the buffer on
125094   ** forced-flush would provide better performance.  I suspect that if
125095   ** we ordered the doclists by size and flushed the largest until the
125096   ** buffer was half empty, that would let the less frequent terms
125097   ** generate longer doclists.
125098   */
125099   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
125100     int rc = sqlcipher3Fts3PendingTermsFlush(p);
125101     if( rc!=SQLCIPHER_OK ) return rc;
125102   }
125103   p->iPrevDocid = iDocid;
125104   return SQLCIPHER_OK;
125105 }
125106
125107 /*
125108 ** Discard the contents of the pending-terms hash tables. 
125109 */
125110 SQLCIPHER_PRIVATE void sqlcipher3Fts3PendingTermsClear(Fts3Table *p){
125111   int i;
125112   for(i=0; i<p->nIndex; i++){
125113     Fts3HashElem *pElem;
125114     Fts3Hash *pHash = &p->aIndex[i].hPending;
125115     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
125116       PendingList *pList = (PendingList *)fts3HashData(pElem);
125117       fts3PendingListDelete(pList);
125118     }
125119     fts3HashClear(pHash);
125120   }
125121   p->nPendingData = 0;
125122 }
125123
125124 /*
125125 ** This function is called by the xUpdate() method as part of an INSERT
125126 ** operation. It adds entries for each term in the new record to the
125127 ** pendingTerms hash table.
125128 **
125129 ** Argument apVal is the same as the similarly named argument passed to
125130 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
125131 */
125132 static int fts3InsertTerms(Fts3Table *p, sqlcipher3_value **apVal, u32 *aSz){
125133   int i;                          /* Iterator variable */
125134   for(i=2; i<p->nColumn+2; i++){
125135     const char *zText = (const char *)sqlcipher3_value_text(apVal[i]);
125136     int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
125137     if( rc!=SQLCIPHER_OK ){
125138       return rc;
125139     }
125140     aSz[p->nColumn] += sqlcipher3_value_bytes(apVal[i]);
125141   }
125142   return SQLCIPHER_OK;
125143 }
125144
125145 /*
125146 ** This function is called by the xUpdate() method for an INSERT operation.
125147 ** The apVal parameter is passed a copy of the apVal argument passed by
125148 ** SQLite to the xUpdate() method. i.e:
125149 **
125150 **   apVal[0]                Not used for INSERT.
125151 **   apVal[1]                rowid
125152 **   apVal[2]                Left-most user-defined column
125153 **   ...
125154 **   apVal[p->nColumn+1]     Right-most user-defined column
125155 **   apVal[p->nColumn+2]     Hidden column with same name as table
125156 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
125157 */
125158 static int fts3InsertData(
125159   Fts3Table *p,                   /* Full-text table */
125160   sqlcipher3_value **apVal,          /* Array of values to insert */
125161   sqlcipher3_int64 *piDocid          /* OUT: Docid for row just inserted */
125162 ){
125163   int rc;                         /* Return code */
125164   sqlcipher3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
125165
125166   if( p->zContentTbl ){
125167     sqlcipher3_value *pRowid = apVal[p->nColumn+3];
125168     if( sqlcipher3_value_type(pRowid)==SQLCIPHER_NULL ){
125169       pRowid = apVal[1];
125170     }
125171     if( sqlcipher3_value_type(pRowid)!=SQLCIPHER_INTEGER ){
125172       return SQLCIPHER_CONSTRAINT;
125173     }
125174     *piDocid = sqlcipher3_value_int64(pRowid);
125175     return SQLCIPHER_OK;
125176   }
125177
125178   /* Locate the statement handle used to insert data into the %_content
125179   ** table. The SQL for this statement is:
125180   **
125181   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
125182   **
125183   ** The statement features N '?' variables, where N is the number of user
125184   ** defined columns in the FTS3 table, plus one for the docid field.
125185   */
125186   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
125187   if( rc!=SQLCIPHER_OK ){
125188     return rc;
125189   }
125190
125191   /* There is a quirk here. The users INSERT statement may have specified
125192   ** a value for the "rowid" field, for the "docid" field, or for both.
125193   ** Which is a problem, since "rowid" and "docid" are aliases for the
125194   ** same value. For example:
125195   **
125196   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
125197   **
125198   ** In FTS3, this is an error. It is an error to specify non-NULL values
125199   ** for both docid and some other rowid alias.
125200   */
125201   if( SQLCIPHER_NULL!=sqlcipher3_value_type(apVal[3+p->nColumn]) ){
125202     if( SQLCIPHER_NULL==sqlcipher3_value_type(apVal[0])
125203      && SQLCIPHER_NULL!=sqlcipher3_value_type(apVal[1])
125204     ){
125205       /* A rowid/docid conflict. */
125206       return SQLCIPHER_ERROR;
125207     }
125208     rc = sqlcipher3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
125209     if( rc!=SQLCIPHER_OK ) return rc;
125210   }
125211
125212   /* Execute the statement to insert the record. Set *piDocid to the 
125213   ** new docid value. 
125214   */
125215   sqlcipher3_step(pContentInsert);
125216   rc = sqlcipher3_reset(pContentInsert);
125217
125218   *piDocid = sqlcipher3_last_insert_rowid(p->db);
125219   return rc;
125220 }
125221
125222
125223
125224 /*
125225 ** Remove all data from the FTS3 table. Clear the hash table containing
125226 ** pending terms.
125227 */
125228 static int fts3DeleteAll(Fts3Table *p, int bContent){
125229   int rc = SQLCIPHER_OK;             /* Return code */
125230
125231   /* Discard the contents of the pending-terms hash table. */
125232   sqlcipher3Fts3PendingTermsClear(p);
125233
125234   /* Delete everything from the shadow tables. Except, leave %_content as
125235   ** is if bContent is false.  */
125236   assert( p->zContentTbl==0 || bContent==0 );
125237   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
125238   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
125239   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
125240   if( p->bHasDocsize ){
125241     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
125242   }
125243   if( p->bHasStat ){
125244     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
125245   }
125246   return rc;
125247 }
125248
125249 /*
125250 ** The first element in the apVal[] array is assumed to contain the docid
125251 ** (an integer) of a row about to be deleted. Remove all terms from the
125252 ** full-text index.
125253 */
125254 static void fts3DeleteTerms( 
125255   int *pRC,               /* Result code */
125256   Fts3Table *p,           /* The FTS table to delete from */
125257   sqlcipher3_value *pRowid,  /* The docid to be deleted */
125258   u32 *aSz                /* Sizes of deleted document written here */
125259 ){
125260   int rc;
125261   sqlcipher3_stmt *pSelect;
125262
125263   if( *pRC ) return;
125264   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
125265   if( rc==SQLCIPHER_OK ){
125266     if( SQLCIPHER_ROW==sqlcipher3_step(pSelect) ){
125267       int i;
125268       for(i=1; i<=p->nColumn; i++){
125269         const char *zText = (const char *)sqlcipher3_column_text(pSelect, i);
125270         rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
125271         if( rc!=SQLCIPHER_OK ){
125272           sqlcipher3_reset(pSelect);
125273           *pRC = rc;
125274           return;
125275         }
125276         aSz[p->nColumn] += sqlcipher3_column_bytes(pSelect, i);
125277       }
125278     }
125279     rc = sqlcipher3_reset(pSelect);
125280   }else{
125281     sqlcipher3_reset(pSelect);
125282   }
125283   *pRC = rc;
125284 }
125285
125286 /*
125287 ** Forward declaration to account for the circular dependency between
125288 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
125289 */
125290 static int fts3SegmentMerge(Fts3Table *, int, int);
125291
125292 /* 
125293 ** This function allocates a new level iLevel index in the segdir table.
125294 ** Usually, indexes are allocated within a level sequentially starting
125295 ** with 0, so the allocated index is one greater than the value returned
125296 ** by:
125297 **
125298 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
125299 **
125300 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
125301 ** level, they are merged into a single level (iLevel+1) segment and the 
125302 ** allocated index is 0.
125303 **
125304 ** If successful, *piIdx is set to the allocated index slot and SQLCIPHER_OK
125305 ** returned. Otherwise, an SQLite error code is returned.
125306 */
125307 static int fts3AllocateSegdirIdx(
125308   Fts3Table *p, 
125309   int iIndex,                     /* Index for p->aIndex */
125310   int iLevel, 
125311   int *piIdx
125312 ){
125313   int rc;                         /* Return Code */
125314   sqlcipher3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
125315   int iNext = 0;                  /* Result of query pNextIdx */
125316
125317   /* Set variable iNext to the next available segdir index at level iLevel. */
125318   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
125319   if( rc==SQLCIPHER_OK ){
125320     sqlcipher3_bind_int(pNextIdx, 1, iIndex*FTS3_SEGDIR_MAXLEVEL + iLevel);
125321     if( SQLCIPHER_ROW==sqlcipher3_step(pNextIdx) ){
125322       iNext = sqlcipher3_column_int(pNextIdx, 0);
125323     }
125324     rc = sqlcipher3_reset(pNextIdx);
125325   }
125326
125327   if( rc==SQLCIPHER_OK ){
125328     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
125329     ** full, merge all segments in level iLevel into a single iLevel+1
125330     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
125331     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
125332     */
125333     if( iNext>=FTS3_MERGE_COUNT ){
125334       rc = fts3SegmentMerge(p, iIndex, iLevel);
125335       *piIdx = 0;
125336     }else{
125337       *piIdx = iNext;
125338     }
125339   }
125340
125341   return rc;
125342 }
125343
125344 /*
125345 ** The %_segments table is declared as follows:
125346 **
125347 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
125348 **
125349 ** This function reads data from a single row of the %_segments table. The
125350 ** specific row is identified by the iBlockid parameter. If paBlob is not
125351 ** NULL, then a buffer is allocated using sqlcipher3_malloc() and populated
125352 ** with the contents of the blob stored in the "block" column of the 
125353 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
125354 ** to the size of the blob in bytes before returning.
125355 **
125356 ** If an error occurs, or the table does not contain the specified row,
125357 ** an SQLite error code is returned. Otherwise, SQLCIPHER_OK is returned. If
125358 ** paBlob is non-NULL, then it is the responsibility of the caller to
125359 ** eventually free the returned buffer.
125360 **
125361 ** This function may leave an open sqlcipher3_blob* handle in the
125362 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
125363 ** to this function. The handle may be closed by calling the
125364 ** sqlcipher3Fts3SegmentsClose() function. Reusing a blob handle is a handy
125365 ** performance improvement, but the blob handle should always be closed
125366 ** before control is returned to the user (to prevent a lock being held
125367 ** on the database file for longer than necessary). Thus, any virtual table
125368 ** method (xFilter etc.) that may directly or indirectly call this function
125369 ** must call sqlcipher3Fts3SegmentsClose() before returning.
125370 */
125371 SQLCIPHER_PRIVATE int sqlcipher3Fts3ReadBlock(
125372   Fts3Table *p,                   /* FTS3 table handle */
125373   sqlcipher3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
125374   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
125375   int *pnBlob,                    /* OUT: Size of blob data */
125376   int *pnLoad                     /* OUT: Bytes actually loaded */
125377 ){
125378   int rc;                         /* Return code */
125379
125380   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
125381   assert( pnBlob);
125382
125383   if( p->pSegments ){
125384     rc = sqlcipher3_blob_reopen(p->pSegments, iBlockid);
125385   }else{
125386     if( 0==p->zSegmentsTbl ){
125387       p->zSegmentsTbl = sqlcipher3_mprintf("%s_segments", p->zName);
125388       if( 0==p->zSegmentsTbl ) return SQLCIPHER_NOMEM;
125389     }
125390     rc = sqlcipher3_blob_open(
125391        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
125392     );
125393   }
125394
125395   if( rc==SQLCIPHER_OK ){
125396     int nByte = sqlcipher3_blob_bytes(p->pSegments);
125397     *pnBlob = nByte;
125398     if( paBlob ){
125399       char *aByte = sqlcipher3_malloc(nByte + FTS3_NODE_PADDING);
125400       if( !aByte ){
125401         rc = SQLCIPHER_NOMEM;
125402       }else{
125403         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
125404           nByte = FTS3_NODE_CHUNKSIZE;
125405           *pnLoad = nByte;
125406         }
125407         rc = sqlcipher3_blob_read(p->pSegments, aByte, nByte, 0);
125408         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
125409         if( rc!=SQLCIPHER_OK ){
125410           sqlcipher3_free(aByte);
125411           aByte = 0;
125412         }
125413       }
125414       *paBlob = aByte;
125415     }
125416   }
125417
125418   return rc;
125419 }
125420
125421 /*
125422 ** Close the blob handle at p->pSegments, if it is open. See comments above
125423 ** the sqlcipher3Fts3ReadBlock() function for details.
125424 */
125425 SQLCIPHER_PRIVATE void sqlcipher3Fts3SegmentsClose(Fts3Table *p){
125426   sqlcipher3_blob_close(p->pSegments);
125427   p->pSegments = 0;
125428 }
125429     
125430 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
125431   int nRead;                      /* Number of bytes to read */
125432   int rc;                         /* Return code */
125433
125434   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
125435   rc = sqlcipher3_blob_read(
125436       pReader->pBlob, 
125437       &pReader->aNode[pReader->nPopulate],
125438       nRead,
125439       pReader->nPopulate
125440   );
125441
125442   if( rc==SQLCIPHER_OK ){
125443     pReader->nPopulate += nRead;
125444     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
125445     if( pReader->nPopulate==pReader->nNode ){
125446       sqlcipher3_blob_close(pReader->pBlob);
125447       pReader->pBlob = 0;
125448       pReader->nPopulate = 0;
125449     }
125450   }
125451   return rc;
125452 }
125453
125454 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
125455   int rc = SQLCIPHER_OK;
125456   assert( !pReader->pBlob 
125457        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
125458   );
125459   while( pReader->pBlob && rc==SQLCIPHER_OK 
125460      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
125461   ){
125462     rc = fts3SegReaderIncrRead(pReader);
125463   }
125464   return rc;
125465 }
125466
125467 /*
125468 ** Move the iterator passed as the first argument to the next term in the
125469 ** segment. If successful, SQLCIPHER_OK is returned. If there is no next term,
125470 ** SQLCIPHER_DONE. Otherwise, an SQLite error code.
125471 */
125472 static int fts3SegReaderNext(
125473   Fts3Table *p, 
125474   Fts3SegReader *pReader,
125475   int bIncr
125476 ){
125477   int rc;                         /* Return code of various sub-routines */
125478   char *pNext;                    /* Cursor variable */
125479   int nPrefix;                    /* Number of bytes in term prefix */
125480   int nSuffix;                    /* Number of bytes in term suffix */
125481
125482   if( !pReader->aDoclist ){
125483     pNext = pReader->aNode;
125484   }else{
125485     pNext = &pReader->aDoclist[pReader->nDoclist];
125486   }
125487
125488   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
125489
125490     if( fts3SegReaderIsPending(pReader) ){
125491       Fts3HashElem *pElem = *(pReader->ppNextElem);
125492       if( pElem==0 ){
125493         pReader->aNode = 0;
125494       }else{
125495         PendingList *pList = (PendingList *)fts3HashData(pElem);
125496         pReader->zTerm = (char *)fts3HashKey(pElem);
125497         pReader->nTerm = fts3HashKeysize(pElem);
125498         pReader->nNode = pReader->nDoclist = pList->nData + 1;
125499         pReader->aNode = pReader->aDoclist = pList->aData;
125500         pReader->ppNextElem++;
125501         assert( pReader->aNode );
125502       }
125503       return SQLCIPHER_OK;
125504     }
125505
125506     if( !fts3SegReaderIsRootOnly(pReader) ){
125507       sqlcipher3_free(pReader->aNode);
125508       sqlcipher3_blob_close(pReader->pBlob);
125509       pReader->pBlob = 0;
125510     }
125511     pReader->aNode = 0;
125512
125513     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
125514     ** blocks have already been traversed.  */
125515     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
125516     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
125517       return SQLCIPHER_OK;
125518     }
125519
125520     rc = sqlcipher3Fts3ReadBlock(
125521         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
125522         (bIncr ? &pReader->nPopulate : 0)
125523     );
125524     if( rc!=SQLCIPHER_OK ) return rc;
125525     assert( pReader->pBlob==0 );
125526     if( bIncr && pReader->nPopulate<pReader->nNode ){
125527       pReader->pBlob = p->pSegments;
125528       p->pSegments = 0;
125529     }
125530     pNext = pReader->aNode;
125531   }
125532
125533   assert( !fts3SegReaderIsPending(pReader) );
125534
125535   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
125536   if( rc!=SQLCIPHER_OK ) return rc;
125537   
125538   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
125539   ** safe (no risk of overread) even if the node data is corrupted. */
125540   pNext += sqlcipher3Fts3GetVarint32(pNext, &nPrefix);
125541   pNext += sqlcipher3Fts3GetVarint32(pNext, &nSuffix);
125542   if( nPrefix<0 || nSuffix<=0 
125543    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
125544   ){
125545     return FTS_CORRUPT_VTAB;
125546   }
125547
125548   if( nPrefix+nSuffix>pReader->nTermAlloc ){
125549     int nNew = (nPrefix+nSuffix)*2;
125550     char *zNew = sqlcipher3_realloc(pReader->zTerm, nNew);
125551     if( !zNew ){
125552       return SQLCIPHER_NOMEM;
125553     }
125554     pReader->zTerm = zNew;
125555     pReader->nTermAlloc = nNew;
125556   }
125557
125558   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
125559   if( rc!=SQLCIPHER_OK ) return rc;
125560
125561   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
125562   pReader->nTerm = nPrefix+nSuffix;
125563   pNext += nSuffix;
125564   pNext += sqlcipher3Fts3GetVarint32(pNext, &pReader->nDoclist);
125565   pReader->aDoclist = pNext;
125566   pReader->pOffsetList = 0;
125567
125568   /* Check that the doclist does not appear to extend past the end of the
125569   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
125570   ** of these statements is untrue, then the data structure is corrupt.
125571   */
125572   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
125573    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
125574   ){
125575     return FTS_CORRUPT_VTAB;
125576   }
125577   return SQLCIPHER_OK;
125578 }
125579
125580 /*
125581 ** Set the SegReader to point to the first docid in the doclist associated
125582 ** with the current term.
125583 */
125584 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
125585   int rc = SQLCIPHER_OK;
125586   assert( pReader->aDoclist );
125587   assert( !pReader->pOffsetList );
125588   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
125589     u8 bEof = 0;
125590     pReader->iDocid = 0;
125591     pReader->nOffsetList = 0;
125592     sqlcipher3Fts3DoclistPrev(0,
125593         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
125594         &pReader->iDocid, &pReader->nOffsetList, &bEof
125595     );
125596   }else{
125597     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
125598     if( rc==SQLCIPHER_OK ){
125599       int n = sqlcipher3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
125600       pReader->pOffsetList = &pReader->aDoclist[n];
125601     }
125602   }
125603   return rc;
125604 }
125605
125606 /*
125607 ** Advance the SegReader to point to the next docid in the doclist
125608 ** associated with the current term.
125609 ** 
125610 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
125611 ** *ppOffsetList is set to point to the first column-offset list
125612 ** in the doclist entry (i.e. immediately past the docid varint).
125613 ** *pnOffsetList is set to the length of the set of column-offset
125614 ** lists, not including the nul-terminator byte. For example:
125615 */
125616 static int fts3SegReaderNextDocid(
125617   Fts3Table *pTab,
125618   Fts3SegReader *pReader,         /* Reader to advance to next docid */
125619   char **ppOffsetList,            /* OUT: Pointer to current position-list */
125620   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
125621 ){
125622   int rc = SQLCIPHER_OK;
125623   char *p = pReader->pOffsetList;
125624   char c = 0;
125625
125626   assert( p );
125627
125628   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
125629     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
125630     ** Pending-terms doclists are always built up in ascending order, so
125631     ** we have to iterate through them backwards here. */
125632     u8 bEof = 0;
125633     if( ppOffsetList ){
125634       *ppOffsetList = pReader->pOffsetList;
125635       *pnOffsetList = pReader->nOffsetList - 1;
125636     }
125637     sqlcipher3Fts3DoclistPrev(0,
125638         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
125639         &pReader->nOffsetList, &bEof
125640     );
125641     if( bEof ){
125642       pReader->pOffsetList = 0;
125643     }else{
125644       pReader->pOffsetList = p;
125645     }
125646   }else{
125647     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
125648
125649     /* Pointer p currently points at the first byte of an offset list. The
125650     ** following block advances it to point one byte past the end of
125651     ** the same offset list. */
125652     while( 1 ){
125653   
125654       /* The following line of code (and the "p++" below the while() loop) is
125655       ** normally all that is required to move pointer p to the desired 
125656       ** position. The exception is if this node is being loaded from disk
125657       ** incrementally and pointer "p" now points to the first byte passed
125658       ** the populated part of pReader->aNode[].
125659       */
125660       while( *p | c ) c = *p++ & 0x80;
125661       assert( *p==0 );
125662   
125663       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
125664       rc = fts3SegReaderIncrRead(pReader);
125665       if( rc!=SQLCIPHER_OK ) return rc;
125666     }
125667     p++;
125668   
125669     /* If required, populate the output variables with a pointer to and the
125670     ** size of the previous offset-list.
125671     */
125672     if( ppOffsetList ){
125673       *ppOffsetList = pReader->pOffsetList;
125674       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
125675     }
125676
125677     while( p<pEnd && *p==0 ) p++;
125678   
125679     /* If there are no more entries in the doclist, set pOffsetList to
125680     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
125681     ** Fts3SegReader.pOffsetList to point to the next offset list before
125682     ** returning.
125683     */
125684     if( p>=pEnd ){
125685       pReader->pOffsetList = 0;
125686     }else{
125687       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
125688       if( rc==SQLCIPHER_OK ){
125689         sqlcipher3_int64 iDelta;
125690         pReader->pOffsetList = p + sqlcipher3Fts3GetVarint(p, &iDelta);
125691         if( pTab->bDescIdx ){
125692           pReader->iDocid -= iDelta;
125693         }else{
125694           pReader->iDocid += iDelta;
125695         }
125696       }
125697     }
125698   }
125699
125700   return SQLCIPHER_OK;
125701 }
125702
125703
125704 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrOvfl(
125705   Fts3Cursor *pCsr, 
125706   Fts3MultiSegReader *pMsr,
125707   int *pnOvfl
125708 ){
125709   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
125710   int nOvfl = 0;
125711   int ii;
125712   int rc = SQLCIPHER_OK;
125713   int pgsz = p->nPgsz;
125714
125715   assert( p->bHasStat );
125716   assert( pgsz>0 );
125717
125718   for(ii=0; rc==SQLCIPHER_OK && ii<pMsr->nSegment; ii++){
125719     Fts3SegReader *pReader = pMsr->apSegment[ii];
125720     if( !fts3SegReaderIsPending(pReader) 
125721      && !fts3SegReaderIsRootOnly(pReader) 
125722     ){
125723       sqlcipher3_int64 jj;
125724       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
125725         int nBlob;
125726         rc = sqlcipher3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
125727         if( rc!=SQLCIPHER_OK ) break;
125728         if( (nBlob+35)>pgsz ){
125729           nOvfl += (nBlob + 34)/pgsz;
125730         }
125731       }
125732     }
125733   }
125734   *pnOvfl = nOvfl;
125735   return rc;
125736 }
125737
125738 /*
125739 ** Free all allocations associated with the iterator passed as the 
125740 ** second argument.
125741 */
125742 SQLCIPHER_PRIVATE void sqlcipher3Fts3SegReaderFree(Fts3SegReader *pReader){
125743   if( pReader && !fts3SegReaderIsPending(pReader) ){
125744     sqlcipher3_free(pReader->zTerm);
125745     if( !fts3SegReaderIsRootOnly(pReader) ){
125746       sqlcipher3_free(pReader->aNode);
125747       sqlcipher3_blob_close(pReader->pBlob);
125748     }
125749   }
125750   sqlcipher3_free(pReader);
125751 }
125752
125753 /*
125754 ** Allocate a new SegReader object.
125755 */
125756 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderNew(
125757   int iAge,                       /* Segment "age". */
125758   sqlcipher3_int64 iStartLeaf,       /* First leaf to traverse */
125759   sqlcipher3_int64 iEndLeaf,         /* Final leaf to traverse */
125760   sqlcipher3_int64 iEndBlock,        /* Final block of segment */
125761   const char *zRoot,              /* Buffer containing root node */
125762   int nRoot,                      /* Size of buffer containing root node */
125763   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
125764 ){
125765   int rc = SQLCIPHER_OK;             /* Return code */
125766   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
125767   int nExtra = 0;                 /* Bytes to allocate segment root node */
125768
125769   assert( iStartLeaf<=iEndLeaf );
125770   if( iStartLeaf==0 ){
125771     nExtra = nRoot + FTS3_NODE_PADDING;
125772   }
125773
125774   pReader = (Fts3SegReader *)sqlcipher3_malloc(sizeof(Fts3SegReader) + nExtra);
125775   if( !pReader ){
125776     return SQLCIPHER_NOMEM;
125777   }
125778   memset(pReader, 0, sizeof(Fts3SegReader));
125779   pReader->iIdx = iAge;
125780   pReader->iStartBlock = iStartLeaf;
125781   pReader->iLeafEndBlock = iEndLeaf;
125782   pReader->iEndBlock = iEndBlock;
125783
125784   if( nExtra ){
125785     /* The entire segment is stored in the root node. */
125786     pReader->aNode = (char *)&pReader[1];
125787     pReader->nNode = nRoot;
125788     memcpy(pReader->aNode, zRoot, nRoot);
125789     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
125790   }else{
125791     pReader->iCurrentBlock = iStartLeaf-1;
125792   }
125793
125794   if( rc==SQLCIPHER_OK ){
125795     *ppReader = pReader;
125796   }else{
125797     sqlcipher3Fts3SegReaderFree(pReader);
125798   }
125799   return rc;
125800 }
125801
125802 /*
125803 ** This is a comparison function used as a qsort() callback when sorting
125804 ** an array of pending terms by term. This occurs as part of flushing
125805 ** the contents of the pending-terms hash table to the database.
125806 */
125807 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
125808   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
125809   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
125810   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
125811   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
125812
125813   int n = (n1<n2 ? n1 : n2);
125814   int c = memcmp(z1, z2, n);
125815   if( c==0 ){
125816     c = n1 - n2;
125817   }
125818   return c;
125819 }
125820
125821 /*
125822 ** This function is used to allocate an Fts3SegReader that iterates through
125823 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
125824 **
125825 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
125826 ** through each term in the pending-terms table. Or, if isPrefixIter is
125827 ** non-zero, it iterates through each term and its prefixes. For example, if
125828 ** the pending terms hash table contains the terms "sqlcipher", "mysql" and
125829 ** "firebird", then the iterator visits the following 'terms' (in the order
125830 ** shown):
125831 **
125832 **   f fi fir fire fireb firebi firebir firebird
125833 **   m my mys mysq mysql
125834 **   s sq sql sqli sqlit sqlcipher
125835 **
125836 ** Whereas if isPrefixIter is zero, the terms visited are:
125837 **
125838 **   firebird mysql sqlcipher
125839 */
125840 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderPending(
125841   Fts3Table *p,                   /* Virtual table handle */
125842   int iIndex,                     /* Index for p->aIndex */
125843   const char *zTerm,              /* Term to search for */
125844   int nTerm,                      /* Size of buffer zTerm */
125845   int bPrefix,                    /* True for a prefix iterator */
125846   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
125847 ){
125848   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
125849   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
125850   int nElem = 0;                  /* Size of array at aElem */
125851   int rc = SQLCIPHER_OK;             /* Return Code */
125852   Fts3Hash *pHash;
125853
125854   pHash = &p->aIndex[iIndex].hPending;
125855   if( bPrefix ){
125856     int nAlloc = 0;               /* Size of allocated array at aElem */
125857     Fts3HashElem *pE = 0;         /* Iterator variable */
125858
125859     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
125860       char *zKey = (char *)fts3HashKey(pE);
125861       int nKey = fts3HashKeysize(pE);
125862       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
125863         if( nElem==nAlloc ){
125864           Fts3HashElem **aElem2;
125865           nAlloc += 16;
125866           aElem2 = (Fts3HashElem **)sqlcipher3_realloc(
125867               aElem, nAlloc*sizeof(Fts3HashElem *)
125868           );
125869           if( !aElem2 ){
125870             rc = SQLCIPHER_NOMEM;
125871             nElem = 0;
125872             break;
125873           }
125874           aElem = aElem2;
125875         }
125876
125877         aElem[nElem++] = pE;
125878       }
125879     }
125880
125881     /* If more than one term matches the prefix, sort the Fts3HashElem
125882     ** objects in term order using qsort(). This uses the same comparison
125883     ** callback as is used when flushing terms to disk.
125884     */
125885     if( nElem>1 ){
125886       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
125887     }
125888
125889   }else{
125890     /* The query is a simple term lookup that matches at most one term in
125891     ** the index. All that is required is a straight hash-lookup. */
125892     Fts3HashElem *pE = fts3HashFindElem(pHash, zTerm, nTerm);
125893     if( pE ){
125894       aElem = &pE;
125895       nElem = 1;
125896     }
125897   }
125898
125899   if( nElem>0 ){
125900     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
125901     pReader = (Fts3SegReader *)sqlcipher3_malloc(nByte);
125902     if( !pReader ){
125903       rc = SQLCIPHER_NOMEM;
125904     }else{
125905       memset(pReader, 0, nByte);
125906       pReader->iIdx = 0x7FFFFFFF;
125907       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
125908       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
125909     }
125910   }
125911
125912   if( bPrefix ){
125913     sqlcipher3_free(aElem);
125914   }
125915   *ppReader = pReader;
125916   return rc;
125917 }
125918
125919 /*
125920 ** Compare the entries pointed to by two Fts3SegReader structures. 
125921 ** Comparison is as follows:
125922 **
125923 **   1) EOF is greater than not EOF.
125924 **
125925 **   2) The current terms (if any) are compared using memcmp(). If one
125926 **      term is a prefix of another, the longer term is considered the
125927 **      larger.
125928 **
125929 **   3) By segment age. An older segment is considered larger.
125930 */
125931 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
125932   int rc;
125933   if( pLhs->aNode && pRhs->aNode ){
125934     int rc2 = pLhs->nTerm - pRhs->nTerm;
125935     if( rc2<0 ){
125936       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
125937     }else{
125938       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
125939     }
125940     if( rc==0 ){
125941       rc = rc2;
125942     }
125943   }else{
125944     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
125945   }
125946   if( rc==0 ){
125947     rc = pRhs->iIdx - pLhs->iIdx;
125948   }
125949   assert( rc!=0 );
125950   return rc;
125951 }
125952
125953 /*
125954 ** A different comparison function for SegReader structures. In this
125955 ** version, it is assumed that each SegReader points to an entry in
125956 ** a doclist for identical terms. Comparison is made as follows:
125957 **
125958 **   1) EOF (end of doclist in this case) is greater than not EOF.
125959 **
125960 **   2) By current docid.
125961 **
125962 **   3) By segment age. An older segment is considered larger.
125963 */
125964 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
125965   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
125966   if( rc==0 ){
125967     if( pLhs->iDocid==pRhs->iDocid ){
125968       rc = pRhs->iIdx - pLhs->iIdx;
125969     }else{
125970       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
125971     }
125972   }
125973   assert( pLhs->aNode && pRhs->aNode );
125974   return rc;
125975 }
125976 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
125977   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
125978   if( rc==0 ){
125979     if( pLhs->iDocid==pRhs->iDocid ){
125980       rc = pRhs->iIdx - pLhs->iIdx;
125981     }else{
125982       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
125983     }
125984   }
125985   assert( pLhs->aNode && pRhs->aNode );
125986   return rc;
125987 }
125988
125989 /*
125990 ** Compare the term that the Fts3SegReader object passed as the first argument
125991 ** points to with the term specified by arguments zTerm and nTerm. 
125992 **
125993 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
125994 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
125995 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
125996 */
125997 static int fts3SegReaderTermCmp(
125998   Fts3SegReader *pSeg,            /* Segment reader object */
125999   const char *zTerm,              /* Term to compare to */
126000   int nTerm                       /* Size of term zTerm in bytes */
126001 ){
126002   int res = 0;
126003   if( pSeg->aNode ){
126004     if( pSeg->nTerm>nTerm ){
126005       res = memcmp(pSeg->zTerm, zTerm, nTerm);
126006     }else{
126007       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
126008     }
126009     if( res==0 ){
126010       res = pSeg->nTerm-nTerm;
126011     }
126012   }
126013   return res;
126014 }
126015
126016 /*
126017 ** Argument apSegment is an array of nSegment elements. It is known that
126018 ** the final (nSegment-nSuspect) members are already in sorted order
126019 ** (according to the comparison function provided). This function shuffles
126020 ** the array around until all entries are in sorted order.
126021 */
126022 static void fts3SegReaderSort(
126023   Fts3SegReader **apSegment,                     /* Array to sort entries of */
126024   int nSegment,                                  /* Size of apSegment array */
126025   int nSuspect,                                  /* Unsorted entry count */
126026   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
126027 ){
126028   int i;                          /* Iterator variable */
126029
126030   assert( nSuspect<=nSegment );
126031
126032   if( nSuspect==nSegment ) nSuspect--;
126033   for(i=nSuspect-1; i>=0; i--){
126034     int j;
126035     for(j=i; j<(nSegment-1); j++){
126036       Fts3SegReader *pTmp;
126037       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
126038       pTmp = apSegment[j+1];
126039       apSegment[j+1] = apSegment[j];
126040       apSegment[j] = pTmp;
126041     }
126042   }
126043
126044 #ifndef NDEBUG
126045   /* Check that the list really is sorted now. */
126046   for(i=0; i<(nSuspect-1); i++){
126047     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
126048   }
126049 #endif
126050 }
126051
126052 /* 
126053 ** Insert a record into the %_segments table.
126054 */
126055 static int fts3WriteSegment(
126056   Fts3Table *p,                   /* Virtual table handle */
126057   sqlcipher3_int64 iBlock,           /* Block id for new block */
126058   char *z,                        /* Pointer to buffer containing block data */
126059   int n                           /* Size of buffer z in bytes */
126060 ){
126061   sqlcipher3_stmt *pStmt;
126062   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
126063   if( rc==SQLCIPHER_OK ){
126064     sqlcipher3_bind_int64(pStmt, 1, iBlock);
126065     sqlcipher3_bind_blob(pStmt, 2, z, n, SQLCIPHER_STATIC);
126066     sqlcipher3_step(pStmt);
126067     rc = sqlcipher3_reset(pStmt);
126068   }
126069   return rc;
126070 }
126071
126072 /* 
126073 ** Insert a record into the %_segdir table.
126074 */
126075 static int fts3WriteSegdir(
126076   Fts3Table *p,                   /* Virtual table handle */
126077   int iLevel,                     /* Value for "level" field */
126078   int iIdx,                       /* Value for "idx" field */
126079   sqlcipher3_int64 iStartBlock,      /* Value for "start_block" field */
126080   sqlcipher3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
126081   sqlcipher3_int64 iEndBlock,        /* Value for "end_block" field */
126082   char *zRoot,                    /* Blob value for "root" field */
126083   int nRoot                       /* Number of bytes in buffer zRoot */
126084 ){
126085   sqlcipher3_stmt *pStmt;
126086   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
126087   if( rc==SQLCIPHER_OK ){
126088     sqlcipher3_bind_int(pStmt, 1, iLevel);
126089     sqlcipher3_bind_int(pStmt, 2, iIdx);
126090     sqlcipher3_bind_int64(pStmt, 3, iStartBlock);
126091     sqlcipher3_bind_int64(pStmt, 4, iLeafEndBlock);
126092     sqlcipher3_bind_int64(pStmt, 5, iEndBlock);
126093     sqlcipher3_bind_blob(pStmt, 6, zRoot, nRoot, SQLCIPHER_STATIC);
126094     sqlcipher3_step(pStmt);
126095     rc = sqlcipher3_reset(pStmt);
126096   }
126097   return rc;
126098 }
126099
126100 /*
126101 ** Return the size of the common prefix (if any) shared by zPrev and
126102 ** zNext, in bytes. For example, 
126103 **
126104 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
126105 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
126106 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
126107 */
126108 static int fts3PrefixCompress(
126109   const char *zPrev,              /* Buffer containing previous term */
126110   int nPrev,                      /* Size of buffer zPrev in bytes */
126111   const char *zNext,              /* Buffer containing next term */
126112   int nNext                       /* Size of buffer zNext in bytes */
126113 ){
126114   int n;
126115   UNUSED_PARAMETER(nNext);
126116   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
126117   return n;
126118 }
126119
126120 /*
126121 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
126122 ** (according to memcmp) than the previous term.
126123 */
126124 static int fts3NodeAddTerm(
126125   Fts3Table *p,                   /* Virtual table handle */
126126   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
126127   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
126128   const char *zTerm,              /* Pointer to buffer containing term */
126129   int nTerm                       /* Size of term in bytes */
126130 ){
126131   SegmentNode *pTree = *ppTree;
126132   int rc;
126133   SegmentNode *pNew;
126134
126135   /* First try to append the term to the current node. Return early if 
126136   ** this is possible.
126137   */
126138   if( pTree ){
126139     int nData = pTree->nData;     /* Current size of node in bytes */
126140     int nReq = nData;             /* Required space after adding zTerm */
126141     int nPrefix;                  /* Number of bytes of prefix compression */
126142     int nSuffix;                  /* Suffix length */
126143
126144     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
126145     nSuffix = nTerm-nPrefix;
126146
126147     nReq += sqlcipher3Fts3VarintLen(nPrefix)+sqlcipher3Fts3VarintLen(nSuffix)+nSuffix;
126148     if( nReq<=p->nNodeSize || !pTree->zTerm ){
126149
126150       if( nReq>p->nNodeSize ){
126151         /* An unusual case: this is the first term to be added to the node
126152         ** and the static node buffer (p->nNodeSize bytes) is not large
126153         ** enough. Use a separately malloced buffer instead This wastes
126154         ** p->nNodeSize bytes, but since this scenario only comes about when
126155         ** the database contain two terms that share a prefix of almost 2KB, 
126156         ** this is not expected to be a serious problem. 
126157         */
126158         assert( pTree->aData==(char *)&pTree[1] );
126159         pTree->aData = (char *)sqlcipher3_malloc(nReq);
126160         if( !pTree->aData ){
126161           return SQLCIPHER_NOMEM;
126162         }
126163       }
126164
126165       if( pTree->zTerm ){
126166         /* There is no prefix-length field for first term in a node */
126167         nData += sqlcipher3Fts3PutVarint(&pTree->aData[nData], nPrefix);
126168       }
126169
126170       nData += sqlcipher3Fts3PutVarint(&pTree->aData[nData], nSuffix);
126171       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
126172       pTree->nData = nData + nSuffix;
126173       pTree->nEntry++;
126174
126175       if( isCopyTerm ){
126176         if( pTree->nMalloc<nTerm ){
126177           char *zNew = sqlcipher3_realloc(pTree->zMalloc, nTerm*2);
126178           if( !zNew ){
126179             return SQLCIPHER_NOMEM;
126180           }
126181           pTree->nMalloc = nTerm*2;
126182           pTree->zMalloc = zNew;
126183         }
126184         pTree->zTerm = pTree->zMalloc;
126185         memcpy(pTree->zTerm, zTerm, nTerm);
126186         pTree->nTerm = nTerm;
126187       }else{
126188         pTree->zTerm = (char *)zTerm;
126189         pTree->nTerm = nTerm;
126190       }
126191       return SQLCIPHER_OK;
126192     }
126193   }
126194
126195   /* If control flows to here, it was not possible to append zTerm to the
126196   ** current node. Create a new node (a right-sibling of the current node).
126197   ** If this is the first node in the tree, the term is added to it.
126198   **
126199   ** Otherwise, the term is not added to the new node, it is left empty for
126200   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
126201   ** has no parent, one is created here.
126202   */
126203   pNew = (SegmentNode *)sqlcipher3_malloc(sizeof(SegmentNode) + p->nNodeSize);
126204   if( !pNew ){
126205     return SQLCIPHER_NOMEM;
126206   }
126207   memset(pNew, 0, sizeof(SegmentNode));
126208   pNew->nData = 1 + FTS3_VARINT_MAX;
126209   pNew->aData = (char *)&pNew[1];
126210
126211   if( pTree ){
126212     SegmentNode *pParent = pTree->pParent;
126213     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
126214     if( pTree->pParent==0 ){
126215       pTree->pParent = pParent;
126216     }
126217     pTree->pRight = pNew;
126218     pNew->pLeftmost = pTree->pLeftmost;
126219     pNew->pParent = pParent;
126220     pNew->zMalloc = pTree->zMalloc;
126221     pNew->nMalloc = pTree->nMalloc;
126222     pTree->zMalloc = 0;
126223   }else{
126224     pNew->pLeftmost = pNew;
126225     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
126226   }
126227
126228   *ppTree = pNew;
126229   return rc;
126230 }
126231
126232 /*
126233 ** Helper function for fts3NodeWrite().
126234 */
126235 static int fts3TreeFinishNode(
126236   SegmentNode *pTree, 
126237   int iHeight, 
126238   sqlcipher3_int64 iLeftChild
126239 ){
126240   int nStart;
126241   assert( iHeight>=1 && iHeight<128 );
126242   nStart = FTS3_VARINT_MAX - sqlcipher3Fts3VarintLen(iLeftChild);
126243   pTree->aData[nStart] = (char)iHeight;
126244   sqlcipher3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
126245   return nStart;
126246 }
126247
126248 /*
126249 ** Write the buffer for the segment node pTree and all of its peers to the
126250 ** database. Then call this function recursively to write the parent of 
126251 ** pTree and its peers to the database. 
126252 **
126253 ** Except, if pTree is a root node, do not write it to the database. Instead,
126254 ** set output variables *paRoot and *pnRoot to contain the root node.
126255 **
126256 ** If successful, SQLCIPHER_OK is returned and output variable *piLast is
126257 ** set to the largest blockid written to the database (or zero if no
126258 ** blocks were written to the db). Otherwise, an SQLite error code is 
126259 ** returned.
126260 */
126261 static int fts3NodeWrite(
126262   Fts3Table *p,                   /* Virtual table handle */
126263   SegmentNode *pTree,             /* SegmentNode handle */
126264   int iHeight,                    /* Height of this node in tree */
126265   sqlcipher3_int64 iLeaf,            /* Block id of first leaf node */
126266   sqlcipher3_int64 iFree,            /* Block id of next free slot in %_segments */
126267   sqlcipher3_int64 *piLast,          /* OUT: Block id of last entry written */
126268   char **paRoot,                  /* OUT: Data for root node */
126269   int *pnRoot                     /* OUT: Size of root node in bytes */
126270 ){
126271   int rc = SQLCIPHER_OK;
126272
126273   if( !pTree->pParent ){
126274     /* Root node of the tree. */
126275     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
126276     *piLast = iFree-1;
126277     *pnRoot = pTree->nData - nStart;
126278     *paRoot = &pTree->aData[nStart];
126279   }else{
126280     SegmentNode *pIter;
126281     sqlcipher3_int64 iNextFree = iFree;
126282     sqlcipher3_int64 iNextLeaf = iLeaf;
126283     for(pIter=pTree->pLeftmost; pIter && rc==SQLCIPHER_OK; pIter=pIter->pRight){
126284       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
126285       int nWrite = pIter->nData - nStart;
126286   
126287       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
126288       iNextFree++;
126289       iNextLeaf += (pIter->nEntry+1);
126290     }
126291     if( rc==SQLCIPHER_OK ){
126292       assert( iNextLeaf==iFree );
126293       rc = fts3NodeWrite(
126294           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
126295       );
126296     }
126297   }
126298
126299   return rc;
126300 }
126301
126302 /*
126303 ** Free all memory allocations associated with the tree pTree.
126304 */
126305 static void fts3NodeFree(SegmentNode *pTree){
126306   if( pTree ){
126307     SegmentNode *p = pTree->pLeftmost;
126308     fts3NodeFree(p->pParent);
126309     while( p ){
126310       SegmentNode *pRight = p->pRight;
126311       if( p->aData!=(char *)&p[1] ){
126312         sqlcipher3_free(p->aData);
126313       }
126314       assert( pRight==0 || p->zMalloc==0 );
126315       sqlcipher3_free(p->zMalloc);
126316       sqlcipher3_free(p);
126317       p = pRight;
126318     }
126319   }
126320 }
126321
126322 /*
126323 ** Add a term to the segment being constructed by the SegmentWriter object
126324 ** *ppWriter. When adding the first term to a segment, *ppWriter should
126325 ** be passed NULL. This function will allocate a new SegmentWriter object
126326 ** and return it via the input/output variable *ppWriter in this case.
126327 **
126328 ** If successful, SQLCIPHER_OK is returned. Otherwise, an SQLite error code.
126329 */
126330 static int fts3SegWriterAdd(
126331   Fts3Table *p,                   /* Virtual table handle */
126332   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
126333   int isCopyTerm,                 /* True if buffer zTerm must be copied */
126334   const char *zTerm,              /* Pointer to buffer containing term */
126335   int nTerm,                      /* Size of term in bytes */
126336   const char *aDoclist,           /* Pointer to buffer containing doclist */
126337   int nDoclist                    /* Size of doclist in bytes */
126338 ){
126339   int nPrefix;                    /* Size of term prefix in bytes */
126340   int nSuffix;                    /* Size of term suffix in bytes */
126341   int nReq;                       /* Number of bytes required on leaf page */
126342   int nData;
126343   SegmentWriter *pWriter = *ppWriter;
126344
126345   if( !pWriter ){
126346     int rc;
126347     sqlcipher3_stmt *pStmt;
126348
126349     /* Allocate the SegmentWriter structure */
126350     pWriter = (SegmentWriter *)sqlcipher3_malloc(sizeof(SegmentWriter));
126351     if( !pWriter ) return SQLCIPHER_NOMEM;
126352     memset(pWriter, 0, sizeof(SegmentWriter));
126353     *ppWriter = pWriter;
126354
126355     /* Allocate a buffer in which to accumulate data */
126356     pWriter->aData = (char *)sqlcipher3_malloc(p->nNodeSize);
126357     if( !pWriter->aData ) return SQLCIPHER_NOMEM;
126358     pWriter->nSize = p->nNodeSize;
126359
126360     /* Find the next free blockid in the %_segments table */
126361     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
126362     if( rc!=SQLCIPHER_OK ) return rc;
126363     if( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
126364       pWriter->iFree = sqlcipher3_column_int64(pStmt, 0);
126365       pWriter->iFirst = pWriter->iFree;
126366     }
126367     rc = sqlcipher3_reset(pStmt);
126368     if( rc!=SQLCIPHER_OK ) return rc;
126369   }
126370   nData = pWriter->nData;
126371
126372   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
126373   nSuffix = nTerm-nPrefix;
126374
126375   /* Figure out how many bytes are required by this new entry */
126376   nReq = sqlcipher3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
126377     sqlcipher3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
126378     nSuffix +                               /* Term suffix */
126379     sqlcipher3Fts3VarintLen(nDoclist) +        /* Size of doclist */
126380     nDoclist;                               /* Doclist data */
126381
126382   if( nData>0 && nData+nReq>p->nNodeSize ){
126383     int rc;
126384
126385     /* The current leaf node is full. Write it out to the database. */
126386     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
126387     if( rc!=SQLCIPHER_OK ) return rc;
126388
126389     /* Add the current term to the interior node tree. The term added to
126390     ** the interior tree must:
126391     **
126392     **   a) be greater than the largest term on the leaf node just written
126393     **      to the database (still available in pWriter->zTerm), and
126394     **
126395     **   b) be less than or equal to the term about to be added to the new
126396     **      leaf node (zTerm/nTerm).
126397     **
126398     ** In other words, it must be the prefix of zTerm 1 byte longer than
126399     ** the common prefix (if any) of zTerm and pWriter->zTerm.
126400     */
126401     assert( nPrefix<nTerm );
126402     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
126403     if( rc!=SQLCIPHER_OK ) return rc;
126404
126405     nData = 0;
126406     pWriter->nTerm = 0;
126407
126408     nPrefix = 0;
126409     nSuffix = nTerm;
126410     nReq = 1 +                              /* varint containing prefix size */
126411       sqlcipher3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
126412       nTerm +                               /* Term suffix */
126413       sqlcipher3Fts3VarintLen(nDoclist) +      /* Size of doclist */
126414       nDoclist;                             /* Doclist data */
126415   }
126416
126417   /* If the buffer currently allocated is too small for this entry, realloc
126418   ** the buffer to make it large enough.
126419   */
126420   if( nReq>pWriter->nSize ){
126421     char *aNew = sqlcipher3_realloc(pWriter->aData, nReq);
126422     if( !aNew ) return SQLCIPHER_NOMEM;
126423     pWriter->aData = aNew;
126424     pWriter->nSize = nReq;
126425   }
126426   assert( nData+nReq<=pWriter->nSize );
126427
126428   /* Append the prefix-compressed term and doclist to the buffer. */
126429   nData += sqlcipher3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
126430   nData += sqlcipher3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
126431   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
126432   nData += nSuffix;
126433   nData += sqlcipher3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
126434   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
126435   pWriter->nData = nData + nDoclist;
126436
126437   /* Save the current term so that it can be used to prefix-compress the next.
126438   ** If the isCopyTerm parameter is true, then the buffer pointed to by
126439   ** zTerm is transient, so take a copy of the term data. Otherwise, just
126440   ** store a copy of the pointer.
126441   */
126442   if( isCopyTerm ){
126443     if( nTerm>pWriter->nMalloc ){
126444       char *zNew = sqlcipher3_realloc(pWriter->zMalloc, nTerm*2);
126445       if( !zNew ){
126446         return SQLCIPHER_NOMEM;
126447       }
126448       pWriter->nMalloc = nTerm*2;
126449       pWriter->zMalloc = zNew;
126450       pWriter->zTerm = zNew;
126451     }
126452     assert( pWriter->zTerm==pWriter->zMalloc );
126453     memcpy(pWriter->zTerm, zTerm, nTerm);
126454   }else{
126455     pWriter->zTerm = (char *)zTerm;
126456   }
126457   pWriter->nTerm = nTerm;
126458
126459   return SQLCIPHER_OK;
126460 }
126461
126462 /*
126463 ** Flush all data associated with the SegmentWriter object pWriter to the
126464 ** database. This function must be called after all terms have been added
126465 ** to the segment using fts3SegWriterAdd(). If successful, SQLCIPHER_OK is
126466 ** returned. Otherwise, an SQLite error code.
126467 */
126468 static int fts3SegWriterFlush(
126469   Fts3Table *p,                   /* Virtual table handle */
126470   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
126471   int iLevel,                     /* Value for 'level' column of %_segdir */
126472   int iIdx                        /* Value for 'idx' column of %_segdir */
126473 ){
126474   int rc;                         /* Return code */
126475   if( pWriter->pTree ){
126476     sqlcipher3_int64 iLast = 0;      /* Largest block id written to database */
126477     sqlcipher3_int64 iLastLeaf;      /* Largest leaf block id written to db */
126478     char *zRoot = NULL;           /* Pointer to buffer containing root node */
126479     int nRoot = 0;                /* Size of buffer zRoot */
126480
126481     iLastLeaf = pWriter->iFree;
126482     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
126483     if( rc==SQLCIPHER_OK ){
126484       rc = fts3NodeWrite(p, pWriter->pTree, 1,
126485           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
126486     }
126487     if( rc==SQLCIPHER_OK ){
126488       rc = fts3WriteSegdir(
126489           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
126490     }
126491   }else{
126492     /* The entire tree fits on the root node. Write it to the segdir table. */
126493     rc = fts3WriteSegdir(
126494         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
126495   }
126496   return rc;
126497 }
126498
126499 /*
126500 ** Release all memory held by the SegmentWriter object passed as the 
126501 ** first argument.
126502 */
126503 static void fts3SegWriterFree(SegmentWriter *pWriter){
126504   if( pWriter ){
126505     sqlcipher3_free(pWriter->aData);
126506     sqlcipher3_free(pWriter->zMalloc);
126507     fts3NodeFree(pWriter->pTree);
126508     sqlcipher3_free(pWriter);
126509   }
126510 }
126511
126512 /*
126513 ** The first value in the apVal[] array is assumed to contain an integer.
126514 ** This function tests if there exist any documents with docid values that
126515 ** are different from that integer. i.e. if deleting the document with docid
126516 ** pRowid would mean the FTS3 table were empty.
126517 **
126518 ** If successful, *pisEmpty is set to true if the table is empty except for
126519 ** document pRowid, or false otherwise, and SQLCIPHER_OK is returned. If an
126520 ** error occurs, an SQLite error code is returned.
126521 */
126522 static int fts3IsEmpty(Fts3Table *p, sqlcipher3_value *pRowid, int *pisEmpty){
126523   sqlcipher3_stmt *pStmt;
126524   int rc;
126525   if( p->zContentTbl ){
126526     /* If using the content=xxx option, assume the table is never empty */
126527     *pisEmpty = 0;
126528     rc = SQLCIPHER_OK;
126529   }else{
126530     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
126531     if( rc==SQLCIPHER_OK ){
126532       if( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
126533         *pisEmpty = sqlcipher3_column_int(pStmt, 0);
126534       }
126535       rc = sqlcipher3_reset(pStmt);
126536     }
126537   }
126538   return rc;
126539 }
126540
126541 /*
126542 ** Set *pnMax to the largest segment level in the database for the index
126543 ** iIndex.
126544 **
126545 ** Segment levels are stored in the 'level' column of the %_segdir table.
126546 **
126547 ** Return SQLCIPHER_OK if successful, or an SQLite error code if not.
126548 */
126549 static int fts3SegmentMaxLevel(Fts3Table *p, int iIndex, int *pnMax){
126550   sqlcipher3_stmt *pStmt;
126551   int rc;
126552   assert( iIndex>=0 && iIndex<p->nIndex );
126553
126554   /* Set pStmt to the compiled version of:
126555   **
126556   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
126557   **
126558   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
126559   */
126560   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
126561   if( rc!=SQLCIPHER_OK ) return rc;
126562   sqlcipher3_bind_int(pStmt, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
126563   sqlcipher3_bind_int(pStmt, 2, (iIndex+1)*FTS3_SEGDIR_MAXLEVEL - 1);
126564   if( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
126565     *pnMax = sqlcipher3_column_int(pStmt, 0);
126566   }
126567   return sqlcipher3_reset(pStmt);
126568 }
126569
126570 /*
126571 ** This function is used after merging multiple segments into a single large
126572 ** segment to delete the old, now redundant, segment b-trees. Specifically,
126573 ** it:
126574 ** 
126575 **   1) Deletes all %_segments entries for the segments associated with 
126576 **      each of the SegReader objects in the array passed as the third 
126577 **      argument, and
126578 **
126579 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
126580 **      entries regardless of level if (iLevel<0).
126581 **
126582 ** SQLCIPHER_OK is returned if successful, otherwise an SQLite error code.
126583 */
126584 static int fts3DeleteSegdir(
126585   Fts3Table *p,                   /* Virtual table handle */
126586   int iIndex,                     /* Index for p->aIndex */
126587   int iLevel,                     /* Level of %_segdir entries to delete */
126588   Fts3SegReader **apSegment,      /* Array of SegReader objects */
126589   int nReader                     /* Size of array apSegment */
126590 ){
126591   int rc;                         /* Return Code */
126592   int i;                          /* Iterator variable */
126593   sqlcipher3_stmt *pDelete;          /* SQL statement to delete rows */
126594
126595   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
126596   for(i=0; rc==SQLCIPHER_OK && i<nReader; i++){
126597     Fts3SegReader *pSegment = apSegment[i];
126598     if( pSegment->iStartBlock ){
126599       sqlcipher3_bind_int64(pDelete, 1, pSegment->iStartBlock);
126600       sqlcipher3_bind_int64(pDelete, 2, pSegment->iEndBlock);
126601       sqlcipher3_step(pDelete);
126602       rc = sqlcipher3_reset(pDelete);
126603     }
126604   }
126605   if( rc!=SQLCIPHER_OK ){
126606     return rc;
126607   }
126608
126609   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
126610   if( iLevel==FTS3_SEGCURSOR_ALL ){
126611     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
126612     if( rc==SQLCIPHER_OK ){
126613       sqlcipher3_bind_int(pDelete, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
126614       sqlcipher3_bind_int(pDelete, 2, (iIndex+1) * FTS3_SEGDIR_MAXLEVEL - 1);
126615     }
126616   }else{
126617     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
126618     if( rc==SQLCIPHER_OK ){
126619       sqlcipher3_bind_int(pDelete, 1, iIndex*FTS3_SEGDIR_MAXLEVEL + iLevel);
126620     }
126621   }
126622
126623   if( rc==SQLCIPHER_OK ){
126624     sqlcipher3_step(pDelete);
126625     rc = sqlcipher3_reset(pDelete);
126626   }
126627
126628   return rc;
126629 }
126630
126631 /*
126632 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
126633 ** a position list that may (or may not) feature multiple columns. This
126634 ** function adjusts the pointer *ppList and the length *pnList so that they
126635 ** identify the subset of the position list that corresponds to column iCol.
126636 **
126637 ** If there are no entries in the input position list for column iCol, then
126638 ** *pnList is set to zero before returning.
126639 */
126640 static void fts3ColumnFilter(
126641   int iCol,                       /* Column to filter on */
126642   char **ppList,                  /* IN/OUT: Pointer to position list */
126643   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
126644 ){
126645   char *pList = *ppList;
126646   int nList = *pnList;
126647   char *pEnd = &pList[nList];
126648   int iCurrent = 0;
126649   char *p = pList;
126650
126651   assert( iCol>=0 );
126652   while( 1 ){
126653     char c = 0;
126654     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
126655   
126656     if( iCol==iCurrent ){
126657       nList = (int)(p - pList);
126658       break;
126659     }
126660
126661     nList -= (int)(p - pList);
126662     pList = p;
126663     if( nList==0 ){
126664       break;
126665     }
126666     p = &pList[1];
126667     p += sqlcipher3Fts3GetVarint32(p, &iCurrent);
126668   }
126669
126670   *ppList = pList;
126671   *pnList = nList;
126672 }
126673
126674 /*
126675 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
126676 ** existing data). Grow the buffer if required.
126677 **
126678 ** If successful, return SQLCIPHER_OK. Otherwise, if an OOM error is encountered
126679 ** trying to resize the buffer, return SQLCIPHER_NOMEM.
126680 */
126681 static int fts3MsrBufferData(
126682   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
126683   char *pList,
126684   int nList
126685 ){
126686   if( nList>pMsr->nBuffer ){
126687     char *pNew;
126688     pMsr->nBuffer = nList*2;
126689     pNew = (char *)sqlcipher3_realloc(pMsr->aBuffer, pMsr->nBuffer);
126690     if( !pNew ) return SQLCIPHER_NOMEM;
126691     pMsr->aBuffer = pNew;
126692   }
126693
126694   memcpy(pMsr->aBuffer, pList, nList);
126695   return SQLCIPHER_OK;
126696 }
126697
126698 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrIncrNext(
126699   Fts3Table *p,                   /* Virtual table handle */
126700   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
126701   sqlcipher3_int64 *piDocid,         /* OUT: Docid value */
126702   char **paPoslist,               /* OUT: Pointer to position list */
126703   int *pnPoslist                  /* OUT: Size of position list in bytes */
126704 ){
126705   int nMerge = pMsr->nAdvance;
126706   Fts3SegReader **apSegment = pMsr->apSegment;
126707   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
126708     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
126709   );
126710
126711   if( nMerge==0 ){
126712     *paPoslist = 0;
126713     return SQLCIPHER_OK;
126714   }
126715
126716   while( 1 ){
126717     Fts3SegReader *pSeg;
126718     pSeg = pMsr->apSegment[0];
126719
126720     if( pSeg->pOffsetList==0 ){
126721       *paPoslist = 0;
126722       break;
126723     }else{
126724       int rc;
126725       char *pList;
126726       int nList;
126727       int j;
126728       sqlcipher3_int64 iDocid = apSegment[0]->iDocid;
126729
126730       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
126731       j = 1;
126732       while( rc==SQLCIPHER_OK 
126733         && j<nMerge
126734         && apSegment[j]->pOffsetList
126735         && apSegment[j]->iDocid==iDocid
126736       ){
126737         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
126738         j++;
126739       }
126740       if( rc!=SQLCIPHER_OK ) return rc;
126741       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
126742
126743       if( pMsr->iColFilter>=0 ){
126744         fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
126745       }
126746
126747       if( nList>0 ){
126748         if( fts3SegReaderIsPending(apSegment[0]) ){
126749           rc = fts3MsrBufferData(pMsr, pList, nList+1);
126750           if( rc!=SQLCIPHER_OK ) return rc;
126751           *paPoslist = pMsr->aBuffer;
126752           assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
126753         }else{
126754           *paPoslist = pList;
126755         }
126756         *piDocid = iDocid;
126757         *pnPoslist = nList;
126758         break;
126759       }
126760     }
126761   }
126762
126763   return SQLCIPHER_OK;
126764 }
126765
126766 static int fts3SegReaderStart(
126767   Fts3Table *p,                   /* Virtual table handle */
126768   Fts3MultiSegReader *pCsr,       /* Cursor object */
126769   const char *zTerm,              /* Term searched for (or NULL) */
126770   int nTerm                       /* Length of zTerm in bytes */
126771 ){
126772   int i;
126773   int nSeg = pCsr->nSegment;
126774
126775   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
126776   ** for, then advance each segment iterator until it points to a term of
126777   ** equal or greater value than the specified term. This prevents many
126778   ** unnecessary merge/sort operations for the case where single segment
126779   ** b-tree leaf nodes contain more than one term.
126780   */
126781   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
126782     Fts3SegReader *pSeg = pCsr->apSegment[i];
126783     do {
126784       int rc = fts3SegReaderNext(p, pSeg, 0);
126785       if( rc!=SQLCIPHER_OK ) return rc;
126786     }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
126787   }
126788   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
126789
126790   return SQLCIPHER_OK;
126791 }
126792
126793 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderStart(
126794   Fts3Table *p,                   /* Virtual table handle */
126795   Fts3MultiSegReader *pCsr,       /* Cursor object */
126796   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
126797 ){
126798   pCsr->pFilter = pFilter;
126799   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
126800 }
126801
126802 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrIncrStart(
126803   Fts3Table *p,                   /* Virtual table handle */
126804   Fts3MultiSegReader *pCsr,       /* Cursor object */
126805   int iCol,                       /* Column to match on. */
126806   const char *zTerm,              /* Term to iterate through a doclist for */
126807   int nTerm                       /* Number of bytes in zTerm */
126808 ){
126809   int i;
126810   int rc;
126811   int nSegment = pCsr->nSegment;
126812   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
126813     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
126814   );
126815
126816   assert( pCsr->pFilter==0 );
126817   assert( zTerm && nTerm>0 );
126818
126819   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
126820   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
126821   if( rc!=SQLCIPHER_OK ) return rc;
126822
126823   /* Determine how many of the segments actually point to zTerm/nTerm. */
126824   for(i=0; i<nSegment; i++){
126825     Fts3SegReader *pSeg = pCsr->apSegment[i];
126826     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
126827       break;
126828     }
126829   }
126830   pCsr->nAdvance = i;
126831
126832   /* Advance each of the segments to point to the first docid. */
126833   for(i=0; i<pCsr->nAdvance; i++){
126834     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
126835     if( rc!=SQLCIPHER_OK ) return rc;
126836   }
126837   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
126838
126839   assert( iCol<0 || iCol<p->nColumn );
126840   pCsr->iColFilter = iCol;
126841
126842   return SQLCIPHER_OK;
126843 }
126844
126845 /*
126846 ** This function is called on a MultiSegReader that has been started using
126847 ** sqlcipher3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
126848 ** have been made. Calling this function puts the MultiSegReader in such
126849 ** a state that if the next two calls are:
126850 **
126851 **   sqlcipher3Fts3SegReaderStart()
126852 **   sqlcipher3Fts3SegReaderStep()
126853 **
126854 ** then the entire doclist for the term is available in 
126855 ** MultiSegReader.aDoclist/nDoclist.
126856 */
126857 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
126858   int i;                          /* Used to iterate through segment-readers */
126859
126860   assert( pCsr->zTerm==0 );
126861   assert( pCsr->nTerm==0 );
126862   assert( pCsr->aDoclist==0 );
126863   assert( pCsr->nDoclist==0 );
126864
126865   pCsr->nAdvance = 0;
126866   pCsr->bRestart = 1;
126867   for(i=0; i<pCsr->nSegment; i++){
126868     pCsr->apSegment[i]->pOffsetList = 0;
126869     pCsr->apSegment[i]->nOffsetList = 0;
126870     pCsr->apSegment[i]->iDocid = 0;
126871   }
126872
126873   return SQLCIPHER_OK;
126874 }
126875
126876
126877 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderStep(
126878   Fts3Table *p,                   /* Virtual table handle */
126879   Fts3MultiSegReader *pCsr        /* Cursor object */
126880 ){
126881   int rc = SQLCIPHER_OK;
126882
126883   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
126884   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
126885   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
126886   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
126887   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
126888   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
126889
126890   Fts3SegReader **apSegment = pCsr->apSegment;
126891   int nSegment = pCsr->nSegment;
126892   Fts3SegFilter *pFilter = pCsr->pFilter;
126893   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
126894     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
126895   );
126896
126897   if( pCsr->nSegment==0 ) return SQLCIPHER_OK;
126898
126899   do {
126900     int nMerge;
126901     int i;
126902   
126903     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
126904     ** forward. Then sort the list in order of current term again.  
126905     */
126906     for(i=0; i<pCsr->nAdvance; i++){
126907       rc = fts3SegReaderNext(p, apSegment[i], 0);
126908       if( rc!=SQLCIPHER_OK ) return rc;
126909     }
126910     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
126911     pCsr->nAdvance = 0;
126912
126913     /* If all the seg-readers are at EOF, we're finished. return SQLCIPHER_OK. */
126914     assert( rc==SQLCIPHER_OK );
126915     if( apSegment[0]->aNode==0 ) break;
126916
126917     pCsr->nTerm = apSegment[0]->nTerm;
126918     pCsr->zTerm = apSegment[0]->zTerm;
126919
126920     /* If this is a prefix-search, and if the term that apSegment[0] points
126921     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
126922     ** required callbacks have been made. In this case exit early.
126923     **
126924     ** Similarly, if this is a search for an exact match, and the first term
126925     ** of segment apSegment[0] is not a match, exit early.
126926     */
126927     if( pFilter->zTerm && !isScan ){
126928       if( pCsr->nTerm<pFilter->nTerm 
126929        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
126930        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
126931       ){
126932         break;
126933       }
126934     }
126935
126936     nMerge = 1;
126937     while( nMerge<nSegment 
126938         && apSegment[nMerge]->aNode
126939         && apSegment[nMerge]->nTerm==pCsr->nTerm 
126940         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
126941     ){
126942       nMerge++;
126943     }
126944
126945     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
126946     if( nMerge==1 
126947      && !isIgnoreEmpty 
126948      && !isFirst 
126949      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
126950     ){
126951       pCsr->nDoclist = apSegment[0]->nDoclist;
126952       if( fts3SegReaderIsPending(apSegment[0]) ){
126953         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
126954         pCsr->aDoclist = pCsr->aBuffer;
126955       }else{
126956         pCsr->aDoclist = apSegment[0]->aDoclist;
126957       }
126958       if( rc==SQLCIPHER_OK ) rc = SQLCIPHER_ROW;
126959     }else{
126960       int nDoclist = 0;           /* Size of doclist */
126961       sqlcipher3_int64 iPrev = 0;    /* Previous docid stored in doclist */
126962
126963       /* The current term of the first nMerge entries in the array
126964       ** of Fts3SegReader objects is the same. The doclists must be merged
126965       ** and a single term returned with the merged doclist.
126966       */
126967       for(i=0; i<nMerge; i++){
126968         fts3SegReaderFirstDocid(p, apSegment[i]);
126969       }
126970       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
126971       while( apSegment[0]->pOffsetList ){
126972         int j;                    /* Number of segments that share a docid */
126973         char *pList;
126974         int nList;
126975         int nByte;
126976         sqlcipher3_int64 iDocid = apSegment[0]->iDocid;
126977         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
126978         j = 1;
126979         while( j<nMerge
126980             && apSegment[j]->pOffsetList
126981             && apSegment[j]->iDocid==iDocid
126982         ){
126983           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
126984           j++;
126985         }
126986
126987         if( isColFilter ){
126988           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
126989         }
126990
126991         if( !isIgnoreEmpty || nList>0 ){
126992
126993           /* Calculate the 'docid' delta value to write into the merged 
126994           ** doclist. */
126995           sqlcipher3_int64 iDelta;
126996           if( p->bDescIdx && nDoclist>0 ){
126997             iDelta = iPrev - iDocid;
126998           }else{
126999             iDelta = iDocid - iPrev;
127000           }
127001           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
127002           assert( nDoclist>0 || iDelta==iDocid );
127003
127004           nByte = sqlcipher3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
127005           if( nDoclist+nByte>pCsr->nBuffer ){
127006             char *aNew;
127007             pCsr->nBuffer = (nDoclist+nByte)*2;
127008             aNew = sqlcipher3_realloc(pCsr->aBuffer, pCsr->nBuffer);
127009             if( !aNew ){
127010               return SQLCIPHER_NOMEM;
127011             }
127012             pCsr->aBuffer = aNew;
127013           }
127014
127015           if( isFirst ){
127016             char *a = &pCsr->aBuffer[nDoclist];
127017             int nWrite;
127018            
127019             nWrite = sqlcipher3Fts3FirstFilter(iDelta, pList, nList, a);
127020             if( nWrite ){
127021               iPrev = iDocid;
127022               nDoclist += nWrite;
127023             }
127024           }else{
127025             nDoclist += sqlcipher3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
127026             iPrev = iDocid;
127027             if( isRequirePos ){
127028               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
127029               nDoclist += nList;
127030               pCsr->aBuffer[nDoclist++] = '\0';
127031             }
127032           }
127033         }
127034
127035         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
127036       }
127037       if( nDoclist>0 ){
127038         pCsr->aDoclist = pCsr->aBuffer;
127039         pCsr->nDoclist = nDoclist;
127040         rc = SQLCIPHER_ROW;
127041       }
127042     }
127043     pCsr->nAdvance = nMerge;
127044   }while( rc==SQLCIPHER_OK );
127045
127046   return rc;
127047 }
127048
127049
127050 SQLCIPHER_PRIVATE void sqlcipher3Fts3SegReaderFinish(
127051   Fts3MultiSegReader *pCsr       /* Cursor object */
127052 ){
127053   if( pCsr ){
127054     int i;
127055     for(i=0; i<pCsr->nSegment; i++){
127056       sqlcipher3Fts3SegReaderFree(pCsr->apSegment[i]);
127057     }
127058     sqlcipher3_free(pCsr->apSegment);
127059     sqlcipher3_free(pCsr->aBuffer);
127060
127061     pCsr->nSegment = 0;
127062     pCsr->apSegment = 0;
127063     pCsr->aBuffer = 0;
127064   }
127065 }
127066
127067 /*
127068 ** Merge all level iLevel segments in the database into a single 
127069 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
127070 ** single segment with a level equal to the numerically largest level 
127071 ** currently present in the database.
127072 **
127073 ** If this function is called with iLevel<0, but there is only one
127074 ** segment in the database, SQLCIPHER_DONE is returned immediately. 
127075 ** Otherwise, if successful, SQLCIPHER_OK is returned. If an error occurs, 
127076 ** an SQLite error code is returned.
127077 */
127078 static int fts3SegmentMerge(Fts3Table *p, int iIndex, int iLevel){
127079   int rc;                         /* Return code */
127080   int iIdx = 0;                   /* Index of new segment */
127081   int iNewLevel = 0;              /* Level/index to create new segment at */
127082   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
127083   Fts3SegFilter filter;           /* Segment term filter condition */
127084   Fts3MultiSegReader csr;        /* Cursor to iterate through level(s) */
127085   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
127086
127087   assert( iLevel==FTS3_SEGCURSOR_ALL
127088        || iLevel==FTS3_SEGCURSOR_PENDING
127089        || iLevel>=0
127090   );
127091   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
127092   assert( iIndex>=0 && iIndex<p->nIndex );
127093
127094   rc = sqlcipher3Fts3SegReaderCursor(p, iIndex, iLevel, 0, 0, 1, 0, &csr);
127095   if( rc!=SQLCIPHER_OK || csr.nSegment==0 ) goto finished;
127096
127097   if( iLevel==FTS3_SEGCURSOR_ALL ){
127098     /* This call is to merge all segments in the database to a single
127099     ** segment. The level of the new segment is equal to the the numerically 
127100     ** greatest segment level currently present in the database for this
127101     ** index. The idx of the new segment is always 0.  */
127102     if( csr.nSegment==1 ){
127103       rc = SQLCIPHER_DONE;
127104       goto finished;
127105     }
127106     rc = fts3SegmentMaxLevel(p, iIndex, &iNewLevel);
127107     bIgnoreEmpty = 1;
127108
127109   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
127110     iNewLevel = iIndex * FTS3_SEGDIR_MAXLEVEL; 
127111     rc = fts3AllocateSegdirIdx(p, iIndex, 0, &iIdx);
127112   }else{
127113     /* This call is to merge all segments at level iLevel. find the next
127114     ** available segment index at level iLevel+1. The call to
127115     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
127116     ** a single iLevel+2 segment if necessary.  */
127117     rc = fts3AllocateSegdirIdx(p, iIndex, iLevel+1, &iIdx);
127118     iNewLevel = iIndex * FTS3_SEGDIR_MAXLEVEL + iLevel+1;
127119   }
127120   if( rc!=SQLCIPHER_OK ) goto finished;
127121   assert( csr.nSegment>0 );
127122   assert( iNewLevel>=(iIndex*FTS3_SEGDIR_MAXLEVEL) );
127123   assert( iNewLevel<((iIndex+1)*FTS3_SEGDIR_MAXLEVEL) );
127124
127125   memset(&filter, 0, sizeof(Fts3SegFilter));
127126   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
127127   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
127128
127129   rc = sqlcipher3Fts3SegReaderStart(p, &csr, &filter);
127130   while( SQLCIPHER_OK==rc ){
127131     rc = sqlcipher3Fts3SegReaderStep(p, &csr);
127132     if( rc!=SQLCIPHER_ROW ) break;
127133     rc = fts3SegWriterAdd(p, &pWriter, 1, 
127134         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
127135   }
127136   if( rc!=SQLCIPHER_OK ) goto finished;
127137   assert( pWriter );
127138
127139   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
127140     rc = fts3DeleteSegdir(p, iIndex, iLevel, csr.apSegment, csr.nSegment);
127141     if( rc!=SQLCIPHER_OK ) goto finished;
127142   }
127143   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
127144
127145  finished:
127146   fts3SegWriterFree(pWriter);
127147   sqlcipher3Fts3SegReaderFinish(&csr);
127148   return rc;
127149 }
127150
127151
127152 /* 
127153 ** Flush the contents of pendingTerms to level 0 segments.
127154 */
127155 SQLCIPHER_PRIVATE int sqlcipher3Fts3PendingTermsFlush(Fts3Table *p){
127156   int rc = SQLCIPHER_OK;
127157   int i;
127158   for(i=0; rc==SQLCIPHER_OK && i<p->nIndex; i++){
127159     rc = fts3SegmentMerge(p, i, FTS3_SEGCURSOR_PENDING);
127160     if( rc==SQLCIPHER_DONE ) rc = SQLCIPHER_OK;
127161   }
127162   sqlcipher3Fts3PendingTermsClear(p);
127163   return rc;
127164 }
127165
127166 /*
127167 ** Encode N integers as varints into a blob.
127168 */
127169 static void fts3EncodeIntArray(
127170   int N,             /* The number of integers to encode */
127171   u32 *a,            /* The integer values */
127172   char *zBuf,        /* Write the BLOB here */
127173   int *pNBuf         /* Write number of bytes if zBuf[] used here */
127174 ){
127175   int i, j;
127176   for(i=j=0; i<N; i++){
127177     j += sqlcipher3Fts3PutVarint(&zBuf[j], (sqlcipher3_int64)a[i]);
127178   }
127179   *pNBuf = j;
127180 }
127181
127182 /*
127183 ** Decode a blob of varints into N integers
127184 */
127185 static void fts3DecodeIntArray(
127186   int N,             /* The number of integers to decode */
127187   u32 *a,            /* Write the integer values */
127188   const char *zBuf,  /* The BLOB containing the varints */
127189   int nBuf           /* size of the BLOB */
127190 ){
127191   int i, j;
127192   UNUSED_PARAMETER(nBuf);
127193   for(i=j=0; i<N; i++){
127194     sqlcipher3_int64 x;
127195     j += sqlcipher3Fts3GetVarint(&zBuf[j], &x);
127196     assert(j<=nBuf);
127197     a[i] = (u32)(x & 0xffffffff);
127198   }
127199 }
127200
127201 /*
127202 ** Insert the sizes (in tokens) for each column of the document
127203 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
127204 ** a blob of varints.
127205 */
127206 static void fts3InsertDocsize(
127207   int *pRC,                       /* Result code */
127208   Fts3Table *p,                   /* Table into which to insert */
127209   u32 *aSz                        /* Sizes of each column, in tokens */
127210 ){
127211   char *pBlob;             /* The BLOB encoding of the document size */
127212   int nBlob;               /* Number of bytes in the BLOB */
127213   sqlcipher3_stmt *pStmt;     /* Statement used to insert the encoding */
127214   int rc;                  /* Result code from subfunctions */
127215
127216   if( *pRC ) return;
127217   pBlob = sqlcipher3_malloc( 10*p->nColumn );
127218   if( pBlob==0 ){
127219     *pRC = SQLCIPHER_NOMEM;
127220     return;
127221   }
127222   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
127223   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
127224   if( rc ){
127225     sqlcipher3_free(pBlob);
127226     *pRC = rc;
127227     return;
127228   }
127229   sqlcipher3_bind_int64(pStmt, 1, p->iPrevDocid);
127230   sqlcipher3_bind_blob(pStmt, 2, pBlob, nBlob, sqlcipher3_free);
127231   sqlcipher3_step(pStmt);
127232   *pRC = sqlcipher3_reset(pStmt);
127233 }
127234
127235 /*
127236 ** Record 0 of the %_stat table contains a blob consisting of N varints,
127237 ** where N is the number of user defined columns in the fts3 table plus
127238 ** two. If nCol is the number of user defined columns, then values of the 
127239 ** varints are set as follows:
127240 **
127241 **   Varint 0:       Total number of rows in the table.
127242 **
127243 **   Varint 1..nCol: For each column, the total number of tokens stored in
127244 **                   the column for all rows of the table.
127245 **
127246 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
127247 **                   columns of all rows of the table.
127248 **
127249 */
127250 static void fts3UpdateDocTotals(
127251   int *pRC,                       /* The result code */
127252   Fts3Table *p,                   /* Table being updated */
127253   u32 *aSzIns,                    /* Size increases */
127254   u32 *aSzDel,                    /* Size decreases */
127255   int nChng                       /* Change in the number of documents */
127256 ){
127257   char *pBlob;             /* Storage for BLOB written into %_stat */
127258   int nBlob;               /* Size of BLOB written into %_stat */
127259   u32 *a;                  /* Array of integers that becomes the BLOB */
127260   sqlcipher3_stmt *pStmt;     /* Statement for reading and writing */
127261   int i;                   /* Loop counter */
127262   int rc;                  /* Result code from subfunctions */
127263
127264   const int nStat = p->nColumn+2;
127265
127266   if( *pRC ) return;
127267   a = sqlcipher3_malloc( (sizeof(u32)+10)*nStat );
127268   if( a==0 ){
127269     *pRC = SQLCIPHER_NOMEM;
127270     return;
127271   }
127272   pBlob = (char*)&a[nStat];
127273   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
127274   if( rc ){
127275     sqlcipher3_free(a);
127276     *pRC = rc;
127277     return;
127278   }
127279   if( sqlcipher3_step(pStmt)==SQLCIPHER_ROW ){
127280     fts3DecodeIntArray(nStat, a,
127281          sqlcipher3_column_blob(pStmt, 0),
127282          sqlcipher3_column_bytes(pStmt, 0));
127283   }else{
127284     memset(a, 0, sizeof(u32)*(nStat) );
127285   }
127286   sqlcipher3_reset(pStmt);
127287   if( nChng<0 && a[0]<(u32)(-nChng) ){
127288     a[0] = 0;
127289   }else{
127290     a[0] += nChng;
127291   }
127292   for(i=0; i<p->nColumn+1; i++){
127293     u32 x = a[i+1];
127294     if( x+aSzIns[i] < aSzDel[i] ){
127295       x = 0;
127296     }else{
127297       x = x + aSzIns[i] - aSzDel[i];
127298     }
127299     a[i+1] = x;
127300   }
127301   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
127302   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
127303   if( rc ){
127304     sqlcipher3_free(a);
127305     *pRC = rc;
127306     return;
127307   }
127308   sqlcipher3_bind_blob(pStmt, 1, pBlob, nBlob, SQLCIPHER_STATIC);
127309   sqlcipher3_step(pStmt);
127310   *pRC = sqlcipher3_reset(pStmt);
127311   sqlcipher3_free(a);
127312 }
127313
127314 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
127315   int i;
127316   int bSeenDone = 0;
127317   int rc = SQLCIPHER_OK;
127318   for(i=0; rc==SQLCIPHER_OK && i<p->nIndex; i++){
127319     rc = fts3SegmentMerge(p, i, FTS3_SEGCURSOR_ALL);
127320     if( rc==SQLCIPHER_DONE ){
127321       bSeenDone = 1;
127322       rc = SQLCIPHER_OK;
127323     }
127324   }
127325   sqlcipher3Fts3SegmentsClose(p);
127326   sqlcipher3Fts3PendingTermsClear(p);
127327
127328   return (rc==SQLCIPHER_OK && bReturnDone && bSeenDone) ? SQLCIPHER_DONE : rc;
127329 }
127330
127331 /*
127332 ** This function is called when the user executes the following statement:
127333 **
127334 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
127335 **
127336 ** The entire FTS index is discarded and rebuilt. If the table is one 
127337 ** created using the content=xxx option, then the new index is based on
127338 ** the current contents of the xxx table. Otherwise, it is rebuilt based
127339 ** on the contents of the %_content table.
127340 */
127341 static int fts3DoRebuild(Fts3Table *p){
127342   int rc;                         /* Return Code */
127343
127344   rc = fts3DeleteAll(p, 0);
127345   if( rc==SQLCIPHER_OK ){
127346     u32 *aSz = 0;
127347     u32 *aSzIns = 0;
127348     u32 *aSzDel = 0;
127349     sqlcipher3_stmt *pStmt = 0;
127350     int nEntry = 0;
127351
127352     /* Compose and prepare an SQL statement to loop through the content table */
127353     char *zSql = sqlcipher3_mprintf("SELECT %s" , p->zReadExprlist);
127354     if( !zSql ){
127355       rc = SQLCIPHER_NOMEM;
127356     }else{
127357       rc = sqlcipher3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
127358       sqlcipher3_free(zSql);
127359     }
127360
127361     if( rc==SQLCIPHER_OK ){
127362       int nByte = sizeof(u32) * (p->nColumn+1)*3;
127363       aSz = (u32 *)sqlcipher3_malloc(nByte);
127364       if( aSz==0 ){
127365         rc = SQLCIPHER_NOMEM;
127366       }else{
127367         memset(aSz, 0, nByte);
127368         aSzIns = &aSz[p->nColumn+1];
127369         aSzDel = &aSzIns[p->nColumn+1];
127370       }
127371     }
127372
127373     while( rc==SQLCIPHER_OK && SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
127374       int iCol;
127375       rc = fts3PendingTermsDocid(p, sqlcipher3_column_int64(pStmt, 0));
127376       aSz[p->nColumn] = 0;
127377       for(iCol=0; rc==SQLCIPHER_OK && iCol<p->nColumn; iCol++){
127378         const char *z = (const char *) sqlcipher3_column_text(pStmt, iCol+1);
127379         rc = fts3PendingTermsAdd(p, z, iCol, &aSz[iCol]);
127380         aSz[p->nColumn] += sqlcipher3_column_bytes(pStmt, iCol+1);
127381       }
127382       if( p->bHasDocsize ){
127383         fts3InsertDocsize(&rc, p, aSz);
127384       }
127385       if( rc!=SQLCIPHER_OK ){
127386         sqlcipher3_finalize(pStmt);
127387         pStmt = 0;
127388       }else{
127389         nEntry++;
127390         for(iCol=0; iCol<=p->nColumn; iCol++){
127391           aSzIns[iCol] += aSz[iCol];
127392         }
127393       }
127394     }
127395     if( p->bHasStat ){
127396       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
127397     }
127398     sqlcipher3_free(aSz);
127399
127400     if( pStmt ){
127401       int rc2 = sqlcipher3_finalize(pStmt);
127402       if( rc==SQLCIPHER_OK ){
127403         rc = rc2;
127404       }
127405     }
127406   }
127407
127408   return rc;
127409 }
127410
127411 /*
127412 ** Handle a 'special' INSERT of the form:
127413 **
127414 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
127415 **
127416 ** Argument pVal contains the result of <expr>. Currently the only 
127417 ** meaningful value to insert is the text 'optimize'.
127418 */
127419 static int fts3SpecialInsert(Fts3Table *p, sqlcipher3_value *pVal){
127420   int rc;                         /* Return Code */
127421   const char *zVal = (const char *)sqlcipher3_value_text(pVal);
127422   int nVal = sqlcipher3_value_bytes(pVal);
127423
127424   if( !zVal ){
127425     return SQLCIPHER_NOMEM;
127426   }else if( nVal==8 && 0==sqlcipher3_strnicmp(zVal, "optimize", 8) ){
127427     rc = fts3DoOptimize(p, 0);
127428   }else if( nVal==7 && 0==sqlcipher3_strnicmp(zVal, "rebuild", 7) ){
127429     rc = fts3DoRebuild(p);
127430 #ifdef SQLCIPHER_TEST
127431   }else if( nVal>9 && 0==sqlcipher3_strnicmp(zVal, "nodesize=", 9) ){
127432     p->nNodeSize = atoi(&zVal[9]);
127433     rc = SQLCIPHER_OK;
127434   }else if( nVal>11 && 0==sqlcipher3_strnicmp(zVal, "maxpending=", 9) ){
127435     p->nMaxPendingData = atoi(&zVal[11]);
127436     rc = SQLCIPHER_OK;
127437 #endif
127438   }else{
127439     rc = SQLCIPHER_ERROR;
127440   }
127441
127442   return rc;
127443 }
127444
127445 /*
127446 ** Delete all cached deferred doclists. Deferred doclists are cached
127447 ** (allocated) by the sqlcipher3Fts3CacheDeferredDoclists() function.
127448 */
127449 SQLCIPHER_PRIVATE void sqlcipher3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
127450   Fts3DeferredToken *pDef;
127451   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
127452     fts3PendingListDelete(pDef->pList);
127453     pDef->pList = 0;
127454   }
127455 }
127456
127457 /*
127458 ** Free all entries in the pCsr->pDeffered list. Entries are added to 
127459 ** this list using sqlcipher3Fts3DeferToken().
127460 */
127461 SQLCIPHER_PRIVATE void sqlcipher3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
127462   Fts3DeferredToken *pDef;
127463   Fts3DeferredToken *pNext;
127464   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
127465     pNext = pDef->pNext;
127466     fts3PendingListDelete(pDef->pList);
127467     sqlcipher3_free(pDef);
127468   }
127469   pCsr->pDeferred = 0;
127470 }
127471
127472 /*
127473 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
127474 ** based on the row that pCsr currently points to.
127475 **
127476 ** A deferred-doclist is like any other doclist with position information
127477 ** included, except that it only contains entries for a single row of the
127478 ** table, not for all rows.
127479 */
127480 SQLCIPHER_PRIVATE int sqlcipher3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
127481   int rc = SQLCIPHER_OK;             /* Return code */
127482   if( pCsr->pDeferred ){
127483     int i;                        /* Used to iterate through table columns */
127484     sqlcipher3_int64 iDocid;         /* Docid of the row pCsr points to */
127485     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
127486   
127487     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
127488     sqlcipher3_tokenizer *pT = p->pTokenizer;
127489     sqlcipher3_tokenizer_module const *pModule = pT->pModule;
127490    
127491     assert( pCsr->isRequireSeek==0 );
127492     iDocid = sqlcipher3_column_int64(pCsr->pStmt, 0);
127493   
127494     for(i=0; i<p->nColumn && rc==SQLCIPHER_OK; i++){
127495       const char *zText = (const char *)sqlcipher3_column_text(pCsr->pStmt, i+1);
127496       sqlcipher3_tokenizer_cursor *pTC = 0;
127497   
127498       rc = pModule->xOpen(pT, zText, -1, &pTC);
127499       while( rc==SQLCIPHER_OK ){
127500         char const *zToken;       /* Buffer containing token */
127501         int nToken;               /* Number of bytes in token */
127502         int iDum1, iDum2;         /* Dummy variables */
127503         int iPos;                 /* Position of token in zText */
127504   
127505         pTC->pTokenizer = pT;
127506         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
127507         for(pDef=pCsr->pDeferred; pDef && rc==SQLCIPHER_OK; pDef=pDef->pNext){
127508           Fts3PhraseToken *pPT = pDef->pToken;
127509           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
127510            && (pPT->bFirst==0 || iPos==0)
127511            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
127512            && (0==memcmp(zToken, pPT->z, pPT->n))
127513           ){
127514             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
127515           }
127516         }
127517       }
127518       if( pTC ) pModule->xClose(pTC);
127519       if( rc==SQLCIPHER_DONE ) rc = SQLCIPHER_OK;
127520     }
127521   
127522     for(pDef=pCsr->pDeferred; pDef && rc==SQLCIPHER_OK; pDef=pDef->pNext){
127523       if( pDef->pList ){
127524         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
127525       }
127526     }
127527   }
127528
127529   return rc;
127530 }
127531
127532 SQLCIPHER_PRIVATE int sqlcipher3Fts3DeferredTokenList(
127533   Fts3DeferredToken *p, 
127534   char **ppData, 
127535   int *pnData
127536 ){
127537   char *pRet;
127538   int nSkip;
127539   sqlcipher3_int64 dummy;
127540
127541   *ppData = 0;
127542   *pnData = 0;
127543
127544   if( p->pList==0 ){
127545     return SQLCIPHER_OK;
127546   }
127547
127548   pRet = (char *)sqlcipher3_malloc(p->pList->nData);
127549   if( !pRet ) return SQLCIPHER_NOMEM;
127550
127551   nSkip = sqlcipher3Fts3GetVarint(p->pList->aData, &dummy);
127552   *pnData = p->pList->nData - nSkip;
127553   *ppData = pRet;
127554   
127555   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
127556   return SQLCIPHER_OK;
127557 }
127558
127559 /*
127560 ** Add an entry for token pToken to the pCsr->pDeferred list.
127561 */
127562 SQLCIPHER_PRIVATE int sqlcipher3Fts3DeferToken(
127563   Fts3Cursor *pCsr,               /* Fts3 table cursor */
127564   Fts3PhraseToken *pToken,        /* Token to defer */
127565   int iCol                        /* Column that token must appear in (or -1) */
127566 ){
127567   Fts3DeferredToken *pDeferred;
127568   pDeferred = sqlcipher3_malloc(sizeof(*pDeferred));
127569   if( !pDeferred ){
127570     return SQLCIPHER_NOMEM;
127571   }
127572   memset(pDeferred, 0, sizeof(*pDeferred));
127573   pDeferred->pToken = pToken;
127574   pDeferred->pNext = pCsr->pDeferred; 
127575   pDeferred->iCol = iCol;
127576   pCsr->pDeferred = pDeferred;
127577
127578   assert( pToken->pDeferred==0 );
127579   pToken->pDeferred = pDeferred;
127580
127581   return SQLCIPHER_OK;
127582 }
127583
127584 /*
127585 ** SQLite value pRowid contains the rowid of a row that may or may not be
127586 ** present in the FTS3 table. If it is, delete it and adjust the contents
127587 ** of subsiduary data structures accordingly.
127588 */
127589 static int fts3DeleteByRowid(
127590   Fts3Table *p, 
127591   sqlcipher3_value *pRowid, 
127592   int *pnDoc,
127593   u32 *aSzDel
127594 ){
127595   int isEmpty = 0;
127596   int rc = fts3IsEmpty(p, pRowid, &isEmpty);
127597   if( rc==SQLCIPHER_OK ){
127598     if( isEmpty ){
127599       /* Deleting this row means the whole table is empty. In this case
127600       ** delete the contents of all three tables and throw away any
127601       ** data in the pendingTerms hash table.  */
127602       rc = fts3DeleteAll(p, 1);
127603       *pnDoc = *pnDoc - 1;
127604     }else{
127605       sqlcipher3_int64 iRemove = sqlcipher3_value_int64(pRowid);
127606       rc = fts3PendingTermsDocid(p, iRemove);
127607       fts3DeleteTerms(&rc, p, pRowid, aSzDel);
127608       if( p->zContentTbl==0 ){
127609         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
127610         if( sqlcipher3_changes(p->db) ) *pnDoc = *pnDoc - 1;
127611       }else{
127612         *pnDoc = *pnDoc - 1;
127613       }
127614       if( p->bHasDocsize ){
127615         fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
127616       }
127617     }
127618   }
127619
127620   return rc;
127621 }
127622
127623 /*
127624 ** This function does the work for the xUpdate method of FTS3 virtual
127625 ** tables.
127626 */
127627 SQLCIPHER_PRIVATE int sqlcipher3Fts3UpdateMethod(
127628   sqlcipher3_vtab *pVtab,            /* FTS3 vtab object */
127629   int nArg,                       /* Size of argument array */
127630   sqlcipher3_value **apVal,          /* Array of arguments */
127631   sqlcipher_int64 *pRowid            /* OUT: The affected (or effected) rowid */
127632 ){
127633   Fts3Table *p = (Fts3Table *)pVtab;
127634   int rc = SQLCIPHER_OK;             /* Return Code */
127635   int isRemove = 0;               /* True for an UPDATE or DELETE */
127636   u32 *aSzIns = 0;                /* Sizes of inserted documents */
127637   u32 *aSzDel;                    /* Sizes of deleted documents */
127638   int nChng = 0;                  /* Net change in number of documents */
127639   int bInsertDone = 0;
127640
127641   assert( p->pSegments==0 );
127642
127643   /* Check for a "special" INSERT operation. One of the form:
127644   **
127645   **   INSERT INTO xyz(xyz) VALUES('command');
127646   */
127647   if( nArg>1 
127648    && sqlcipher3_value_type(apVal[0])==SQLCIPHER_NULL 
127649    && sqlcipher3_value_type(apVal[p->nColumn+2])!=SQLCIPHER_NULL 
127650   ){
127651     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
127652     goto update_out;
127653   }
127654
127655   /* Allocate space to hold the change in document sizes */
127656   aSzIns = sqlcipher3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
127657   if( aSzIns==0 ){
127658     rc = SQLCIPHER_NOMEM;
127659     goto update_out;
127660   }
127661   aSzDel = &aSzIns[p->nColumn+1];
127662   memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
127663
127664   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
127665   ** value, then this operation requires constraint handling.
127666   **
127667   ** If the on-conflict mode is REPLACE, this means that the existing row
127668   ** should be deleted from the database before inserting the new row. Or,
127669   ** if the on-conflict mode is other than REPLACE, then this method must
127670   ** detect the conflict and return SQLCIPHER_CONSTRAINT before beginning to
127671   ** modify the database file.
127672   */
127673   if( nArg>1 && p->zContentTbl==0 ){
127674     /* Find the value object that holds the new rowid value. */
127675     sqlcipher3_value *pNewRowid = apVal[3+p->nColumn];
127676     if( sqlcipher3_value_type(pNewRowid)==SQLCIPHER_NULL ){
127677       pNewRowid = apVal[1];
127678     }
127679
127680     if( sqlcipher3_value_type(pNewRowid)!=SQLCIPHER_NULL && ( 
127681         sqlcipher3_value_type(apVal[0])==SQLCIPHER_NULL
127682      || sqlcipher3_value_int64(apVal[0])!=sqlcipher3_value_int64(pNewRowid)
127683     )){
127684       /* The new rowid is not NULL (in this case the rowid will be
127685       ** automatically assigned and there is no chance of a conflict), and 
127686       ** the statement is either an INSERT or an UPDATE that modifies the
127687       ** rowid column. So if the conflict mode is REPLACE, then delete any
127688       ** existing row with rowid=pNewRowid. 
127689       **
127690       ** Or, if the conflict mode is not REPLACE, insert the new record into 
127691       ** the %_content table. If we hit the duplicate rowid constraint (or any
127692       ** other error) while doing so, return immediately.
127693       **
127694       ** This branch may also run if pNewRowid contains a value that cannot
127695       ** be losslessly converted to an integer. In this case, the eventual 
127696       ** call to fts3InsertData() (either just below or further on in this
127697       ** function) will return SQLCIPHER_MISMATCH. If fts3DeleteByRowid is 
127698       ** invoked, it will delete zero rows (since no row will have
127699       ** docid=$pNewRowid if $pNewRowid is not an integer value).
127700       */
127701       if( sqlcipher3_vtab_on_conflict(p->db)==SQLCIPHER_REPLACE ){
127702         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
127703       }else{
127704         rc = fts3InsertData(p, apVal, pRowid);
127705         bInsertDone = 1;
127706       }
127707     }
127708   }
127709   if( rc!=SQLCIPHER_OK ){
127710     goto update_out;
127711   }
127712
127713   /* If this is a DELETE or UPDATE operation, remove the old record. */
127714   if( sqlcipher3_value_type(apVal[0])!=SQLCIPHER_NULL ){
127715     assert( sqlcipher3_value_type(apVal[0])==SQLCIPHER_INTEGER );
127716     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
127717     isRemove = 1;
127718   }
127719   
127720   /* If this is an INSERT or UPDATE operation, insert the new record. */
127721   if( nArg>1 && rc==SQLCIPHER_OK ){
127722     if( bInsertDone==0 ){
127723       rc = fts3InsertData(p, apVal, pRowid);
127724       if( rc==SQLCIPHER_CONSTRAINT && p->zContentTbl==0 ){
127725         rc = FTS_CORRUPT_VTAB;
127726       }
127727     }
127728     if( rc==SQLCIPHER_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
127729       rc = fts3PendingTermsDocid(p, *pRowid);
127730     }
127731     if( rc==SQLCIPHER_OK ){
127732       assert( p->iPrevDocid==*pRowid );
127733       rc = fts3InsertTerms(p, apVal, aSzIns);
127734     }
127735     if( p->bHasDocsize ){
127736       fts3InsertDocsize(&rc, p, aSzIns);
127737     }
127738     nChng++;
127739   }
127740
127741   if( p->bHasStat ){
127742     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
127743   }
127744
127745  update_out:
127746   sqlcipher3_free(aSzIns);
127747   sqlcipher3Fts3SegmentsClose(p);
127748   return rc;
127749 }
127750
127751 /* 
127752 ** Flush any data in the pending-terms hash table to disk. If successful,
127753 ** merge all segments in the database (including the new segment, if 
127754 ** there was any data to flush) into a single segment. 
127755 */
127756 SQLCIPHER_PRIVATE int sqlcipher3Fts3Optimize(Fts3Table *p){
127757   int rc;
127758   rc = sqlcipher3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
127759   if( rc==SQLCIPHER_OK ){
127760     rc = fts3DoOptimize(p, 1);
127761     if( rc==SQLCIPHER_OK || rc==SQLCIPHER_DONE ){
127762       int rc2 = sqlcipher3_exec(p->db, "RELEASE fts3", 0, 0, 0);
127763       if( rc2!=SQLCIPHER_OK ) rc = rc2;
127764     }else{
127765       sqlcipher3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
127766       sqlcipher3_exec(p->db, "RELEASE fts3", 0, 0, 0);
127767     }
127768   }
127769   sqlcipher3Fts3SegmentsClose(p);
127770   return rc;
127771 }
127772
127773 #endif
127774
127775 /************** End of fts3_write.c ******************************************/
127776 /************** Begin file fts3_snippet.c ************************************/
127777 /*
127778 ** 2009 Oct 23
127779 **
127780 ** The author disclaims copyright to this source code.  In place of
127781 ** a legal notice, here is a blessing:
127782 **
127783 **    May you do good and not evil.
127784 **    May you find forgiveness for yourself and forgive others.
127785 **    May you share freely, never taking more than you give.
127786 **
127787 ******************************************************************************
127788 */
127789
127790 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
127791
127792 /* #include <string.h> */
127793 /* #include <assert.h> */
127794
127795 /*
127796 ** Characters that may appear in the second argument to matchinfo().
127797 */
127798 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
127799 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
127800 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
127801 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
127802 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
127803 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
127804 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
127805
127806 /*
127807 ** The default value for the second argument to matchinfo(). 
127808 */
127809 #define FTS3_MATCHINFO_DEFAULT   "pcx"
127810
127811
127812 /*
127813 ** Used as an fts3ExprIterate() context when loading phrase doclists to
127814 ** Fts3Expr.aDoclist[]/nDoclist.
127815 */
127816 typedef struct LoadDoclistCtx LoadDoclistCtx;
127817 struct LoadDoclistCtx {
127818   Fts3Cursor *pCsr;               /* FTS3 Cursor */
127819   int nPhrase;                    /* Number of phrases seen so far */
127820   int nToken;                     /* Number of tokens seen so far */
127821 };
127822
127823 /*
127824 ** The following types are used as part of the implementation of the 
127825 ** fts3BestSnippet() routine.
127826 */
127827 typedef struct SnippetIter SnippetIter;
127828 typedef struct SnippetPhrase SnippetPhrase;
127829 typedef struct SnippetFragment SnippetFragment;
127830
127831 struct SnippetIter {
127832   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
127833   int iCol;                       /* Extract snippet from this column */
127834   int nSnippet;                   /* Requested snippet length (in tokens) */
127835   int nPhrase;                    /* Number of phrases in query */
127836   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
127837   int iCurrent;                   /* First token of current snippet */
127838 };
127839
127840 struct SnippetPhrase {
127841   int nToken;                     /* Number of tokens in phrase */
127842   char *pList;                    /* Pointer to start of phrase position list */
127843   int iHead;                      /* Next value in position list */
127844   char *pHead;                    /* Position list data following iHead */
127845   int iTail;                      /* Next value in trailing position list */
127846   char *pTail;                    /* Position list data following iTail */
127847 };
127848
127849 struct SnippetFragment {
127850   int iCol;                       /* Column snippet is extracted from */
127851   int iPos;                       /* Index of first token in snippet */
127852   u64 covered;                    /* Mask of query phrases covered */
127853   u64 hlmask;                     /* Mask of snippet terms to highlight */
127854 };
127855
127856 /*
127857 ** This type is used as an fts3ExprIterate() context object while 
127858 ** accumulating the data returned by the matchinfo() function.
127859 */
127860 typedef struct MatchInfo MatchInfo;
127861 struct MatchInfo {
127862   Fts3Cursor *pCursor;            /* FTS3 Cursor */
127863   int nCol;                       /* Number of columns in table */
127864   int nPhrase;                    /* Number of matchable phrases in query */
127865   sqlcipher3_int64 nDoc;             /* Number of docs in database */
127866   u32 *aMatchinfo;                /* Pre-allocated buffer */
127867 };
127868
127869
127870
127871 /*
127872 ** The snippet() and offsets() functions both return text values. An instance
127873 ** of the following structure is used to accumulate those values while the
127874 ** functions are running. See fts3StringAppend() for details.
127875 */
127876 typedef struct StrBuffer StrBuffer;
127877 struct StrBuffer {
127878   char *z;                        /* Pointer to buffer containing string */
127879   int n;                          /* Length of z in bytes (excl. nul-term) */
127880   int nAlloc;                     /* Allocated size of buffer z in bytes */
127881 };
127882
127883
127884 /*
127885 ** This function is used to help iterate through a position-list. A position
127886 ** list is a list of unique integers, sorted from smallest to largest. Each
127887 ** element of the list is represented by an FTS3 varint that takes the value
127888 ** of the difference between the current element and the previous one plus
127889 ** two. For example, to store the position-list:
127890 **
127891 **     4 9 113
127892 **
127893 ** the three varints:
127894 **
127895 **     6 7 106
127896 **
127897 ** are encoded.
127898 **
127899 ** When this function is called, *pp points to the start of an element of
127900 ** the list. *piPos contains the value of the previous entry in the list.
127901 ** After it returns, *piPos contains the value of the next element of the
127902 ** list and *pp is advanced to the following varint.
127903 */
127904 static void fts3GetDeltaPosition(char **pp, int *piPos){
127905   int iVal;
127906   *pp += sqlcipher3Fts3GetVarint32(*pp, &iVal);
127907   *piPos += (iVal-2);
127908 }
127909
127910 /*
127911 ** Helper function for fts3ExprIterate() (see below).
127912 */
127913 static int fts3ExprIterate2(
127914   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
127915   int *piPhrase,                  /* Pointer to phrase counter */
127916   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
127917   void *pCtx                      /* Second argument to pass to callback */
127918 ){
127919   int rc;                         /* Return code */
127920   int eType = pExpr->eType;       /* Type of expression node pExpr */
127921
127922   if( eType!=FTSQUERY_PHRASE ){
127923     assert( pExpr->pLeft && pExpr->pRight );
127924     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
127925     if( rc==SQLCIPHER_OK && eType!=FTSQUERY_NOT ){
127926       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
127927     }
127928   }else{
127929     rc = x(pExpr, *piPhrase, pCtx);
127930     (*piPhrase)++;
127931   }
127932   return rc;
127933 }
127934
127935 /*
127936 ** Iterate through all phrase nodes in an FTS3 query, except those that
127937 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
127938 ** For each phrase node found, the supplied callback function is invoked.
127939 **
127940 ** If the callback function returns anything other than SQLCIPHER_OK, 
127941 ** the iteration is abandoned and the error code returned immediately.
127942 ** Otherwise, SQLCIPHER_OK is returned after a callback has been made for
127943 ** all eligible phrase nodes.
127944 */
127945 static int fts3ExprIterate(
127946   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
127947   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
127948   void *pCtx                      /* Second argument to pass to callback */
127949 ){
127950   int iPhrase = 0;                /* Variable used as the phrase counter */
127951   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
127952 }
127953
127954 /*
127955 ** This is an fts3ExprIterate() callback used while loading the doclists
127956 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
127957 ** fts3ExprLoadDoclists().
127958 */
127959 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
127960   int rc = SQLCIPHER_OK;
127961   Fts3Phrase *pPhrase = pExpr->pPhrase;
127962   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
127963
127964   UNUSED_PARAMETER(iPhrase);
127965
127966   p->nPhrase++;
127967   p->nToken += pPhrase->nToken;
127968
127969   return rc;
127970 }
127971
127972 /*
127973 ** Load the doclists for each phrase in the query associated with FTS3 cursor
127974 ** pCsr. 
127975 **
127976 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
127977 ** phrases in the expression (all phrases except those directly or 
127978 ** indirectly descended from the right-hand-side of a NOT operator). If 
127979 ** pnToken is not NULL, then it is set to the number of tokens in all
127980 ** matchable phrases of the expression.
127981 */
127982 static int fts3ExprLoadDoclists(
127983   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
127984   int *pnPhrase,                  /* OUT: Number of phrases in query */
127985   int *pnToken                    /* OUT: Number of tokens in query */
127986 ){
127987   int rc;                         /* Return Code */
127988   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
127989   sCtx.pCsr = pCsr;
127990   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
127991   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
127992   if( pnToken ) *pnToken = sCtx.nToken;
127993   return rc;
127994 }
127995
127996 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
127997   (*(int *)ctx)++;
127998   UNUSED_PARAMETER(pExpr);
127999   UNUSED_PARAMETER(iPhrase);
128000   return SQLCIPHER_OK;
128001 }
128002 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
128003   int nPhrase = 0;
128004   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
128005   return nPhrase;
128006 }
128007
128008 /*
128009 ** Advance the position list iterator specified by the first two 
128010 ** arguments so that it points to the first element with a value greater
128011 ** than or equal to parameter iNext.
128012 */
128013 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
128014   char *pIter = *ppIter;
128015   if( pIter ){
128016     int iIter = *piIter;
128017
128018     while( iIter<iNext ){
128019       if( 0==(*pIter & 0xFE) ){
128020         iIter = -1;
128021         pIter = 0;
128022         break;
128023       }
128024       fts3GetDeltaPosition(&pIter, &iIter);
128025     }
128026
128027     *piIter = iIter;
128028     *ppIter = pIter;
128029   }
128030 }
128031
128032 /*
128033 ** Advance the snippet iterator to the next candidate snippet.
128034 */
128035 static int fts3SnippetNextCandidate(SnippetIter *pIter){
128036   int i;                          /* Loop counter */
128037
128038   if( pIter->iCurrent<0 ){
128039     /* The SnippetIter object has just been initialized. The first snippet
128040     ** candidate always starts at offset 0 (even if this candidate has a
128041     ** score of 0.0).
128042     */
128043     pIter->iCurrent = 0;
128044
128045     /* Advance the 'head' iterator of each phrase to the first offset that
128046     ** is greater than or equal to (iNext+nSnippet).
128047     */
128048     for(i=0; i<pIter->nPhrase; i++){
128049       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128050       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
128051     }
128052   }else{
128053     int iStart;
128054     int iEnd = 0x7FFFFFFF;
128055
128056     for(i=0; i<pIter->nPhrase; i++){
128057       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128058       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
128059         iEnd = pPhrase->iHead;
128060       }
128061     }
128062     if( iEnd==0x7FFFFFFF ){
128063       return 1;
128064     }
128065
128066     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
128067     for(i=0; i<pIter->nPhrase; i++){
128068       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128069       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
128070       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
128071     }
128072   }
128073
128074   return 0;
128075 }
128076
128077 /*
128078 ** Retrieve information about the current candidate snippet of snippet 
128079 ** iterator pIter.
128080 */
128081 static void fts3SnippetDetails(
128082   SnippetIter *pIter,             /* Snippet iterator */
128083   u64 mCovered,                   /* Bitmask of phrases already covered */
128084   int *piToken,                   /* OUT: First token of proposed snippet */
128085   int *piScore,                   /* OUT: "Score" for this snippet */
128086   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
128087   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
128088 ){
128089   int iStart = pIter->iCurrent;   /* First token of snippet */
128090   int iScore = 0;                 /* Score of this snippet */
128091   int i;                          /* Loop counter */
128092   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
128093   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
128094
128095   for(i=0; i<pIter->nPhrase; i++){
128096     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128097     if( pPhrase->pTail ){
128098       char *pCsr = pPhrase->pTail;
128099       int iCsr = pPhrase->iTail;
128100
128101       while( iCsr<(iStart+pIter->nSnippet) ){
128102         int j;
128103         u64 mPhrase = (u64)1 << i;
128104         u64 mPos = (u64)1 << (iCsr - iStart);
128105         assert( iCsr>=iStart );
128106         if( (mCover|mCovered)&mPhrase ){
128107           iScore++;
128108         }else{
128109           iScore += 1000;
128110         }
128111         mCover |= mPhrase;
128112
128113         for(j=0; j<pPhrase->nToken; j++){
128114           mHighlight |= (mPos>>j);
128115         }
128116
128117         if( 0==(*pCsr & 0x0FE) ) break;
128118         fts3GetDeltaPosition(&pCsr, &iCsr);
128119       }
128120     }
128121   }
128122
128123   /* Set the output variables before returning. */
128124   *piToken = iStart;
128125   *piScore = iScore;
128126   *pmCover = mCover;
128127   *pmHighlight = mHighlight;
128128 }
128129
128130 /*
128131 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
128132 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
128133 */
128134 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
128135   SnippetIter *p = (SnippetIter *)ctx;
128136   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
128137   char *pCsr;
128138
128139   pPhrase->nToken = pExpr->pPhrase->nToken;
128140
128141   pCsr = sqlcipher3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
128142   if( pCsr ){
128143     int iFirst = 0;
128144     pPhrase->pList = pCsr;
128145     fts3GetDeltaPosition(&pCsr, &iFirst);
128146     assert( iFirst>=0 );
128147     pPhrase->pHead = pCsr;
128148     pPhrase->pTail = pCsr;
128149     pPhrase->iHead = iFirst;
128150     pPhrase->iTail = iFirst;
128151   }else{
128152     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
128153   }
128154
128155   return SQLCIPHER_OK;
128156 }
128157
128158 /*
128159 ** Select the fragment of text consisting of nFragment contiguous tokens 
128160 ** from column iCol that represent the "best" snippet. The best snippet
128161 ** is the snippet with the highest score, where scores are calculated
128162 ** by adding:
128163 **
128164 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
128165 **
128166 **   (b) +1000 points for the first occurence of each matchable phrase in 
128167 **       the snippet for which the corresponding mCovered bit is not set.
128168 **
128169 ** The selected snippet parameters are stored in structure *pFragment before
128170 ** returning. The score of the selected snippet is stored in *piScore
128171 ** before returning.
128172 */
128173 static int fts3BestSnippet(
128174   int nSnippet,                   /* Desired snippet length */
128175   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
128176   int iCol,                       /* Index of column to create snippet from */
128177   u64 mCovered,                   /* Mask of phrases already covered */
128178   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
128179   SnippetFragment *pFragment,     /* OUT: Best snippet found */
128180   int *piScore                    /* OUT: Score of snippet pFragment */
128181 ){
128182   int rc;                         /* Return Code */
128183   int nList;                      /* Number of phrases in expression */
128184   SnippetIter sIter;              /* Iterates through snippet candidates */
128185   int nByte;                      /* Number of bytes of space to allocate */
128186   int iBestScore = -1;            /* Best snippet score found so far */
128187   int i;                          /* Loop counter */
128188
128189   memset(&sIter, 0, sizeof(sIter));
128190
128191   /* Iterate through the phrases in the expression to count them. The same
128192   ** callback makes sure the doclists are loaded for each phrase.
128193   */
128194   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
128195   if( rc!=SQLCIPHER_OK ){
128196     return rc;
128197   }
128198
128199   /* Now that it is known how many phrases there are, allocate and zero
128200   ** the required space using malloc().
128201   */
128202   nByte = sizeof(SnippetPhrase) * nList;
128203   sIter.aPhrase = (SnippetPhrase *)sqlcipher3_malloc(nByte);
128204   if( !sIter.aPhrase ){
128205     return SQLCIPHER_NOMEM;
128206   }
128207   memset(sIter.aPhrase, 0, nByte);
128208
128209   /* Initialize the contents of the SnippetIter object. Then iterate through
128210   ** the set of phrases in the expression to populate the aPhrase[] array.
128211   */
128212   sIter.pCsr = pCsr;
128213   sIter.iCol = iCol;
128214   sIter.nSnippet = nSnippet;
128215   sIter.nPhrase = nList;
128216   sIter.iCurrent = -1;
128217   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
128218
128219   /* Set the *pmSeen output variable. */
128220   for(i=0; i<nList; i++){
128221     if( sIter.aPhrase[i].pHead ){
128222       *pmSeen |= (u64)1 << i;
128223     }
128224   }
128225
128226   /* Loop through all candidate snippets. Store the best snippet in 
128227   ** *pFragment. Store its associated 'score' in iBestScore.
128228   */
128229   pFragment->iCol = iCol;
128230   while( !fts3SnippetNextCandidate(&sIter) ){
128231     int iPos;
128232     int iScore;
128233     u64 mCover;
128234     u64 mHighlight;
128235     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
128236     assert( iScore>=0 );
128237     if( iScore>iBestScore ){
128238       pFragment->iPos = iPos;
128239       pFragment->hlmask = mHighlight;
128240       pFragment->covered = mCover;
128241       iBestScore = iScore;
128242     }
128243   }
128244
128245   sqlcipher3_free(sIter.aPhrase);
128246   *piScore = iBestScore;
128247   return SQLCIPHER_OK;
128248 }
128249
128250
128251 /*
128252 ** Append a string to the string-buffer passed as the first argument.
128253 **
128254 ** If nAppend is negative, then the length of the string zAppend is
128255 ** determined using strlen().
128256 */
128257 static int fts3StringAppend(
128258   StrBuffer *pStr,                /* Buffer to append to */
128259   const char *zAppend,            /* Pointer to data to append to buffer */
128260   int nAppend                     /* Size of zAppend in bytes (or -1) */
128261 ){
128262   if( nAppend<0 ){
128263     nAppend = (int)strlen(zAppend);
128264   }
128265
128266   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
128267   ** to grow the buffer until so that it is big enough to accomadate the
128268   ** appended data.
128269   */
128270   if( pStr->n+nAppend+1>=pStr->nAlloc ){
128271     int nAlloc = pStr->nAlloc+nAppend+100;
128272     char *zNew = sqlcipher3_realloc(pStr->z, nAlloc);
128273     if( !zNew ){
128274       return SQLCIPHER_NOMEM;
128275     }
128276     pStr->z = zNew;
128277     pStr->nAlloc = nAlloc;
128278   }
128279
128280   /* Append the data to the string buffer. */
128281   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
128282   pStr->n += nAppend;
128283   pStr->z[pStr->n] = '\0';
128284
128285   return SQLCIPHER_OK;
128286 }
128287
128288 /*
128289 ** The fts3BestSnippet() function often selects snippets that end with a
128290 ** query term. That is, the final term of the snippet is always a term
128291 ** that requires highlighting. For example, if 'X' is a highlighted term
128292 ** and '.' is a non-highlighted term, BestSnippet() may select:
128293 **
128294 **     ........X.....X
128295 **
128296 ** This function "shifts" the beginning of the snippet forward in the 
128297 ** document so that there are approximately the same number of 
128298 ** non-highlighted terms to the right of the final highlighted term as there
128299 ** are to the left of the first highlighted term. For example, to this:
128300 **
128301 **     ....X.....X....
128302 **
128303 ** This is done as part of extracting the snippet text, not when selecting
128304 ** the snippet. Snippet selection is done based on doclists only, so there
128305 ** is no way for fts3BestSnippet() to know whether or not the document 
128306 ** actually contains terms that follow the final highlighted term. 
128307 */
128308 static int fts3SnippetShift(
128309   Fts3Table *pTab,                /* FTS3 table snippet comes from */
128310   int nSnippet,                   /* Number of tokens desired for snippet */
128311   const char *zDoc,               /* Document text to extract snippet from */
128312   int nDoc,                       /* Size of buffer zDoc in bytes */
128313   int *piPos,                     /* IN/OUT: First token of snippet */
128314   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
128315 ){
128316   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
128317
128318   if( hlmask ){
128319     int nLeft;                    /* Tokens to the left of first highlight */
128320     int nRight;                   /* Tokens to the right of last highlight */
128321     int nDesired;                 /* Ideal number of tokens to shift forward */
128322
128323     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
128324     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
128325     nDesired = (nLeft-nRight)/2;
128326
128327     /* Ideally, the start of the snippet should be pushed forward in the
128328     ** document nDesired tokens. This block checks if there are actually
128329     ** nDesired tokens to the right of the snippet. If so, *piPos and
128330     ** *pHlMask are updated to shift the snippet nDesired tokens to the
128331     ** right. Otherwise, the snippet is shifted by the number of tokens
128332     ** available.
128333     */
128334     if( nDesired>0 ){
128335       int nShift;                 /* Number of tokens to shift snippet by */
128336       int iCurrent = 0;           /* Token counter */
128337       int rc;                     /* Return Code */
128338       sqlcipher3_tokenizer_module *pMod;
128339       sqlcipher3_tokenizer_cursor *pC;
128340       pMod = (sqlcipher3_tokenizer_module *)pTab->pTokenizer->pModule;
128341
128342       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
128343       ** or more tokens in zDoc/nDoc.
128344       */
128345       rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
128346       if( rc!=SQLCIPHER_OK ){
128347         return rc;
128348       }
128349       pC->pTokenizer = pTab->pTokenizer;
128350       while( rc==SQLCIPHER_OK && iCurrent<(nSnippet+nDesired) ){
128351         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
128352         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
128353       }
128354       pMod->xClose(pC);
128355       if( rc!=SQLCIPHER_OK && rc!=SQLCIPHER_DONE ){ return rc; }
128356
128357       nShift = (rc==SQLCIPHER_DONE)+iCurrent-nSnippet;
128358       assert( nShift<=nDesired );
128359       if( nShift>0 ){
128360         *piPos += nShift;
128361         *pHlmask = hlmask >> nShift;
128362       }
128363     }
128364   }
128365   return SQLCIPHER_OK;
128366 }
128367
128368 /*
128369 ** Extract the snippet text for fragment pFragment from cursor pCsr and
128370 ** append it to string buffer pOut.
128371 */
128372 static int fts3SnippetText(
128373   Fts3Cursor *pCsr,               /* FTS3 Cursor */
128374   SnippetFragment *pFragment,     /* Snippet to extract */
128375   int iFragment,                  /* Fragment number */
128376   int isLast,                     /* True for final fragment in snippet */
128377   int nSnippet,                   /* Number of tokens in extracted snippet */
128378   const char *zOpen,              /* String inserted before highlighted term */
128379   const char *zClose,             /* String inserted after highlighted term */
128380   const char *zEllipsis,          /* String inserted between snippets */
128381   StrBuffer *pOut                 /* Write output here */
128382 ){
128383   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128384   int rc;                         /* Return code */
128385   const char *zDoc;               /* Document text to extract snippet from */
128386   int nDoc;                       /* Size of zDoc in bytes */
128387   int iCurrent = 0;               /* Current token number of document */
128388   int iEnd = 0;                   /* Byte offset of end of current token */
128389   int isShiftDone = 0;            /* True after snippet is shifted */
128390   int iPos = pFragment->iPos;     /* First token of snippet */
128391   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
128392   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
128393   sqlcipher3_tokenizer_module *pMod; /* Tokenizer module methods object */
128394   sqlcipher3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
128395   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
128396   int DUMMY1;                     /* Dummy argument used with tokenizer */
128397   
128398   zDoc = (const char *)sqlcipher3_column_text(pCsr->pStmt, iCol);
128399   if( zDoc==0 ){
128400     if( sqlcipher3_column_type(pCsr->pStmt, iCol)!=SQLCIPHER_NULL ){
128401       return SQLCIPHER_NOMEM;
128402     }
128403     return SQLCIPHER_OK;
128404   }
128405   nDoc = sqlcipher3_column_bytes(pCsr->pStmt, iCol);
128406
128407   /* Open a token cursor on the document. */
128408   pMod = (sqlcipher3_tokenizer_module *)pTab->pTokenizer->pModule;
128409   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
128410   if( rc!=SQLCIPHER_OK ){
128411     return rc;
128412   }
128413   pC->pTokenizer = pTab->pTokenizer;
128414
128415   while( rc==SQLCIPHER_OK ){
128416     int iBegin;                   /* Offset in zDoc of start of token */
128417     int iFin;                     /* Offset in zDoc of end of token */
128418     int isHighlight;              /* True for highlighted terms */
128419
128420     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
128421     if( rc!=SQLCIPHER_OK ){
128422       if( rc==SQLCIPHER_DONE ){
128423         /* Special case - the last token of the snippet is also the last token
128424         ** of the column. Append any punctuation that occurred between the end
128425         ** of the previous token and the end of the document to the output. 
128426         ** Then break out of the loop. */
128427         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
128428       }
128429       break;
128430     }
128431     if( iCurrent<iPos ){ continue; }
128432
128433     if( !isShiftDone ){
128434       int n = nDoc - iBegin;
128435       rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
128436       isShiftDone = 1;
128437
128438       /* Now that the shift has been done, check if the initial "..." are
128439       ** required. They are required if (a) this is not the first fragment,
128440       ** or (b) this fragment does not begin at position 0 of its column. 
128441       */
128442       if( rc==SQLCIPHER_OK && (iPos>0 || iFragment>0) ){
128443         rc = fts3StringAppend(pOut, zEllipsis, -1);
128444       }
128445       if( rc!=SQLCIPHER_OK || iCurrent<iPos ) continue;
128446     }
128447
128448     if( iCurrent>=(iPos+nSnippet) ){
128449       if( isLast ){
128450         rc = fts3StringAppend(pOut, zEllipsis, -1);
128451       }
128452       break;
128453     }
128454
128455     /* Set isHighlight to true if this term should be highlighted. */
128456     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
128457
128458     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
128459     if( rc==SQLCIPHER_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
128460     if( rc==SQLCIPHER_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
128461     if( rc==SQLCIPHER_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
128462
128463     iEnd = iFin;
128464   }
128465
128466   pMod->xClose(pC);
128467   return rc;
128468 }
128469
128470
128471 /*
128472 ** This function is used to count the entries in a column-list (a 
128473 ** delta-encoded list of term offsets within a single column of a single 
128474 ** row). When this function is called, *ppCollist should point to the
128475 ** beginning of the first varint in the column-list (the varint that
128476 ** contains the position of the first matching term in the column data).
128477 ** Before returning, *ppCollist is set to point to the first byte after
128478 ** the last varint in the column-list (either the 0x00 signifying the end
128479 ** of the position-list, or the 0x01 that precedes the column number of
128480 ** the next column in the position-list).
128481 **
128482 ** The number of elements in the column-list is returned.
128483 */
128484 static int fts3ColumnlistCount(char **ppCollist){
128485   char *pEnd = *ppCollist;
128486   char c = 0;
128487   int nEntry = 0;
128488
128489   /* A column-list is terminated by either a 0x01 or 0x00. */
128490   while( 0xFE & (*pEnd | c) ){
128491     c = *pEnd++ & 0x80;
128492     if( !c ) nEntry++;
128493   }
128494
128495   *ppCollist = pEnd;
128496   return nEntry;
128497 }
128498
128499 /*
128500 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
128501 ** for a single query. 
128502 **
128503 ** fts3ExprIterate() callback to load the 'global' elements of a
128504 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
128505 ** of the matchinfo array that are constant for all rows returned by the 
128506 ** current query.
128507 **
128508 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
128509 ** function populates Matchinfo.aMatchinfo[] as follows:
128510 **
128511 **   for(iCol=0; iCol<nCol; iCol++){
128512 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
128513 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
128514 **   }
128515 **
128516 ** where X is the number of matches for phrase iPhrase is column iCol of all
128517 ** rows of the table. Y is the number of rows for which column iCol contains
128518 ** at least one instance of phrase iPhrase.
128519 **
128520 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
128521 ** Y values are set to nDoc, where nDoc is the number of documents in the 
128522 ** file system. This is done because the full-text index doclist is required
128523 ** to calculate these values properly, and the full-text index doclist is
128524 ** not available for deferred tokens.
128525 */
128526 static int fts3ExprGlobalHitsCb(
128527   Fts3Expr *pExpr,                /* Phrase expression node */
128528   int iPhrase,                    /* Phrase number (numbered from zero) */
128529   void *pCtx                      /* Pointer to MatchInfo structure */
128530 ){
128531   MatchInfo *p = (MatchInfo *)pCtx;
128532   return sqlcipher3Fts3EvalPhraseStats(
128533       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
128534   );
128535 }
128536
128537 /*
128538 ** fts3ExprIterate() callback used to collect the "local" part of the
128539 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
128540 ** array that are different for each row returned by the query.
128541 */
128542 static int fts3ExprLocalHitsCb(
128543   Fts3Expr *pExpr,                /* Phrase expression node */
128544   int iPhrase,                    /* Phrase number */
128545   void *pCtx                      /* Pointer to MatchInfo structure */
128546 ){
128547   MatchInfo *p = (MatchInfo *)pCtx;
128548   int iStart = iPhrase * p->nCol * 3;
128549   int i;
128550
128551   for(i=0; i<p->nCol; i++){
128552     char *pCsr;
128553     pCsr = sqlcipher3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i);
128554     if( pCsr ){
128555       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
128556     }else{
128557       p->aMatchinfo[iStart+i*3] = 0;
128558     }
128559   }
128560
128561   return SQLCIPHER_OK;
128562 }
128563
128564 static int fts3MatchinfoCheck(
128565   Fts3Table *pTab, 
128566   char cArg,
128567   char **pzErr
128568 ){
128569   if( (cArg==FTS3_MATCHINFO_NPHRASE)
128570    || (cArg==FTS3_MATCHINFO_NCOL)
128571    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
128572    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
128573    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
128574    || (cArg==FTS3_MATCHINFO_LCS)
128575    || (cArg==FTS3_MATCHINFO_HITS)
128576   ){
128577     return SQLCIPHER_OK;
128578   }
128579   *pzErr = sqlcipher3_mprintf("unrecognized matchinfo request: %c", cArg);
128580   return SQLCIPHER_ERROR;
128581 }
128582
128583 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
128584   int nVal;                       /* Number of integers output by cArg */
128585
128586   switch( cArg ){
128587     case FTS3_MATCHINFO_NDOC:
128588     case FTS3_MATCHINFO_NPHRASE: 
128589     case FTS3_MATCHINFO_NCOL: 
128590       nVal = 1;
128591       break;
128592
128593     case FTS3_MATCHINFO_AVGLENGTH:
128594     case FTS3_MATCHINFO_LENGTH:
128595     case FTS3_MATCHINFO_LCS:
128596       nVal = pInfo->nCol;
128597       break;
128598
128599     default:
128600       assert( cArg==FTS3_MATCHINFO_HITS );
128601       nVal = pInfo->nCol * pInfo->nPhrase * 3;
128602       break;
128603   }
128604
128605   return nVal;
128606 }
128607
128608 static int fts3MatchinfoSelectDoctotal(
128609   Fts3Table *pTab,
128610   sqlcipher3_stmt **ppStmt,
128611   sqlcipher3_int64 *pnDoc,
128612   const char **paLen
128613 ){
128614   sqlcipher3_stmt *pStmt;
128615   const char *a;
128616   sqlcipher3_int64 nDoc;
128617
128618   if( !*ppStmt ){
128619     int rc = sqlcipher3Fts3SelectDoctotal(pTab, ppStmt);
128620     if( rc!=SQLCIPHER_OK ) return rc;
128621   }
128622   pStmt = *ppStmt;
128623   assert( sqlcipher3_data_count(pStmt)==1 );
128624
128625   a = sqlcipher3_column_blob(pStmt, 0);
128626   a += sqlcipher3Fts3GetVarint(a, &nDoc);
128627   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
128628   *pnDoc = (u32)nDoc;
128629
128630   if( paLen ) *paLen = a;
128631   return SQLCIPHER_OK;
128632 }
128633
128634 /*
128635 ** An instance of the following structure is used to store state while 
128636 ** iterating through a multi-column position-list corresponding to the
128637 ** hits for a single phrase on a single row in order to calculate the
128638 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
128639 */
128640 typedef struct LcsIterator LcsIterator;
128641 struct LcsIterator {
128642   Fts3Expr *pExpr;                /* Pointer to phrase expression */
128643   int iPosOffset;                 /* Tokens count up to end of this phrase */
128644   char *pRead;                    /* Cursor used to iterate through aDoclist */
128645   int iPos;                       /* Current position */
128646 };
128647
128648 /* 
128649 ** If LcsIterator.iCol is set to the following value, the iterator has
128650 ** finished iterating through all offsets for all columns.
128651 */
128652 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
128653
128654 static int fts3MatchinfoLcsCb(
128655   Fts3Expr *pExpr,                /* Phrase expression node */
128656   int iPhrase,                    /* Phrase number (numbered from zero) */
128657   void *pCtx                      /* Pointer to MatchInfo structure */
128658 ){
128659   LcsIterator *aIter = (LcsIterator *)pCtx;
128660   aIter[iPhrase].pExpr = pExpr;
128661   return SQLCIPHER_OK;
128662 }
128663
128664 /*
128665 ** Advance the iterator passed as an argument to the next position. Return
128666 ** 1 if the iterator is at EOF or if it now points to the start of the
128667 ** position list for the next column.
128668 */
128669 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
128670   char *pRead = pIter->pRead;
128671   sqlcipher3_int64 iRead;
128672   int rc = 0;
128673
128674   pRead += sqlcipher3Fts3GetVarint(pRead, &iRead);
128675   if( iRead==0 || iRead==1 ){
128676     pRead = 0;
128677     rc = 1;
128678   }else{
128679     pIter->iPos += (int)(iRead-2);
128680   }
128681
128682   pIter->pRead = pRead;
128683   return rc;
128684 }
128685   
128686 /*
128687 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
128688 **
128689 ** If the call is successful, the longest-common-substring lengths for each
128690 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
128691 ** array before returning. SQLCIPHER_OK is returned in this case.
128692 **
128693 ** Otherwise, if an error occurs, an SQLite error code is returned and the
128694 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
128695 ** undefined.
128696 */
128697 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
128698   LcsIterator *aIter;
128699   int i;
128700   int iCol;
128701   int nToken = 0;
128702
128703   /* Allocate and populate the array of LcsIterator objects. The array
128704   ** contains one element for each matchable phrase in the query.
128705   **/
128706   aIter = sqlcipher3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
128707   if( !aIter ) return SQLCIPHER_NOMEM;
128708   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
128709   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
128710
128711   for(i=0; i<pInfo->nPhrase; i++){
128712     LcsIterator *pIter = &aIter[i];
128713     nToken -= pIter->pExpr->pPhrase->nToken;
128714     pIter->iPosOffset = nToken;
128715   }
128716
128717   for(iCol=0; iCol<pInfo->nCol; iCol++){
128718     int nLcs = 0;                 /* LCS value for this column */
128719     int nLive = 0;                /* Number of iterators in aIter not at EOF */
128720
128721     for(i=0; i<pInfo->nPhrase; i++){
128722       LcsIterator *pIt = &aIter[i];
128723       pIt->pRead = sqlcipher3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol);
128724       if( pIt->pRead ){
128725         pIt->iPos = pIt->iPosOffset;
128726         fts3LcsIteratorAdvance(&aIter[i]);
128727         nLive++;
128728       }
128729     }
128730
128731     while( nLive>0 ){
128732       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
128733       int nThisLcs = 0;           /* LCS for the current iterator positions */
128734
128735       for(i=0; i<pInfo->nPhrase; i++){
128736         LcsIterator *pIter = &aIter[i];
128737         if( pIter->pRead==0 ){
128738           /* This iterator is already at EOF for this column. */
128739           nThisLcs = 0;
128740         }else{
128741           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
128742             pAdv = pIter;
128743           }
128744           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
128745             nThisLcs++;
128746           }else{
128747             nThisLcs = 1;
128748           }
128749           if( nThisLcs>nLcs ) nLcs = nThisLcs;
128750         }
128751       }
128752       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
128753     }
128754
128755     pInfo->aMatchinfo[iCol] = nLcs;
128756   }
128757
128758   sqlcipher3_free(aIter);
128759   return SQLCIPHER_OK;
128760 }
128761
128762 /*
128763 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
128764 ** be returned by the matchinfo() function. Argument zArg contains the 
128765 ** format string passed as the second argument to matchinfo (or the
128766 ** default value "pcx" if no second argument was specified). The format
128767 ** string has already been validated and the pInfo->aMatchinfo[] array
128768 ** is guaranteed to be large enough for the output.
128769 **
128770 ** If bGlobal is true, then populate all fields of the matchinfo() output.
128771 ** If it is false, then assume that those fields that do not change between
128772 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
128773 ** have already been populated.
128774 **
128775 ** Return SQLCIPHER_OK if successful, or an SQLite error code if an error 
128776 ** occurs. If a value other than SQLCIPHER_OK is returned, the state the
128777 ** pInfo->aMatchinfo[] buffer is left in is undefined.
128778 */
128779 static int fts3MatchinfoValues(
128780   Fts3Cursor *pCsr,               /* FTS3 cursor object */
128781   int bGlobal,                    /* True to grab the global stats */
128782   MatchInfo *pInfo,               /* Matchinfo context object */
128783   const char *zArg                /* Matchinfo format string */
128784 ){
128785   int rc = SQLCIPHER_OK;
128786   int i;
128787   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128788   sqlcipher3_stmt *pSelect = 0;
128789
128790   for(i=0; rc==SQLCIPHER_OK && zArg[i]; i++){
128791
128792     switch( zArg[i] ){
128793       case FTS3_MATCHINFO_NPHRASE:
128794         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
128795         break;
128796
128797       case FTS3_MATCHINFO_NCOL:
128798         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
128799         break;
128800         
128801       case FTS3_MATCHINFO_NDOC:
128802         if( bGlobal ){
128803           sqlcipher3_int64 nDoc = 0;
128804           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
128805           pInfo->aMatchinfo[0] = (u32)nDoc;
128806         }
128807         break;
128808
128809       case FTS3_MATCHINFO_AVGLENGTH: 
128810         if( bGlobal ){
128811           sqlcipher3_int64 nDoc;     /* Number of rows in table */
128812           const char *a;          /* Aggregate column length array */
128813
128814           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
128815           if( rc==SQLCIPHER_OK ){
128816             int iCol;
128817             for(iCol=0; iCol<pInfo->nCol; iCol++){
128818               u32 iVal;
128819               sqlcipher3_int64 nToken;
128820               a += sqlcipher3Fts3GetVarint(a, &nToken);
128821               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
128822               pInfo->aMatchinfo[iCol] = iVal;
128823             }
128824           }
128825         }
128826         break;
128827
128828       case FTS3_MATCHINFO_LENGTH: {
128829         sqlcipher3_stmt *pSelectDocsize = 0;
128830         rc = sqlcipher3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
128831         if( rc==SQLCIPHER_OK ){
128832           int iCol;
128833           const char *a = sqlcipher3_column_blob(pSelectDocsize, 0);
128834           for(iCol=0; iCol<pInfo->nCol; iCol++){
128835             sqlcipher3_int64 nToken;
128836             a += sqlcipher3Fts3GetVarint(a, &nToken);
128837             pInfo->aMatchinfo[iCol] = (u32)nToken;
128838           }
128839         }
128840         sqlcipher3_reset(pSelectDocsize);
128841         break;
128842       }
128843
128844       case FTS3_MATCHINFO_LCS:
128845         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
128846         if( rc==SQLCIPHER_OK ){
128847           rc = fts3MatchinfoLcs(pCsr, pInfo);
128848         }
128849         break;
128850
128851       default: {
128852         Fts3Expr *pExpr;
128853         assert( zArg[i]==FTS3_MATCHINFO_HITS );
128854         pExpr = pCsr->pExpr;
128855         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
128856         if( rc!=SQLCIPHER_OK ) break;
128857         if( bGlobal ){
128858           if( pCsr->pDeferred ){
128859             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
128860             if( rc!=SQLCIPHER_OK ) break;
128861           }
128862           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
128863           if( rc!=SQLCIPHER_OK ) break;
128864         }
128865         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
128866         break;
128867       }
128868     }
128869
128870     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
128871   }
128872
128873   sqlcipher3_reset(pSelect);
128874   return rc;
128875 }
128876
128877
128878 /*
128879 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
128880 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
128881 */
128882 static int fts3GetMatchinfo(
128883   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
128884   const char *zArg                /* Second argument to matchinfo() function */
128885 ){
128886   MatchInfo sInfo;
128887   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128888   int rc = SQLCIPHER_OK;
128889   int bGlobal = 0;                /* Collect 'global' stats as well as local */
128890
128891   memset(&sInfo, 0, sizeof(MatchInfo));
128892   sInfo.pCursor = pCsr;
128893   sInfo.nCol = pTab->nColumn;
128894
128895   /* If there is cached matchinfo() data, but the format string for the 
128896   ** cache does not match the format string for this request, discard 
128897   ** the cached data. */
128898   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
128899     assert( pCsr->aMatchinfo );
128900     sqlcipher3_free(pCsr->aMatchinfo);
128901     pCsr->zMatchinfo = 0;
128902     pCsr->aMatchinfo = 0;
128903   }
128904
128905   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
128906   ** matchinfo function has been called for this query. In this case 
128907   ** allocate the array used to accumulate the matchinfo data and
128908   ** initialize those elements that are constant for every row.
128909   */
128910   if( pCsr->aMatchinfo==0 ){
128911     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
128912     int nArg;                     /* Bytes in zArg */
128913     int i;                        /* Used to iterate through zArg */
128914
128915     /* Determine the number of phrases in the query */
128916     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
128917     sInfo.nPhrase = pCsr->nPhrase;
128918
128919     /* Determine the number of integers in the buffer returned by this call. */
128920     for(i=0; zArg[i]; i++){
128921       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
128922     }
128923
128924     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
128925     nArg = (int)strlen(zArg);
128926     pCsr->aMatchinfo = (u32 *)sqlcipher3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
128927     if( !pCsr->aMatchinfo ) return SQLCIPHER_NOMEM;
128928
128929     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
128930     pCsr->nMatchinfo = nMatchinfo;
128931     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
128932     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
128933     pCsr->isMatchinfoNeeded = 1;
128934     bGlobal = 1;
128935   }
128936
128937   sInfo.aMatchinfo = pCsr->aMatchinfo;
128938   sInfo.nPhrase = pCsr->nPhrase;
128939   if( pCsr->isMatchinfoNeeded ){
128940     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
128941     pCsr->isMatchinfoNeeded = 0;
128942   }
128943
128944   return rc;
128945 }
128946
128947 /*
128948 ** Implementation of snippet() function.
128949 */
128950 SQLCIPHER_PRIVATE void sqlcipher3Fts3Snippet(
128951   sqlcipher3_context *pCtx,          /* SQLite function call context */
128952   Fts3Cursor *pCsr,               /* Cursor object */
128953   const char *zStart,             /* Snippet start text - "<b>" */
128954   const char *zEnd,               /* Snippet end text - "</b>" */
128955   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
128956   int iCol,                       /* Extract snippet from this column */
128957   int nToken                      /* Approximate number of tokens in snippet */
128958 ){
128959   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128960   int rc = SQLCIPHER_OK;
128961   int i;
128962   StrBuffer res = {0, 0, 0};
128963
128964   /* The returned text includes up to four fragments of text extracted from
128965   ** the data in the current row. The first iteration of the for(...) loop
128966   ** below attempts to locate a single fragment of text nToken tokens in 
128967   ** size that contains at least one instance of all phrases in the query
128968   ** expression that appear in the current row. If such a fragment of text
128969   ** cannot be found, the second iteration of the loop attempts to locate
128970   ** a pair of fragments, and so on.
128971   */
128972   int nSnippet = 0;               /* Number of fragments in this snippet */
128973   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
128974   int nFToken = -1;               /* Number of tokens in each fragment */
128975
128976   if( !pCsr->pExpr ){
128977     sqlcipher3_result_text(pCtx, "", 0, SQLCIPHER_STATIC);
128978     return;
128979   }
128980
128981   for(nSnippet=1; 1; nSnippet++){
128982
128983     int iSnip;                    /* Loop counter 0..nSnippet-1 */
128984     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
128985     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
128986
128987     if( nToken>=0 ){
128988       nFToken = (nToken+nSnippet-1) / nSnippet;
128989     }else{
128990       nFToken = -1 * nToken;
128991     }
128992
128993     for(iSnip=0; iSnip<nSnippet; iSnip++){
128994       int iBestScore = -1;        /* Best score of columns checked so far */
128995       int iRead;                  /* Used to iterate through columns */
128996       SnippetFragment *pFragment = &aSnippet[iSnip];
128997
128998       memset(pFragment, 0, sizeof(*pFragment));
128999
129000       /* Loop through all columns of the table being considered for snippets.
129001       ** If the iCol argument to this function was negative, this means all
129002       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
129003       */
129004       for(iRead=0; iRead<pTab->nColumn; iRead++){
129005         SnippetFragment sF = {0, 0, 0, 0};
129006         int iS;
129007         if( iCol>=0 && iRead!=iCol ) continue;
129008
129009         /* Find the best snippet of nFToken tokens in column iRead. */
129010         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
129011         if( rc!=SQLCIPHER_OK ){
129012           goto snippet_out;
129013         }
129014         if( iS>iBestScore ){
129015           *pFragment = sF;
129016           iBestScore = iS;
129017         }
129018       }
129019
129020       mCovered |= pFragment->covered;
129021     }
129022
129023     /* If all query phrases seen by fts3BestSnippet() are present in at least
129024     ** one of the nSnippet snippet fragments, break out of the loop.
129025     */
129026     assert( (mCovered&mSeen)==mCovered );
129027     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
129028   }
129029
129030   assert( nFToken>0 );
129031
129032   for(i=0; i<nSnippet && rc==SQLCIPHER_OK; i++){
129033     rc = fts3SnippetText(pCsr, &aSnippet[i], 
129034         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
129035     );
129036   }
129037
129038  snippet_out:
129039   sqlcipher3Fts3SegmentsClose(pTab);
129040   if( rc!=SQLCIPHER_OK ){
129041     sqlcipher3_result_error_code(pCtx, rc);
129042     sqlcipher3_free(res.z);
129043   }else{
129044     sqlcipher3_result_text(pCtx, res.z, -1, sqlcipher3_free);
129045   }
129046 }
129047
129048
129049 typedef struct TermOffset TermOffset;
129050 typedef struct TermOffsetCtx TermOffsetCtx;
129051
129052 struct TermOffset {
129053   char *pList;                    /* Position-list */
129054   int iPos;                       /* Position just read from pList */
129055   int iOff;                       /* Offset of this term from read positions */
129056 };
129057
129058 struct TermOffsetCtx {
129059   Fts3Cursor *pCsr;
129060   int iCol;                       /* Column of table to populate aTerm for */
129061   int iTerm;
129062   sqlcipher3_int64 iDocid;
129063   TermOffset *aTerm;
129064 };
129065
129066 /*
129067 ** This function is an fts3ExprIterate() callback used by sqlcipher3Fts3Offsets().
129068 */
129069 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
129070   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
129071   int nTerm;                      /* Number of tokens in phrase */
129072   int iTerm;                      /* For looping through nTerm phrase terms */
129073   char *pList;                    /* Pointer to position list for phrase */
129074   int iPos = 0;                   /* First position in position-list */
129075
129076   UNUSED_PARAMETER(iPhrase);
129077   pList = sqlcipher3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
129078   nTerm = pExpr->pPhrase->nToken;
129079   if( pList ){
129080     fts3GetDeltaPosition(&pList, &iPos);
129081     assert( iPos>=0 );
129082   }
129083
129084   for(iTerm=0; iTerm<nTerm; iTerm++){
129085     TermOffset *pT = &p->aTerm[p->iTerm++];
129086     pT->iOff = nTerm-iTerm-1;
129087     pT->pList = pList;
129088     pT->iPos = iPos;
129089   }
129090
129091   return SQLCIPHER_OK;
129092 }
129093
129094 /*
129095 ** Implementation of offsets() function.
129096 */
129097 SQLCIPHER_PRIVATE void sqlcipher3Fts3Offsets(
129098   sqlcipher3_context *pCtx,          /* SQLite function call context */
129099   Fts3Cursor *pCsr                /* Cursor object */
129100 ){
129101   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129102   sqlcipher3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
129103   const char *ZDUMMY;             /* Dummy argument used with xNext() */
129104   int NDUMMY;                     /* Dummy argument used with xNext() */
129105   int rc;                         /* Return Code */
129106   int nToken;                     /* Number of tokens in query */
129107   int iCol;                       /* Column currently being processed */
129108   StrBuffer res = {0, 0, 0};      /* Result string */
129109   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
129110
129111   if( !pCsr->pExpr ){
129112     sqlcipher3_result_text(pCtx, "", 0, SQLCIPHER_STATIC);
129113     return;
129114   }
129115
129116   memset(&sCtx, 0, sizeof(sCtx));
129117   assert( pCsr->isRequireSeek==0 );
129118
129119   /* Count the number of terms in the query */
129120   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
129121   if( rc!=SQLCIPHER_OK ) goto offsets_out;
129122
129123   /* Allocate the array of TermOffset iterators. */
129124   sCtx.aTerm = (TermOffset *)sqlcipher3_malloc(sizeof(TermOffset)*nToken);
129125   if( 0==sCtx.aTerm ){
129126     rc = SQLCIPHER_NOMEM;
129127     goto offsets_out;
129128   }
129129   sCtx.iDocid = pCsr->iPrevId;
129130   sCtx.pCsr = pCsr;
129131
129132   /* Loop through the table columns, appending offset information to 
129133   ** string-buffer res for each column.
129134   */
129135   for(iCol=0; iCol<pTab->nColumn; iCol++){
129136     sqlcipher3_tokenizer_cursor *pC; /* Tokenizer cursor */
129137     int iStart;
129138     int iEnd;
129139     int iCurrent;
129140     const char *zDoc;
129141     int nDoc;
129142
129143     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
129144     ** no way that this operation can fail, so the return code from
129145     ** fts3ExprIterate() can be discarded.
129146     */
129147     sCtx.iCol = iCol;
129148     sCtx.iTerm = 0;
129149     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
129150
129151     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
129152     ** in column iCol, jump immediately to the next iteration of the loop.
129153     ** If an OOM occurs while retrieving the data (this can happen if SQLite
129154     ** needs to transform the data from utf-16 to utf-8), return SQLCIPHER_NOMEM 
129155     ** to the caller. 
129156     */
129157     zDoc = (const char *)sqlcipher3_column_text(pCsr->pStmt, iCol+1);
129158     nDoc = sqlcipher3_column_bytes(pCsr->pStmt, iCol+1);
129159     if( zDoc==0 ){
129160       if( sqlcipher3_column_type(pCsr->pStmt, iCol+1)==SQLCIPHER_NULL ){
129161         continue;
129162       }
129163       rc = SQLCIPHER_NOMEM;
129164       goto offsets_out;
129165     }
129166
129167     /* Initialize a tokenizer iterator to iterate through column iCol. */
129168     rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
129169     if( rc!=SQLCIPHER_OK ) goto offsets_out;
129170     pC->pTokenizer = pTab->pTokenizer;
129171
129172     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
129173     while( rc==SQLCIPHER_OK ){
129174       int i;                      /* Used to loop through terms */
129175       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
129176       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
129177
129178       for(i=0; i<nToken; i++){
129179         TermOffset *pT = &sCtx.aTerm[i];
129180         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
129181           iMinPos = pT->iPos-pT->iOff;
129182           pTerm = pT;
129183         }
129184       }
129185
129186       if( !pTerm ){
129187         /* All offsets for this column have been gathered. */
129188         rc = SQLCIPHER_DONE;
129189       }else{
129190         assert( iCurrent<=iMinPos );
129191         if( 0==(0xFE&*pTerm->pList) ){
129192           pTerm->pList = 0;
129193         }else{
129194           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
129195         }
129196         while( rc==SQLCIPHER_OK && iCurrent<iMinPos ){
129197           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
129198         }
129199         if( rc==SQLCIPHER_OK ){
129200           char aBuffer[64];
129201           sqlcipher3_snprintf(sizeof(aBuffer), aBuffer, 
129202               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
129203           );
129204           rc = fts3StringAppend(&res, aBuffer, -1);
129205         }else if( rc==SQLCIPHER_DONE && pTab->zContentTbl==0 ){
129206           rc = FTS_CORRUPT_VTAB;
129207         }
129208       }
129209     }
129210     if( rc==SQLCIPHER_DONE ){
129211       rc = SQLCIPHER_OK;
129212     }
129213
129214     pMod->xClose(pC);
129215     if( rc!=SQLCIPHER_OK ) goto offsets_out;
129216   }
129217
129218  offsets_out:
129219   sqlcipher3_free(sCtx.aTerm);
129220   assert( rc!=SQLCIPHER_DONE );
129221   sqlcipher3Fts3SegmentsClose(pTab);
129222   if( rc!=SQLCIPHER_OK ){
129223     sqlcipher3_result_error_code(pCtx,  rc);
129224     sqlcipher3_free(res.z);
129225   }else{
129226     sqlcipher3_result_text(pCtx, res.z, res.n-1, sqlcipher3_free);
129227   }
129228   return;
129229 }
129230
129231 /*
129232 ** Implementation of matchinfo() function.
129233 */
129234 SQLCIPHER_PRIVATE void sqlcipher3Fts3Matchinfo(
129235   sqlcipher3_context *pContext,      /* Function call context */
129236   Fts3Cursor *pCsr,               /* FTS3 table cursor */
129237   const char *zArg                /* Second arg to matchinfo() function */
129238 ){
129239   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129240   int rc;
129241   int i;
129242   const char *zFormat;
129243
129244   if( zArg ){
129245     for(i=0; zArg[i]; i++){
129246       char *zErr = 0;
129247       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
129248         sqlcipher3_result_error(pContext, zErr, -1);
129249         sqlcipher3_free(zErr);
129250         return;
129251       }
129252     }
129253     zFormat = zArg;
129254   }else{
129255     zFormat = FTS3_MATCHINFO_DEFAULT;
129256   }
129257
129258   if( !pCsr->pExpr ){
129259     sqlcipher3_result_blob(pContext, "", 0, SQLCIPHER_STATIC);
129260     return;
129261   }
129262
129263   /* Retrieve matchinfo() data. */
129264   rc = fts3GetMatchinfo(pCsr, zFormat);
129265   sqlcipher3Fts3SegmentsClose(pTab);
129266
129267   if( rc!=SQLCIPHER_OK ){
129268     sqlcipher3_result_error_code(pContext, rc);
129269   }else{
129270     int n = pCsr->nMatchinfo * sizeof(u32);
129271     sqlcipher3_result_blob(pContext, pCsr->aMatchinfo, n, SQLCIPHER_TRANSIENT);
129272   }
129273 }
129274
129275 #endif
129276
129277 /************** End of fts3_snippet.c ****************************************/
129278 /************** Begin file rtree.c *******************************************/
129279 /*
129280 ** 2001 September 15
129281 **
129282 ** The author disclaims copyright to this source code.  In place of
129283 ** a legal notice, here is a blessing:
129284 **
129285 **    May you do good and not evil.
129286 **    May you find forgiveness for yourself and forgive others.
129287 **    May you share freely, never taking more than you give.
129288 **
129289 *************************************************************************
129290 ** This file contains code for implementations of the r-tree and r*-tree
129291 ** algorithms packaged as an SQLite virtual table module.
129292 */
129293
129294 /*
129295 ** Database Format of R-Tree Tables
129296 ** --------------------------------
129297 **
129298 ** The data structure for a single virtual r-tree table is stored in three 
129299 ** native SQLite tables declared as follows. In each case, the '%' character
129300 ** in the table name is replaced with the user-supplied name of the r-tree
129301 ** table.
129302 **
129303 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
129304 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
129305 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
129306 **
129307 ** The data for each node of the r-tree structure is stored in the %_node
129308 ** table. For each node that is not the root node of the r-tree, there is
129309 ** an entry in the %_parent table associating the node with its parent.
129310 ** And for each row of data in the table, there is an entry in the %_rowid
129311 ** table that maps from the entries rowid to the id of the node that it
129312 ** is stored on.
129313 **
129314 ** The root node of an r-tree always exists, even if the r-tree table is
129315 ** empty. The nodeno of the root node is always 1. All other nodes in the
129316 ** table must be the same size as the root node. The content of each node
129317 ** is formatted as follows:
129318 **
129319 **   1. If the node is the root node (node 1), then the first 2 bytes
129320 **      of the node contain the tree depth as a big-endian integer.
129321 **      For non-root nodes, the first 2 bytes are left unused.
129322 **
129323 **   2. The next 2 bytes contain the number of entries currently 
129324 **      stored in the node.
129325 **
129326 **   3. The remainder of the node contains the node entries. Each entry
129327 **      consists of a single 8-byte integer followed by an even number
129328 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
129329 **      of a record. For internal nodes it is the node number of a
129330 **      child page.
129331 */
129332
129333 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_RTREE)
129334
129335 /*
129336 ** This file contains an implementation of a couple of different variants
129337 ** of the r-tree algorithm. See the README file for further details. The 
129338 ** same data-structure is used for all, but the algorithms for insert and
129339 ** delete operations vary. The variants used are selected at compile time 
129340 ** by defining the following symbols:
129341 */
129342
129343 /* Either, both or none of the following may be set to activate 
129344 ** r*tree variant algorithms.
129345 */
129346 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
129347 #define VARIANT_RSTARTREE_REINSERT      1
129348
129349 /* 
129350 ** Exactly one of the following must be set to 1.
129351 */
129352 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
129353 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
129354 #define VARIANT_RSTARTREE_SPLIT         1
129355
129356 #define VARIANT_GUTTMAN_SPLIT \
129357         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
129358
129359 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
129360   #define PickNext QuadraticPickNext
129361   #define PickSeeds QuadraticPickSeeds
129362   #define AssignCells splitNodeGuttman
129363 #endif
129364 #if VARIANT_GUTTMAN_LINEAR_SPLIT
129365   #define PickNext LinearPickNext
129366   #define PickSeeds LinearPickSeeds
129367   #define AssignCells splitNodeGuttman
129368 #endif
129369 #if VARIANT_RSTARTREE_SPLIT
129370   #define AssignCells splitNodeStartree
129371 #endif
129372
129373 #if !defined(NDEBUG) && !defined(SQLCIPHER_DEBUG) 
129374 # define NDEBUG 1
129375 #endif
129376
129377 #ifndef SQLCIPHER_CORE
129378   SQLCIPHER_EXTENSION_INIT1
129379 #else
129380 #endif
129381
129382 /* #include <string.h> */
129383 /* #include <assert.h> */
129384
129385 #ifndef SQLCIPHER_AMALGAMATION
129386 #include "sqlcipher3rtree.h"
129387 typedef sqlcipher3_int64 i64;
129388 typedef unsigned char u8;
129389 typedef unsigned int u32;
129390 #endif
129391
129392 /*  The following macro is used to suppress compiler warnings.
129393 */
129394 #ifndef UNUSED_PARAMETER
129395 # define UNUSED_PARAMETER(x) (void)(x)
129396 #endif
129397
129398 typedef struct Rtree Rtree;
129399 typedef struct RtreeCursor RtreeCursor;
129400 typedef struct RtreeNode RtreeNode;
129401 typedef struct RtreeCell RtreeCell;
129402 typedef struct RtreeConstraint RtreeConstraint;
129403 typedef struct RtreeMatchArg RtreeMatchArg;
129404 typedef struct RtreeGeomCallback RtreeGeomCallback;
129405 typedef union RtreeCoord RtreeCoord;
129406
129407 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
129408 #define RTREE_MAX_DIMENSIONS 5
129409
129410 /* Size of hash table Rtree.aHash. This hash table is not expected to
129411 ** ever contain very many entries, so a fixed number of buckets is 
129412 ** used.
129413 */
129414 #define HASHSIZE 128
129415
129416 /* 
129417 ** An rtree virtual-table object.
129418 */
129419 struct Rtree {
129420   sqlcipher3_vtab base;
129421   sqlcipher3 *db;                /* Host database connection */
129422   int iNodeSize;              /* Size in bytes of each node in the node table */
129423   int nDim;                   /* Number of dimensions */
129424   int nBytesPerCell;          /* Bytes consumed per cell */
129425   int iDepth;                 /* Current depth of the r-tree structure */
129426   char *zDb;                  /* Name of database containing r-tree table */
129427   char *zName;                /* Name of r-tree table */ 
129428   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
129429   int nBusy;                  /* Current number of users of this structure */
129430
129431   /* List of nodes removed during a CondenseTree operation. List is
129432   ** linked together via the pointer normally used for hash chains -
129433   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
129434   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
129435   */
129436   RtreeNode *pDeleted;
129437   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
129438
129439   /* Statements to read/write/delete a record from xxx_node */
129440   sqlcipher3_stmt *pReadNode;
129441   sqlcipher3_stmt *pWriteNode;
129442   sqlcipher3_stmt *pDeleteNode;
129443
129444   /* Statements to read/write/delete a record from xxx_rowid */
129445   sqlcipher3_stmt *pReadRowid;
129446   sqlcipher3_stmt *pWriteRowid;
129447   sqlcipher3_stmt *pDeleteRowid;
129448
129449   /* Statements to read/write/delete a record from xxx_parent */
129450   sqlcipher3_stmt *pReadParent;
129451   sqlcipher3_stmt *pWriteParent;
129452   sqlcipher3_stmt *pDeleteParent;
129453
129454   int eCoordType;
129455 };
129456
129457 /* Possible values for eCoordType: */
129458 #define RTREE_COORD_REAL32 0
129459 #define RTREE_COORD_INT32  1
129460
129461 /*
129462 ** The minimum number of cells allowed for a node is a third of the 
129463 ** maximum. In Gutman's notation:
129464 **
129465 **     m = M/3
129466 **
129467 ** If an R*-tree "Reinsert" operation is required, the same number of
129468 ** cells are removed from the overfull node and reinserted into the tree.
129469 */
129470 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
129471 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
129472 #define RTREE_MAXCELLS 51
129473
129474 /*
129475 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
129476 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
129477 ** Therefore all non-root nodes must contain at least 3 entries. Since 
129478 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
129479 ** 40 or less.
129480 */
129481 #define RTREE_MAX_DEPTH 40
129482
129483 /* 
129484 ** An rtree cursor object.
129485 */
129486 struct RtreeCursor {
129487   sqlcipher3_vtab_cursor base;
129488   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
129489   int iCell;                        /* Index of current cell in pNode */
129490   int iStrategy;                    /* Copy of idxNum search parameter */
129491   int nConstraint;                  /* Number of entries in aConstraint */
129492   RtreeConstraint *aConstraint;     /* Search constraints. */
129493 };
129494
129495 union RtreeCoord {
129496   float f;
129497   int i;
129498 };
129499
129500 /*
129501 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
129502 ** formatted as a double. This macro assumes that local variable pRtree points
129503 ** to the Rtree structure associated with the RtreeCoord.
129504 */
129505 #define DCOORD(coord) (                           \
129506   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
129507     ((double)coord.f) :                           \
129508     ((double)coord.i)                             \
129509 )
129510
129511 /*
129512 ** A search constraint.
129513 */
129514 struct RtreeConstraint {
129515   int iCoord;                     /* Index of constrained coordinate */
129516   int op;                         /* Constraining operation */
129517   double rValue;                  /* Constraint value. */
129518   int (*xGeom)(sqlcipher3_rtree_geometry *, int, double *, int *);
129519   sqlcipher3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
129520 };
129521
129522 /* Possible values for RtreeConstraint.op */
129523 #define RTREE_EQ    0x41
129524 #define RTREE_LE    0x42
129525 #define RTREE_LT    0x43
129526 #define RTREE_GE    0x44
129527 #define RTREE_GT    0x45
129528 #define RTREE_MATCH 0x46
129529
129530 /* 
129531 ** An rtree structure node.
129532 */
129533 struct RtreeNode {
129534   RtreeNode *pParent;               /* Parent node */
129535   i64 iNode;
129536   int nRef;
129537   int isDirty;
129538   u8 *zData;
129539   RtreeNode *pNext;                 /* Next node in this hash chain */
129540 };
129541 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
129542
129543 /* 
129544 ** Structure to store a deserialized rtree record.
129545 */
129546 struct RtreeCell {
129547   i64 iRowid;
129548   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
129549 };
129550
129551
129552 /*
129553 ** Value for the first field of every RtreeMatchArg object. The MATCH
129554 ** operator tests that the first field of a blob operand matches this
129555 ** value to avoid operating on invalid blobs (which could cause a segfault).
129556 */
129557 #define RTREE_GEOMETRY_MAGIC 0x891245AB
129558
129559 /*
129560 ** An instance of this structure must be supplied as a blob argument to
129561 ** the right-hand-side of an SQL MATCH operator used to constrain an
129562 ** r-tree query.
129563 */
129564 struct RtreeMatchArg {
129565   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
129566   int (*xGeom)(sqlcipher3_rtree_geometry *, int, double *, int *);
129567   void *pContext;
129568   int nParam;
129569   double aParam[1];
129570 };
129571
129572 /*
129573 ** When a geometry callback is created (see sqlcipher3_rtree_geometry_callback),
129574 ** a single instance of the following structure is allocated. It is used
129575 ** as the context for the user-function created by by s_r_g_c(). The object
129576 ** is eventually deleted by the destructor mechanism provided by
129577 ** sqlcipher3_create_function_v2() (which is called by s_r_g_c() to create
129578 ** the geometry callback function).
129579 */
129580 struct RtreeGeomCallback {
129581   int (*xGeom)(sqlcipher3_rtree_geometry *, int, double *, int *);
129582   void *pContext;
129583 };
129584
129585 #ifndef MAX
129586 # define MAX(x,y) ((x) < (y) ? (y) : (x))
129587 #endif
129588 #ifndef MIN
129589 # define MIN(x,y) ((x) > (y) ? (y) : (x))
129590 #endif
129591
129592 /*
129593 ** Functions to deserialize a 16 bit integer, 32 bit real number and
129594 ** 64 bit integer. The deserialized value is returned.
129595 */
129596 static int readInt16(u8 *p){
129597   return (p[0]<<8) + p[1];
129598 }
129599 static void readCoord(u8 *p, RtreeCoord *pCoord){
129600   u32 i = (
129601     (((u32)p[0]) << 24) + 
129602     (((u32)p[1]) << 16) + 
129603     (((u32)p[2]) <<  8) + 
129604     (((u32)p[3]) <<  0)
129605   );
129606   *(u32 *)pCoord = i;
129607 }
129608 static i64 readInt64(u8 *p){
129609   return (
129610     (((i64)p[0]) << 56) + 
129611     (((i64)p[1]) << 48) + 
129612     (((i64)p[2]) << 40) + 
129613     (((i64)p[3]) << 32) + 
129614     (((i64)p[4]) << 24) + 
129615     (((i64)p[5]) << 16) + 
129616     (((i64)p[6]) <<  8) + 
129617     (((i64)p[7]) <<  0)
129618   );
129619 }
129620
129621 /*
129622 ** Functions to serialize a 16 bit integer, 32 bit real number and
129623 ** 64 bit integer. The value returned is the number of bytes written
129624 ** to the argument buffer (always 2, 4 and 8 respectively).
129625 */
129626 static int writeInt16(u8 *p, int i){
129627   p[0] = (i>> 8)&0xFF;
129628   p[1] = (i>> 0)&0xFF;
129629   return 2;
129630 }
129631 static int writeCoord(u8 *p, RtreeCoord *pCoord){
129632   u32 i;
129633   assert( sizeof(RtreeCoord)==4 );
129634   assert( sizeof(u32)==4 );
129635   i = *(u32 *)pCoord;
129636   p[0] = (i>>24)&0xFF;
129637   p[1] = (i>>16)&0xFF;
129638   p[2] = (i>> 8)&0xFF;
129639   p[3] = (i>> 0)&0xFF;
129640   return 4;
129641 }
129642 static int writeInt64(u8 *p, i64 i){
129643   p[0] = (i>>56)&0xFF;
129644   p[1] = (i>>48)&0xFF;
129645   p[2] = (i>>40)&0xFF;
129646   p[3] = (i>>32)&0xFF;
129647   p[4] = (i>>24)&0xFF;
129648   p[5] = (i>>16)&0xFF;
129649   p[6] = (i>> 8)&0xFF;
129650   p[7] = (i>> 0)&0xFF;
129651   return 8;
129652 }
129653
129654 /*
129655 ** Increment the reference count of node p.
129656 */
129657 static void nodeReference(RtreeNode *p){
129658   if( p ){
129659     p->nRef++;
129660   }
129661 }
129662
129663 /*
129664 ** Clear the content of node p (set all bytes to 0x00).
129665 */
129666 static void nodeZero(Rtree *pRtree, RtreeNode *p){
129667   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
129668   p->isDirty = 1;
129669 }
129670
129671 /*
129672 ** Given a node number iNode, return the corresponding key to use
129673 ** in the Rtree.aHash table.
129674 */
129675 static int nodeHash(i64 iNode){
129676   return (
129677     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
129678     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
129679   ) % HASHSIZE;
129680 }
129681
129682 /*
129683 ** Search the node hash table for node iNode. If found, return a pointer
129684 ** to it. Otherwise, return 0.
129685 */
129686 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
129687   RtreeNode *p;
129688   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
129689   return p;
129690 }
129691
129692 /*
129693 ** Add node pNode to the node hash table.
129694 */
129695 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
129696   int iHash;
129697   assert( pNode->pNext==0 );
129698   iHash = nodeHash(pNode->iNode);
129699   pNode->pNext = pRtree->aHash[iHash];
129700   pRtree->aHash[iHash] = pNode;
129701 }
129702
129703 /*
129704 ** Remove node pNode from the node hash table.
129705 */
129706 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
129707   RtreeNode **pp;
129708   if( pNode->iNode!=0 ){
129709     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
129710     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
129711     *pp = pNode->pNext;
129712     pNode->pNext = 0;
129713   }
129714 }
129715
129716 /*
129717 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
129718 ** indicating that node has not yet been assigned a node number. It is
129719 ** assigned a node number when nodeWrite() is called to write the
129720 ** node contents out to the database.
129721 */
129722 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
129723   RtreeNode *pNode;
129724   pNode = (RtreeNode *)sqlcipher3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
129725   if( pNode ){
129726     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
129727     pNode->zData = (u8 *)&pNode[1];
129728     pNode->nRef = 1;
129729     pNode->pParent = pParent;
129730     pNode->isDirty = 1;
129731     nodeReference(pParent);
129732   }
129733   return pNode;
129734 }
129735
129736 /*
129737 ** Obtain a reference to an r-tree node.
129738 */
129739 static int
129740 nodeAcquire(
129741   Rtree *pRtree,             /* R-tree structure */
129742   i64 iNode,                 /* Node number to load */
129743   RtreeNode *pParent,        /* Either the parent node or NULL */
129744   RtreeNode **ppNode         /* OUT: Acquired node */
129745 ){
129746   int rc;
129747   int rc2 = SQLCIPHER_OK;
129748   RtreeNode *pNode;
129749
129750   /* Check if the requested node is already in the hash table. If so,
129751   ** increase its reference count and return it.
129752   */
129753   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
129754     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
129755     if( pParent && !pNode->pParent ){
129756       nodeReference(pParent);
129757       pNode->pParent = pParent;
129758     }
129759     pNode->nRef++;
129760     *ppNode = pNode;
129761     return SQLCIPHER_OK;
129762   }
129763
129764   sqlcipher3_bind_int64(pRtree->pReadNode, 1, iNode);
129765   rc = sqlcipher3_step(pRtree->pReadNode);
129766   if( rc==SQLCIPHER_ROW ){
129767     const u8 *zBlob = sqlcipher3_column_blob(pRtree->pReadNode, 0);
129768     if( pRtree->iNodeSize==sqlcipher3_column_bytes(pRtree->pReadNode, 0) ){
129769       pNode = (RtreeNode *)sqlcipher3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
129770       if( !pNode ){
129771         rc2 = SQLCIPHER_NOMEM;
129772       }else{
129773         pNode->pParent = pParent;
129774         pNode->zData = (u8 *)&pNode[1];
129775         pNode->nRef = 1;
129776         pNode->iNode = iNode;
129777         pNode->isDirty = 0;
129778         pNode->pNext = 0;
129779         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
129780         nodeReference(pParent);
129781       }
129782     }
129783   }
129784   rc = sqlcipher3_reset(pRtree->pReadNode);
129785   if( rc==SQLCIPHER_OK ) rc = rc2;
129786
129787   /* If the root node was just loaded, set pRtree->iDepth to the height
129788   ** of the r-tree structure. A height of zero means all data is stored on
129789   ** the root node. A height of one means the children of the root node
129790   ** are the leaves, and so on. If the depth as specified on the root node
129791   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
129792   */
129793   if( pNode && iNode==1 ){
129794     pRtree->iDepth = readInt16(pNode->zData);
129795     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
129796       rc = SQLCIPHER_CORRUPT_VTAB;
129797     }
129798   }
129799
129800   /* If no error has occurred so far, check if the "number of entries"
129801   ** field on the node is too large. If so, set the return code to 
129802   ** SQLCIPHER_CORRUPT_VTAB.
129803   */
129804   if( pNode && rc==SQLCIPHER_OK ){
129805     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
129806       rc = SQLCIPHER_CORRUPT_VTAB;
129807     }
129808   }
129809
129810   if( rc==SQLCIPHER_OK ){
129811     if( pNode!=0 ){
129812       nodeHashInsert(pRtree, pNode);
129813     }else{
129814       rc = SQLCIPHER_CORRUPT_VTAB;
129815     }
129816     *ppNode = pNode;
129817   }else{
129818     sqlcipher3_free(pNode);
129819     *ppNode = 0;
129820   }
129821
129822   return rc;
129823 }
129824
129825 /*
129826 ** Overwrite cell iCell of node pNode with the contents of pCell.
129827 */
129828 static void nodeOverwriteCell(
129829   Rtree *pRtree, 
129830   RtreeNode *pNode,  
129831   RtreeCell *pCell, 
129832   int iCell
129833 ){
129834   int ii;
129835   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
129836   p += writeInt64(p, pCell->iRowid);
129837   for(ii=0; ii<(pRtree->nDim*2); ii++){
129838     p += writeCoord(p, &pCell->aCoord[ii]);
129839   }
129840   pNode->isDirty = 1;
129841 }
129842
129843 /*
129844 ** Remove cell the cell with index iCell from node pNode.
129845 */
129846 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
129847   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
129848   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
129849   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
129850   memmove(pDst, pSrc, nByte);
129851   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
129852   pNode->isDirty = 1;
129853 }
129854
129855 /*
129856 ** Insert the contents of cell pCell into node pNode. If the insert
129857 ** is successful, return SQLCIPHER_OK.
129858 **
129859 ** If there is not enough free space in pNode, return SQLCIPHER_FULL.
129860 */
129861 static int
129862 nodeInsertCell(
129863   Rtree *pRtree, 
129864   RtreeNode *pNode, 
129865   RtreeCell *pCell 
129866 ){
129867   int nCell;                    /* Current number of cells in pNode */
129868   int nMaxCell;                 /* Maximum number of cells for pNode */
129869
129870   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
129871   nCell = NCELL(pNode);
129872
129873   assert( nCell<=nMaxCell );
129874   if( nCell<nMaxCell ){
129875     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
129876     writeInt16(&pNode->zData[2], nCell+1);
129877     pNode->isDirty = 1;
129878   }
129879
129880   return (nCell==nMaxCell);
129881 }
129882
129883 /*
129884 ** If the node is dirty, write it out to the database.
129885 */
129886 static int
129887 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
129888   int rc = SQLCIPHER_OK;
129889   if( pNode->isDirty ){
129890     sqlcipher3_stmt *p = pRtree->pWriteNode;
129891     if( pNode->iNode ){
129892       sqlcipher3_bind_int64(p, 1, pNode->iNode);
129893     }else{
129894       sqlcipher3_bind_null(p, 1);
129895     }
129896     sqlcipher3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLCIPHER_STATIC);
129897     sqlcipher3_step(p);
129898     pNode->isDirty = 0;
129899     rc = sqlcipher3_reset(p);
129900     if( pNode->iNode==0 && rc==SQLCIPHER_OK ){
129901       pNode->iNode = sqlcipher3_last_insert_rowid(pRtree->db);
129902       nodeHashInsert(pRtree, pNode);
129903     }
129904   }
129905   return rc;
129906 }
129907
129908 /*
129909 ** Release a reference to a node. If the node is dirty and the reference
129910 ** count drops to zero, the node data is written to the database.
129911 */
129912 static int
129913 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
129914   int rc = SQLCIPHER_OK;
129915   if( pNode ){
129916     assert( pNode->nRef>0 );
129917     pNode->nRef--;
129918     if( pNode->nRef==0 ){
129919       if( pNode->iNode==1 ){
129920         pRtree->iDepth = -1;
129921       }
129922       if( pNode->pParent ){
129923         rc = nodeRelease(pRtree, pNode->pParent);
129924       }
129925       if( rc==SQLCIPHER_OK ){
129926         rc = nodeWrite(pRtree, pNode);
129927       }
129928       nodeHashDelete(pRtree, pNode);
129929       sqlcipher3_free(pNode);
129930     }
129931   }
129932   return rc;
129933 }
129934
129935 /*
129936 ** Return the 64-bit integer value associated with cell iCell of
129937 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
129938 ** an internal node, then the 64-bit integer is a child page number.
129939 */
129940 static i64 nodeGetRowid(
129941   Rtree *pRtree, 
129942   RtreeNode *pNode, 
129943   int iCell
129944 ){
129945   assert( iCell<NCELL(pNode) );
129946   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
129947 }
129948
129949 /*
129950 ** Return coordinate iCoord from cell iCell in node pNode.
129951 */
129952 static void nodeGetCoord(
129953   Rtree *pRtree, 
129954   RtreeNode *pNode, 
129955   int iCell,
129956   int iCoord,
129957   RtreeCoord *pCoord           /* Space to write result to */
129958 ){
129959   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
129960 }
129961
129962 /*
129963 ** Deserialize cell iCell of node pNode. Populate the structure pointed
129964 ** to by pCell with the results.
129965 */
129966 static void nodeGetCell(
129967   Rtree *pRtree, 
129968   RtreeNode *pNode, 
129969   int iCell,
129970   RtreeCell *pCell
129971 ){
129972   int ii;
129973   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
129974   for(ii=0; ii<pRtree->nDim*2; ii++){
129975     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
129976   }
129977 }
129978
129979
129980 /* Forward declaration for the function that does the work of
129981 ** the virtual table module xCreate() and xConnect() methods.
129982 */
129983 static int rtreeInit(
129984   sqlcipher3 *, void *, int, const char *const*, sqlcipher3_vtab **, char **, int
129985 );
129986
129987 /* 
129988 ** Rtree virtual table module xCreate method.
129989 */
129990 static int rtreeCreate(
129991   sqlcipher3 *db,
129992   void *pAux,
129993   int argc, const char *const*argv,
129994   sqlcipher3_vtab **ppVtab,
129995   char **pzErr
129996 ){
129997   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
129998 }
129999
130000 /* 
130001 ** Rtree virtual table module xConnect method.
130002 */
130003 static int rtreeConnect(
130004   sqlcipher3 *db,
130005   void *pAux,
130006   int argc, const char *const*argv,
130007   sqlcipher3_vtab **ppVtab,
130008   char **pzErr
130009 ){
130010   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
130011 }
130012
130013 /*
130014 ** Increment the r-tree reference count.
130015 */
130016 static void rtreeReference(Rtree *pRtree){
130017   pRtree->nBusy++;
130018 }
130019
130020 /*
130021 ** Decrement the r-tree reference count. When the reference count reaches
130022 ** zero the structure is deleted.
130023 */
130024 static void rtreeRelease(Rtree *pRtree){
130025   pRtree->nBusy--;
130026   if( pRtree->nBusy==0 ){
130027     sqlcipher3_finalize(pRtree->pReadNode);
130028     sqlcipher3_finalize(pRtree->pWriteNode);
130029     sqlcipher3_finalize(pRtree->pDeleteNode);
130030     sqlcipher3_finalize(pRtree->pReadRowid);
130031     sqlcipher3_finalize(pRtree->pWriteRowid);
130032     sqlcipher3_finalize(pRtree->pDeleteRowid);
130033     sqlcipher3_finalize(pRtree->pReadParent);
130034     sqlcipher3_finalize(pRtree->pWriteParent);
130035     sqlcipher3_finalize(pRtree->pDeleteParent);
130036     sqlcipher3_free(pRtree);
130037   }
130038 }
130039
130040 /* 
130041 ** Rtree virtual table module xDisconnect method.
130042 */
130043 static int rtreeDisconnect(sqlcipher3_vtab *pVtab){
130044   rtreeRelease((Rtree *)pVtab);
130045   return SQLCIPHER_OK;
130046 }
130047
130048 /* 
130049 ** Rtree virtual table module xDestroy method.
130050 */
130051 static int rtreeDestroy(sqlcipher3_vtab *pVtab){
130052   Rtree *pRtree = (Rtree *)pVtab;
130053   int rc;
130054   char *zCreate = sqlcipher3_mprintf(
130055     "DROP TABLE '%q'.'%q_node';"
130056     "DROP TABLE '%q'.'%q_rowid';"
130057     "DROP TABLE '%q'.'%q_parent';",
130058     pRtree->zDb, pRtree->zName, 
130059     pRtree->zDb, pRtree->zName,
130060     pRtree->zDb, pRtree->zName
130061   );
130062   if( !zCreate ){
130063     rc = SQLCIPHER_NOMEM;
130064   }else{
130065     rc = sqlcipher3_exec(pRtree->db, zCreate, 0, 0, 0);
130066     sqlcipher3_free(zCreate);
130067   }
130068   if( rc==SQLCIPHER_OK ){
130069     rtreeRelease(pRtree);
130070   }
130071
130072   return rc;
130073 }
130074
130075 /* 
130076 ** Rtree virtual table module xOpen method.
130077 */
130078 static int rtreeOpen(sqlcipher3_vtab *pVTab, sqlcipher3_vtab_cursor **ppCursor){
130079   int rc = SQLCIPHER_NOMEM;
130080   RtreeCursor *pCsr;
130081
130082   pCsr = (RtreeCursor *)sqlcipher3_malloc(sizeof(RtreeCursor));
130083   if( pCsr ){
130084     memset(pCsr, 0, sizeof(RtreeCursor));
130085     pCsr->base.pVtab = pVTab;
130086     rc = SQLCIPHER_OK;
130087   }
130088   *ppCursor = (sqlcipher3_vtab_cursor *)pCsr;
130089
130090   return rc;
130091 }
130092
130093
130094 /*
130095 ** Free the RtreeCursor.aConstraint[] array and its contents.
130096 */
130097 static void freeCursorConstraints(RtreeCursor *pCsr){
130098   if( pCsr->aConstraint ){
130099     int i;                        /* Used to iterate through constraint array */
130100     for(i=0; i<pCsr->nConstraint; i++){
130101       sqlcipher3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
130102       if( pGeom ){
130103         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
130104         sqlcipher3_free(pGeom);
130105       }
130106     }
130107     sqlcipher3_free(pCsr->aConstraint);
130108     pCsr->aConstraint = 0;
130109   }
130110 }
130111
130112 /* 
130113 ** Rtree virtual table module xClose method.
130114 */
130115 static int rtreeClose(sqlcipher3_vtab_cursor *cur){
130116   Rtree *pRtree = (Rtree *)(cur->pVtab);
130117   int rc;
130118   RtreeCursor *pCsr = (RtreeCursor *)cur;
130119   freeCursorConstraints(pCsr);
130120   rc = nodeRelease(pRtree, pCsr->pNode);
130121   sqlcipher3_free(pCsr);
130122   return rc;
130123 }
130124
130125 /*
130126 ** Rtree virtual table module xEof method.
130127 **
130128 ** Return non-zero if the cursor does not currently point to a valid 
130129 ** record (i.e if the scan has finished), or zero otherwise.
130130 */
130131 static int rtreeEof(sqlcipher3_vtab_cursor *cur){
130132   RtreeCursor *pCsr = (RtreeCursor *)cur;
130133   return (pCsr->pNode==0);
130134 }
130135
130136 /*
130137 ** The r-tree constraint passed as the second argument to this function is
130138 ** guaranteed to be a MATCH constraint.
130139 */
130140 static int testRtreeGeom(
130141   Rtree *pRtree,                  /* R-Tree object */
130142   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
130143   RtreeCell *pCell,               /* Cell to test */
130144   int *pbRes                      /* OUT: Test result */
130145 ){
130146   int i;
130147   double aCoord[RTREE_MAX_DIMENSIONS*2];
130148   int nCoord = pRtree->nDim*2;
130149
130150   assert( pConstraint->op==RTREE_MATCH );
130151   assert( pConstraint->pGeom );
130152
130153   for(i=0; i<nCoord; i++){
130154     aCoord[i] = DCOORD(pCell->aCoord[i]);
130155   }
130156   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
130157 }
130158
130159 /* 
130160 ** Cursor pCursor currently points to a cell in a non-leaf page.
130161 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
130162 ** (excluded) by the constraints in the pCursor->aConstraint[] 
130163 ** array, or false otherwise.
130164 **
130165 ** Return SQLCIPHER_OK if successful or an SQLite error code if an error
130166 ** occurs within a geometry callback.
130167 */
130168 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
130169   RtreeCell cell;
130170   int ii;
130171   int bRes = 0;
130172   int rc = SQLCIPHER_OK;
130173
130174   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
130175   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
130176     RtreeConstraint *p = &pCursor->aConstraint[ii];
130177     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
130178     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
130179
130180     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
130181         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
130182     );
130183
130184     switch( p->op ){
130185       case RTREE_LE: case RTREE_LT: 
130186         bRes = p->rValue<cell_min; 
130187         break;
130188
130189       case RTREE_GE: case RTREE_GT: 
130190         bRes = p->rValue>cell_max; 
130191         break;
130192
130193       case RTREE_EQ:
130194         bRes = (p->rValue>cell_max || p->rValue<cell_min);
130195         break;
130196
130197       default: {
130198         assert( p->op==RTREE_MATCH );
130199         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
130200         bRes = !bRes;
130201         break;
130202       }
130203     }
130204   }
130205
130206   *pbEof = bRes;
130207   return rc;
130208 }
130209
130210 /* 
130211 ** Test if the cell that cursor pCursor currently points to
130212 ** would be filtered (excluded) by the constraints in the 
130213 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
130214 ** returning. If the cell is not filtered (excluded) by the constraints,
130215 ** set pbEof to zero.
130216 **
130217 ** Return SQLCIPHER_OK if successful or an SQLite error code if an error
130218 ** occurs within a geometry callback.
130219 **
130220 ** This function assumes that the cell is part of a leaf node.
130221 */
130222 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
130223   RtreeCell cell;
130224   int ii;
130225   *pbEof = 0;
130226
130227   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
130228   for(ii=0; ii<pCursor->nConstraint; ii++){
130229     RtreeConstraint *p = &pCursor->aConstraint[ii];
130230     double coord = DCOORD(cell.aCoord[p->iCoord]);
130231     int res;
130232     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
130233         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
130234     );
130235     switch( p->op ){
130236       case RTREE_LE: res = (coord<=p->rValue); break;
130237       case RTREE_LT: res = (coord<p->rValue);  break;
130238       case RTREE_GE: res = (coord>=p->rValue); break;
130239       case RTREE_GT: res = (coord>p->rValue);  break;
130240       case RTREE_EQ: res = (coord==p->rValue); break;
130241       default: {
130242         int rc;
130243         assert( p->op==RTREE_MATCH );
130244         rc = testRtreeGeom(pRtree, p, &cell, &res);
130245         if( rc!=SQLCIPHER_OK ){
130246           return rc;
130247         }
130248         break;
130249       }
130250     }
130251
130252     if( !res ){
130253       *pbEof = 1;
130254       return SQLCIPHER_OK;
130255     }
130256   }
130257
130258   return SQLCIPHER_OK;
130259 }
130260
130261 /*
130262 ** Cursor pCursor currently points at a node that heads a sub-tree of
130263 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
130264 ** to point to the left-most cell of the sub-tree that matches the 
130265 ** configured constraints.
130266 */
130267 static int descendToCell(
130268   Rtree *pRtree, 
130269   RtreeCursor *pCursor, 
130270   int iHeight,
130271   int *pEof                 /* OUT: Set to true if cannot descend */
130272 ){
130273   int isEof;
130274   int rc;
130275   int ii;
130276   RtreeNode *pChild;
130277   sqlcipher3_int64 iRowid;
130278
130279   RtreeNode *pSavedNode = pCursor->pNode;
130280   int iSavedCell = pCursor->iCell;
130281
130282   assert( iHeight>=0 );
130283
130284   if( iHeight==0 ){
130285     rc = testRtreeEntry(pRtree, pCursor, &isEof);
130286   }else{
130287     rc = testRtreeCell(pRtree, pCursor, &isEof);
130288   }
130289   if( rc!=SQLCIPHER_OK || isEof || iHeight==0 ){
130290     goto descend_to_cell_out;
130291   }
130292
130293   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
130294   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
130295   if( rc!=SQLCIPHER_OK ){
130296     goto descend_to_cell_out;
130297   }
130298
130299   nodeRelease(pRtree, pCursor->pNode);
130300   pCursor->pNode = pChild;
130301   isEof = 1;
130302   for(ii=0; isEof && ii<NCELL(pChild); ii++){
130303     pCursor->iCell = ii;
130304     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
130305     if( rc!=SQLCIPHER_OK ){
130306       goto descend_to_cell_out;
130307     }
130308   }
130309
130310   if( isEof ){
130311     assert( pCursor->pNode==pChild );
130312     nodeReference(pSavedNode);
130313     nodeRelease(pRtree, pChild);
130314     pCursor->pNode = pSavedNode;
130315     pCursor->iCell = iSavedCell;
130316   }
130317
130318 descend_to_cell_out:
130319   *pEof = isEof;
130320   return rc;
130321 }
130322
130323 /*
130324 ** One of the cells in node pNode is guaranteed to have a 64-bit 
130325 ** integer value equal to iRowid. Return the index of this cell.
130326 */
130327 static int nodeRowidIndex(
130328   Rtree *pRtree, 
130329   RtreeNode *pNode, 
130330   i64 iRowid,
130331   int *piIndex
130332 ){
130333   int ii;
130334   int nCell = NCELL(pNode);
130335   for(ii=0; ii<nCell; ii++){
130336     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
130337       *piIndex = ii;
130338       return SQLCIPHER_OK;
130339     }
130340   }
130341   return SQLCIPHER_CORRUPT_VTAB;
130342 }
130343
130344 /*
130345 ** Return the index of the cell containing a pointer to node pNode
130346 ** in its parent. If pNode is the root node, return -1.
130347 */
130348 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
130349   RtreeNode *pParent = pNode->pParent;
130350   if( pParent ){
130351     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
130352   }
130353   *piIndex = -1;
130354   return SQLCIPHER_OK;
130355 }
130356
130357 /* 
130358 ** Rtree virtual table module xNext method.
130359 */
130360 static int rtreeNext(sqlcipher3_vtab_cursor *pVtabCursor){
130361   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
130362   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
130363   int rc = SQLCIPHER_OK;
130364
130365   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
130366   ** already at EOF. It is against the rules to call the xNext() method of
130367   ** a cursor that has already reached EOF.
130368   */
130369   assert( pCsr->pNode );
130370
130371   if( pCsr->iStrategy==1 ){
130372     /* This "scan" is a direct lookup by rowid. There is no next entry. */
130373     nodeRelease(pRtree, pCsr->pNode);
130374     pCsr->pNode = 0;
130375   }else{
130376     /* Move to the next entry that matches the configured constraints. */
130377     int iHeight = 0;
130378     while( pCsr->pNode ){
130379       RtreeNode *pNode = pCsr->pNode;
130380       int nCell = NCELL(pNode);
130381       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
130382         int isEof;
130383         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
130384         if( rc!=SQLCIPHER_OK || !isEof ){
130385           return rc;
130386         }
130387       }
130388       pCsr->pNode = pNode->pParent;
130389       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
130390       if( rc!=SQLCIPHER_OK ){
130391         return rc;
130392       }
130393       nodeReference(pCsr->pNode);
130394       nodeRelease(pRtree, pNode);
130395       iHeight++;
130396     }
130397   }
130398
130399   return rc;
130400 }
130401
130402 /* 
130403 ** Rtree virtual table module xRowid method.
130404 */
130405 static int rtreeRowid(sqlcipher3_vtab_cursor *pVtabCursor, sqlcipher_int64 *pRowid){
130406   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
130407   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
130408
130409   assert(pCsr->pNode);
130410   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
130411
130412   return SQLCIPHER_OK;
130413 }
130414
130415 /* 
130416 ** Rtree virtual table module xColumn method.
130417 */
130418 static int rtreeColumn(sqlcipher3_vtab_cursor *cur, sqlcipher3_context *ctx, int i){
130419   Rtree *pRtree = (Rtree *)cur->pVtab;
130420   RtreeCursor *pCsr = (RtreeCursor *)cur;
130421
130422   if( i==0 ){
130423     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
130424     sqlcipher3_result_int64(ctx, iRowid);
130425   }else{
130426     RtreeCoord c;
130427     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
130428     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
130429       sqlcipher3_result_double(ctx, c.f);
130430     }else{
130431       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
130432       sqlcipher3_result_int(ctx, c.i);
130433     }
130434   }
130435
130436   return SQLCIPHER_OK;
130437 }
130438
130439 /* 
130440 ** Use nodeAcquire() to obtain the leaf node containing the record with 
130441 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
130442 ** return SQLCIPHER_OK. If there is no such record in the table, set
130443 ** *ppLeaf to 0 and return SQLCIPHER_OK. If an error occurs, set *ppLeaf
130444 ** to zero and return an SQLite error code.
130445 */
130446 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
130447   int rc;
130448   *ppLeaf = 0;
130449   sqlcipher3_bind_int64(pRtree->pReadRowid, 1, iRowid);
130450   if( sqlcipher3_step(pRtree->pReadRowid)==SQLCIPHER_ROW ){
130451     i64 iNode = sqlcipher3_column_int64(pRtree->pReadRowid, 0);
130452     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
130453     sqlcipher3_reset(pRtree->pReadRowid);
130454   }else{
130455     rc = sqlcipher3_reset(pRtree->pReadRowid);
130456   }
130457   return rc;
130458 }
130459
130460 /*
130461 ** This function is called to configure the RtreeConstraint object passed
130462 ** as the second argument for a MATCH constraint. The value passed as the
130463 ** first argument to this function is the right-hand operand to the MATCH
130464 ** operator.
130465 */
130466 static int deserializeGeometry(sqlcipher3_value *pValue, RtreeConstraint *pCons){
130467   RtreeMatchArg *p;
130468   sqlcipher3_rtree_geometry *pGeom;
130469   int nBlob;
130470
130471   /* Check that value is actually a blob. */
130472   if( !sqlcipher3_value_type(pValue)==SQLCIPHER_BLOB ) return SQLCIPHER_ERROR;
130473
130474   /* Check that the blob is roughly the right size. */
130475   nBlob = sqlcipher3_value_bytes(pValue);
130476   if( nBlob<(int)sizeof(RtreeMatchArg) 
130477    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
130478   ){
130479     return SQLCIPHER_ERROR;
130480   }
130481
130482   pGeom = (sqlcipher3_rtree_geometry *)sqlcipher3_malloc(
130483       sizeof(sqlcipher3_rtree_geometry) + nBlob
130484   );
130485   if( !pGeom ) return SQLCIPHER_NOMEM;
130486   memset(pGeom, 0, sizeof(sqlcipher3_rtree_geometry));
130487   p = (RtreeMatchArg *)&pGeom[1];
130488
130489   memcpy(p, sqlcipher3_value_blob(pValue), nBlob);
130490   if( p->magic!=RTREE_GEOMETRY_MAGIC 
130491    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
130492   ){
130493     sqlcipher3_free(pGeom);
130494     return SQLCIPHER_ERROR;
130495   }
130496
130497   pGeom->pContext = p->pContext;
130498   pGeom->nParam = p->nParam;
130499   pGeom->aParam = p->aParam;
130500
130501   pCons->xGeom = p->xGeom;
130502   pCons->pGeom = pGeom;
130503   return SQLCIPHER_OK;
130504 }
130505
130506 /* 
130507 ** Rtree virtual table module xFilter method.
130508 */
130509 static int rtreeFilter(
130510   sqlcipher3_vtab_cursor *pVtabCursor, 
130511   int idxNum, const char *idxStr,
130512   int argc, sqlcipher3_value **argv
130513 ){
130514   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
130515   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
130516
130517   RtreeNode *pRoot = 0;
130518   int ii;
130519   int rc = SQLCIPHER_OK;
130520
130521   rtreeReference(pRtree);
130522
130523   freeCursorConstraints(pCsr);
130524   pCsr->iStrategy = idxNum;
130525
130526   if( idxNum==1 ){
130527     /* Special case - lookup by rowid. */
130528     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
130529     i64 iRowid = sqlcipher3_value_int64(argv[0]);
130530     rc = findLeafNode(pRtree, iRowid, &pLeaf);
130531     pCsr->pNode = pLeaf; 
130532     if( pLeaf ){
130533       assert( rc==SQLCIPHER_OK );
130534       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
130535     }
130536   }else{
130537     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
130538     ** with the configured constraints. 
130539     */
130540     if( argc>0 ){
130541       pCsr->aConstraint = sqlcipher3_malloc(sizeof(RtreeConstraint)*argc);
130542       pCsr->nConstraint = argc;
130543       if( !pCsr->aConstraint ){
130544         rc = SQLCIPHER_NOMEM;
130545       }else{
130546         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
130547         assert( (idxStr==0 && argc==0)
130548                 || (idxStr && (int)strlen(idxStr)==argc*2) );
130549         for(ii=0; ii<argc; ii++){
130550           RtreeConstraint *p = &pCsr->aConstraint[ii];
130551           p->op = idxStr[ii*2];
130552           p->iCoord = idxStr[ii*2+1]-'a';
130553           if( p->op==RTREE_MATCH ){
130554             /* A MATCH operator. The right-hand-side must be a blob that
130555             ** can be cast into an RtreeMatchArg object. One created using
130556             ** an sqlcipher3_rtree_geometry_callback() SQL user function.
130557             */
130558             rc = deserializeGeometry(argv[ii], p);
130559             if( rc!=SQLCIPHER_OK ){
130560               break;
130561             }
130562           }else{
130563             p->rValue = sqlcipher3_value_double(argv[ii]);
130564           }
130565         }
130566       }
130567     }
130568   
130569     if( rc==SQLCIPHER_OK ){
130570       pCsr->pNode = 0;
130571       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
130572     }
130573     if( rc==SQLCIPHER_OK ){
130574       int isEof = 1;
130575       int nCell = NCELL(pRoot);
130576       pCsr->pNode = pRoot;
130577       for(pCsr->iCell=0; rc==SQLCIPHER_OK && pCsr->iCell<nCell; pCsr->iCell++){
130578         assert( pCsr->pNode==pRoot );
130579         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
130580         if( !isEof ){
130581           break;
130582         }
130583       }
130584       if( rc==SQLCIPHER_OK && isEof ){
130585         assert( pCsr->pNode==pRoot );
130586         nodeRelease(pRtree, pRoot);
130587         pCsr->pNode = 0;
130588       }
130589       assert( rc!=SQLCIPHER_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
130590     }
130591   }
130592
130593   rtreeRelease(pRtree);
130594   return rc;
130595 }
130596
130597 /*
130598 ** Rtree virtual table module xBestIndex method. There are three
130599 ** table scan strategies to choose from (in order from most to 
130600 ** least desirable):
130601 **
130602 **   idxNum     idxStr        Strategy
130603 **   ------------------------------------------------
130604 **     1        Unused        Direct lookup by rowid.
130605 **     2        See below     R-tree query or full-table scan.
130606 **   ------------------------------------------------
130607 **
130608 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
130609 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
130610 ** constraint used. The first two bytes of idxStr correspond to 
130611 ** the constraint in sqlcipher3_index_info.aConstraintUsage[] with
130612 ** (argvIndex==1) etc.
130613 **
130614 ** The first of each pair of bytes in idxStr identifies the constraint
130615 ** operator as follows:
130616 **
130617 **   Operator    Byte Value
130618 **   ----------------------
130619 **      =        0x41 ('A')
130620 **     <=        0x42 ('B')
130621 **      <        0x43 ('C')
130622 **     >=        0x44 ('D')
130623 **      >        0x45 ('E')
130624 **   MATCH       0x46 ('F')
130625 **   ----------------------
130626 **
130627 ** The second of each pair of bytes identifies the coordinate column
130628 ** to which the constraint applies. The leftmost coordinate column
130629 ** is 'a', the second from the left 'b' etc.
130630 */
130631 static int rtreeBestIndex(sqlcipher3_vtab *tab, sqlcipher3_index_info *pIdxInfo){
130632   int rc = SQLCIPHER_OK;
130633   int ii;
130634
130635   int iIdx = 0;
130636   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
130637   memset(zIdxStr, 0, sizeof(zIdxStr));
130638   UNUSED_PARAMETER(tab);
130639
130640   assert( pIdxInfo->idxStr==0 );
130641   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
130642     struct sqlcipher3_index_constraint *p = &pIdxInfo->aConstraint[ii];
130643
130644     if( p->usable && p->iColumn==0 && p->op==SQLCIPHER_INDEX_CONSTRAINT_EQ ){
130645       /* We have an equality constraint on the rowid. Use strategy 1. */
130646       int jj;
130647       for(jj=0; jj<ii; jj++){
130648         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
130649         pIdxInfo->aConstraintUsage[jj].omit = 0;
130650       }
130651       pIdxInfo->idxNum = 1;
130652       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
130653       pIdxInfo->aConstraintUsage[jj].omit = 1;
130654
130655       /* This strategy involves a two rowid lookups on an B-Tree structures
130656       ** and then a linear search of an R-Tree node. This should be 
130657       ** considered almost as quick as a direct rowid lookup (for which 
130658       ** sqlcipher uses an internal cost of 0.0).
130659       */ 
130660       pIdxInfo->estimatedCost = 10.0;
130661       return SQLCIPHER_OK;
130662     }
130663
130664     if( p->usable && (p->iColumn>0 || p->op==SQLCIPHER_INDEX_CONSTRAINT_MATCH) ){
130665       u8 op;
130666       switch( p->op ){
130667         case SQLCIPHER_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
130668         case SQLCIPHER_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
130669         case SQLCIPHER_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
130670         case SQLCIPHER_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
130671         case SQLCIPHER_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
130672         default:
130673           assert( p->op==SQLCIPHER_INDEX_CONSTRAINT_MATCH );
130674           op = RTREE_MATCH; 
130675           break;
130676       }
130677       zIdxStr[iIdx++] = op;
130678       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
130679       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
130680       pIdxInfo->aConstraintUsage[ii].omit = 1;
130681     }
130682   }
130683
130684   pIdxInfo->idxNum = 2;
130685   pIdxInfo->needToFreeIdxStr = 1;
130686   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlcipher3_mprintf("%s", zIdxStr)) ){
130687     return SQLCIPHER_NOMEM;
130688   }
130689   assert( iIdx>=0 );
130690   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
130691   return rc;
130692 }
130693
130694 /*
130695 ** Return the N-dimensional volumn of the cell stored in *p.
130696 */
130697 static float cellArea(Rtree *pRtree, RtreeCell *p){
130698   float area = 1.0;
130699   int ii;
130700   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
130701     area = (float)(area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
130702   }
130703   return area;
130704 }
130705
130706 /*
130707 ** Return the margin length of cell p. The margin length is the sum
130708 ** of the objects size in each dimension.
130709 */
130710 static float cellMargin(Rtree *pRtree, RtreeCell *p){
130711   float margin = 0.0;
130712   int ii;
130713   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
130714     margin += (float)(DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
130715   }
130716   return margin;
130717 }
130718
130719 /*
130720 ** Store the union of cells p1 and p2 in p1.
130721 */
130722 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
130723   int ii;
130724   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
130725     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
130726       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
130727       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
130728     }
130729   }else{
130730     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
130731       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
130732       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
130733     }
130734   }
130735 }
130736
130737 /*
130738 ** Return true if the area covered by p2 is a subset of the area covered
130739 ** by p1. False otherwise.
130740 */
130741 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
130742   int ii;
130743   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
130744   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
130745     RtreeCoord *a1 = &p1->aCoord[ii];
130746     RtreeCoord *a2 = &p2->aCoord[ii];
130747     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
130748      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
130749     ){
130750       return 0;
130751     }
130752   }
130753   return 1;
130754 }
130755
130756 /*
130757 ** Return the amount cell p would grow by if it were unioned with pCell.
130758 */
130759 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
130760   float area;
130761   RtreeCell cell;
130762   memcpy(&cell, p, sizeof(RtreeCell));
130763   area = cellArea(pRtree, &cell);
130764   cellUnion(pRtree, &cell, pCell);
130765   return (cellArea(pRtree, &cell)-area);
130766 }
130767
130768 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
130769 static float cellOverlap(
130770   Rtree *pRtree, 
130771   RtreeCell *p, 
130772   RtreeCell *aCell, 
130773   int nCell, 
130774   int iExclude
130775 ){
130776   int ii;
130777   float overlap = 0.0;
130778   for(ii=0; ii<nCell; ii++){
130779 #if VARIANT_RSTARTREE_CHOOSESUBTREE
130780     if( ii!=iExclude )
130781 #else
130782     assert( iExclude==-1 );
130783     UNUSED_PARAMETER(iExclude);
130784 #endif
130785     {
130786       int jj;
130787       float o = 1.0;
130788       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
130789         double x1;
130790         double x2;
130791
130792         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
130793         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
130794
130795         if( x2<x1 ){
130796           o = 0.0;
130797           break;
130798         }else{
130799           o = o * (float)(x2-x1);
130800         }
130801       }
130802       overlap += o;
130803     }
130804   }
130805   return overlap;
130806 }
130807 #endif
130808
130809 #if VARIANT_RSTARTREE_CHOOSESUBTREE
130810 static float cellOverlapEnlargement(
130811   Rtree *pRtree, 
130812   RtreeCell *p, 
130813   RtreeCell *pInsert, 
130814   RtreeCell *aCell, 
130815   int nCell, 
130816   int iExclude
130817 ){
130818   double before;
130819   double after;
130820   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
130821   cellUnion(pRtree, p, pInsert);
130822   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
130823   return (float)(after-before);
130824 }
130825 #endif
130826
130827
130828 /*
130829 ** This function implements the ChooseLeaf algorithm from Gutman[84].
130830 ** ChooseSubTree in r*tree terminology.
130831 */
130832 static int ChooseLeaf(
130833   Rtree *pRtree,               /* Rtree table */
130834   RtreeCell *pCell,            /* Cell to insert into rtree */
130835   int iHeight,                 /* Height of sub-tree rooted at pCell */
130836   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
130837 ){
130838   int rc;
130839   int ii;
130840   RtreeNode *pNode;
130841   rc = nodeAcquire(pRtree, 1, 0, &pNode);
130842
130843   for(ii=0; rc==SQLCIPHER_OK && ii<(pRtree->iDepth-iHeight); ii++){
130844     int iCell;
130845     sqlcipher3_int64 iBest = 0;
130846
130847     float fMinGrowth = 0.0;
130848     float fMinArea = 0.0;
130849 #if VARIANT_RSTARTREE_CHOOSESUBTREE
130850     float fMinOverlap = 0.0;
130851     float overlap;
130852 #endif
130853
130854     int nCell = NCELL(pNode);
130855     RtreeCell cell;
130856     RtreeNode *pChild;
130857
130858     RtreeCell *aCell = 0;
130859
130860 #if VARIANT_RSTARTREE_CHOOSESUBTREE
130861     if( ii==(pRtree->iDepth-1) ){
130862       int jj;
130863       aCell = sqlcipher3_malloc(sizeof(RtreeCell)*nCell);
130864       if( !aCell ){
130865         rc = SQLCIPHER_NOMEM;
130866         nodeRelease(pRtree, pNode);
130867         pNode = 0;
130868         continue;
130869       }
130870       for(jj=0; jj<nCell; jj++){
130871         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
130872       }
130873     }
130874 #endif
130875
130876     /* Select the child node which will be enlarged the least if pCell
130877     ** is inserted into it. Resolve ties by choosing the entry with
130878     ** the smallest area.
130879     */
130880     for(iCell=0; iCell<nCell; iCell++){
130881       int bBest = 0;
130882       float growth;
130883       float area;
130884       nodeGetCell(pRtree, pNode, iCell, &cell);
130885       growth = cellGrowth(pRtree, &cell, pCell);
130886       area = cellArea(pRtree, &cell);
130887
130888 #if VARIANT_RSTARTREE_CHOOSESUBTREE
130889       if( ii==(pRtree->iDepth-1) ){
130890         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
130891       }else{
130892         overlap = 0.0;
130893       }
130894       if( (iCell==0) 
130895        || (overlap<fMinOverlap) 
130896        || (overlap==fMinOverlap && growth<fMinGrowth)
130897        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
130898       ){
130899         bBest = 1;
130900         fMinOverlap = overlap;
130901       }
130902 #else
130903       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
130904         bBest = 1;
130905       }
130906 #endif
130907       if( bBest ){
130908         fMinGrowth = growth;
130909         fMinArea = area;
130910         iBest = cell.iRowid;
130911       }
130912     }
130913
130914     sqlcipher3_free(aCell);
130915     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
130916     nodeRelease(pRtree, pNode);
130917     pNode = pChild;
130918   }
130919
130920   *ppLeaf = pNode;
130921   return rc;
130922 }
130923
130924 /*
130925 ** A cell with the same content as pCell has just been inserted into
130926 ** the node pNode. This function updates the bounding box cells in
130927 ** all ancestor elements.
130928 */
130929 static int AdjustTree(
130930   Rtree *pRtree,                    /* Rtree table */
130931   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
130932   RtreeCell *pCell                  /* This cell was just inserted */
130933 ){
130934   RtreeNode *p = pNode;
130935   while( p->pParent ){
130936     RtreeNode *pParent = p->pParent;
130937     RtreeCell cell;
130938     int iCell;
130939
130940     if( nodeParentIndex(pRtree, p, &iCell) ){
130941       return SQLCIPHER_CORRUPT_VTAB;
130942     }
130943
130944     nodeGetCell(pRtree, pParent, iCell, &cell);
130945     if( !cellContains(pRtree, &cell, pCell) ){
130946       cellUnion(pRtree, &cell, pCell);
130947       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
130948     }
130949  
130950     p = pParent;
130951   }
130952   return SQLCIPHER_OK;
130953 }
130954
130955 /*
130956 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
130957 */
130958 static int rowidWrite(Rtree *pRtree, sqlcipher3_int64 iRowid, sqlcipher3_int64 iNode){
130959   sqlcipher3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
130960   sqlcipher3_bind_int64(pRtree->pWriteRowid, 2, iNode);
130961   sqlcipher3_step(pRtree->pWriteRowid);
130962   return sqlcipher3_reset(pRtree->pWriteRowid);
130963 }
130964
130965 /*
130966 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
130967 */
130968 static int parentWrite(Rtree *pRtree, sqlcipher3_int64 iNode, sqlcipher3_int64 iPar){
130969   sqlcipher3_bind_int64(pRtree->pWriteParent, 1, iNode);
130970   sqlcipher3_bind_int64(pRtree->pWriteParent, 2, iPar);
130971   sqlcipher3_step(pRtree->pWriteParent);
130972   return sqlcipher3_reset(pRtree->pWriteParent);
130973 }
130974
130975 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
130976
130977 #if VARIANT_GUTTMAN_LINEAR_SPLIT
130978 /*
130979 ** Implementation of the linear variant of the PickNext() function from
130980 ** Guttman[84].
130981 */
130982 static RtreeCell *LinearPickNext(
130983   Rtree *pRtree,
130984   RtreeCell *aCell, 
130985   int nCell, 
130986   RtreeCell *pLeftBox, 
130987   RtreeCell *pRightBox,
130988   int *aiUsed
130989 ){
130990   int ii;
130991   for(ii=0; aiUsed[ii]; ii++);
130992   aiUsed[ii] = 1;
130993   return &aCell[ii];
130994 }
130995
130996 /*
130997 ** Implementation of the linear variant of the PickSeeds() function from
130998 ** Guttman[84].
130999 */
131000 static void LinearPickSeeds(
131001   Rtree *pRtree,
131002   RtreeCell *aCell, 
131003   int nCell, 
131004   int *piLeftSeed, 
131005   int *piRightSeed
131006 ){
131007   int i;
131008   int iLeftSeed = 0;
131009   int iRightSeed = 1;
131010   float maxNormalInnerWidth = 0.0;
131011
131012   /* Pick two "seed" cells from the array of cells. The algorithm used
131013   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
131014   ** indices of the two seed cells in the array are stored in local
131015   ** variables iLeftSeek and iRightSeed.
131016   */
131017   for(i=0; i<pRtree->nDim; i++){
131018     float x1 = DCOORD(aCell[0].aCoord[i*2]);
131019     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
131020     float x3 = x1;
131021     float x4 = x2;
131022     int jj;
131023
131024     int iCellLeft = 0;
131025     int iCellRight = 0;
131026
131027     for(jj=1; jj<nCell; jj++){
131028       float left = DCOORD(aCell[jj].aCoord[i*2]);
131029       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
131030
131031       if( left<x1 ) x1 = left;
131032       if( right>x4 ) x4 = right;
131033       if( left>x3 ){
131034         x3 = left;
131035         iCellRight = jj;
131036       }
131037       if( right<x2 ){
131038         x2 = right;
131039         iCellLeft = jj;
131040       }
131041     }
131042
131043     if( x4!=x1 ){
131044       float normalwidth = (x3 - x2) / (x4 - x1);
131045       if( normalwidth>maxNormalInnerWidth ){
131046         iLeftSeed = iCellLeft;
131047         iRightSeed = iCellRight;
131048       }
131049     }
131050   }
131051
131052   *piLeftSeed = iLeftSeed;
131053   *piRightSeed = iRightSeed;
131054 }
131055 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
131056
131057 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
131058 /*
131059 ** Implementation of the quadratic variant of the PickNext() function from
131060 ** Guttman[84].
131061 */
131062 static RtreeCell *QuadraticPickNext(
131063   Rtree *pRtree,
131064   RtreeCell *aCell, 
131065   int nCell, 
131066   RtreeCell *pLeftBox, 
131067   RtreeCell *pRightBox,
131068   int *aiUsed
131069 ){
131070   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
131071
131072   int iSelect = -1;
131073   float fDiff;
131074   int ii;
131075   for(ii=0; ii<nCell; ii++){
131076     if( aiUsed[ii]==0 ){
131077       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
131078       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
131079       float diff = FABS(right-left);
131080       if( iSelect<0 || diff>fDiff ){
131081         fDiff = diff;
131082         iSelect = ii;
131083       }
131084     }
131085   }
131086   aiUsed[iSelect] = 1;
131087   return &aCell[iSelect];
131088 }
131089
131090 /*
131091 ** Implementation of the quadratic variant of the PickSeeds() function from
131092 ** Guttman[84].
131093 */
131094 static void QuadraticPickSeeds(
131095   Rtree *pRtree,
131096   RtreeCell *aCell, 
131097   int nCell, 
131098   int *piLeftSeed, 
131099   int *piRightSeed
131100 ){
131101   int ii;
131102   int jj;
131103
131104   int iLeftSeed = 0;
131105   int iRightSeed = 1;
131106   float fWaste = 0.0;
131107
131108   for(ii=0; ii<nCell; ii++){
131109     for(jj=ii+1; jj<nCell; jj++){
131110       float right = cellArea(pRtree, &aCell[jj]);
131111       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
131112       float waste = growth - right;
131113
131114       if( waste>fWaste ){
131115         iLeftSeed = ii;
131116         iRightSeed = jj;
131117         fWaste = waste;
131118       }
131119     }
131120   }
131121
131122   *piLeftSeed = iLeftSeed;
131123   *piRightSeed = iRightSeed;
131124 }
131125 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
131126
131127 /*
131128 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
131129 ** nIdx. The aIdx array contains the set of integers from 0 to 
131130 ** (nIdx-1) in no particular order. This function sorts the values
131131 ** in aIdx according to the indexed values in aDistance. For
131132 ** example, assuming the inputs:
131133 **
131134 **   aIdx      = { 0,   1,   2,   3 }
131135 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
131136 **
131137 ** this function sets the aIdx array to contain:
131138 **
131139 **   aIdx      = { 0,   1,   2,   3 }
131140 **
131141 ** The aSpare array is used as temporary working space by the
131142 ** sorting algorithm.
131143 */
131144 static void SortByDistance(
131145   int *aIdx, 
131146   int nIdx, 
131147   float *aDistance, 
131148   int *aSpare
131149 ){
131150   if( nIdx>1 ){
131151     int iLeft = 0;
131152     int iRight = 0;
131153
131154     int nLeft = nIdx/2;
131155     int nRight = nIdx-nLeft;
131156     int *aLeft = aIdx;
131157     int *aRight = &aIdx[nLeft];
131158
131159     SortByDistance(aLeft, nLeft, aDistance, aSpare);
131160     SortByDistance(aRight, nRight, aDistance, aSpare);
131161
131162     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
131163     aLeft = aSpare;
131164
131165     while( iLeft<nLeft || iRight<nRight ){
131166       if( iLeft==nLeft ){
131167         aIdx[iLeft+iRight] = aRight[iRight];
131168         iRight++;
131169       }else if( iRight==nRight ){
131170         aIdx[iLeft+iRight] = aLeft[iLeft];
131171         iLeft++;
131172       }else{
131173         float fLeft = aDistance[aLeft[iLeft]];
131174         float fRight = aDistance[aRight[iRight]];
131175         if( fLeft<fRight ){
131176           aIdx[iLeft+iRight] = aLeft[iLeft];
131177           iLeft++;
131178         }else{
131179           aIdx[iLeft+iRight] = aRight[iRight];
131180           iRight++;
131181         }
131182       }
131183     }
131184
131185 #if 0
131186     /* Check that the sort worked */
131187     {
131188       int jj;
131189       for(jj=1; jj<nIdx; jj++){
131190         float left = aDistance[aIdx[jj-1]];
131191         float right = aDistance[aIdx[jj]];
131192         assert( left<=right );
131193       }
131194     }
131195 #endif
131196   }
131197 }
131198
131199 /*
131200 ** Arguments aIdx, aCell and aSpare all point to arrays of size
131201 ** nIdx. The aIdx array contains the set of integers from 0 to 
131202 ** (nIdx-1) in no particular order. This function sorts the values
131203 ** in aIdx according to dimension iDim of the cells in aCell. The
131204 ** minimum value of dimension iDim is considered first, the
131205 ** maximum used to break ties.
131206 **
131207 ** The aSpare array is used as temporary working space by the
131208 ** sorting algorithm.
131209 */
131210 static void SortByDimension(
131211   Rtree *pRtree,
131212   int *aIdx, 
131213   int nIdx, 
131214   int iDim, 
131215   RtreeCell *aCell, 
131216   int *aSpare
131217 ){
131218   if( nIdx>1 ){
131219
131220     int iLeft = 0;
131221     int iRight = 0;
131222
131223     int nLeft = nIdx/2;
131224     int nRight = nIdx-nLeft;
131225     int *aLeft = aIdx;
131226     int *aRight = &aIdx[nLeft];
131227
131228     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
131229     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
131230
131231     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
131232     aLeft = aSpare;
131233     while( iLeft<nLeft || iRight<nRight ){
131234       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
131235       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
131236       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
131237       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
131238       if( (iLeft!=nLeft) && ((iRight==nRight)
131239        || (xleft1<xright1)
131240        || (xleft1==xright1 && xleft2<xright2)
131241       )){
131242         aIdx[iLeft+iRight] = aLeft[iLeft];
131243         iLeft++;
131244       }else{
131245         aIdx[iLeft+iRight] = aRight[iRight];
131246         iRight++;
131247       }
131248     }
131249
131250 #if 0
131251     /* Check that the sort worked */
131252     {
131253       int jj;
131254       for(jj=1; jj<nIdx; jj++){
131255         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
131256         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
131257         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
131258         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
131259         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
131260       }
131261     }
131262 #endif
131263   }
131264 }
131265
131266 #if VARIANT_RSTARTREE_SPLIT
131267 /*
131268 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
131269 */
131270 static int splitNodeStartree(
131271   Rtree *pRtree,
131272   RtreeCell *aCell,
131273   int nCell,
131274   RtreeNode *pLeft,
131275   RtreeNode *pRight,
131276   RtreeCell *pBboxLeft,
131277   RtreeCell *pBboxRight
131278 ){
131279   int **aaSorted;
131280   int *aSpare;
131281   int ii;
131282
131283   int iBestDim = 0;
131284   int iBestSplit = 0;
131285   float fBestMargin = 0.0;
131286
131287   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
131288
131289   aaSorted = (int **)sqlcipher3_malloc(nByte);
131290   if( !aaSorted ){
131291     return SQLCIPHER_NOMEM;
131292   }
131293
131294   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
131295   memset(aaSorted, 0, nByte);
131296   for(ii=0; ii<pRtree->nDim; ii++){
131297     int jj;
131298     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
131299     for(jj=0; jj<nCell; jj++){
131300       aaSorted[ii][jj] = jj;
131301     }
131302     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
131303   }
131304
131305   for(ii=0; ii<pRtree->nDim; ii++){
131306     float margin = 0.0;
131307     float fBestOverlap = 0.0;
131308     float fBestArea = 0.0;
131309     int iBestLeft = 0;
131310     int nLeft;
131311
131312     for(
131313       nLeft=RTREE_MINCELLS(pRtree); 
131314       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
131315       nLeft++
131316     ){
131317       RtreeCell left;
131318       RtreeCell right;
131319       int kk;
131320       float overlap;
131321       float area;
131322
131323       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
131324       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
131325       for(kk=1; kk<(nCell-1); kk++){
131326         if( kk<nLeft ){
131327           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
131328         }else{
131329           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
131330         }
131331       }
131332       margin += cellMargin(pRtree, &left);
131333       margin += cellMargin(pRtree, &right);
131334       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
131335       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
131336       if( (nLeft==RTREE_MINCELLS(pRtree))
131337        || (overlap<fBestOverlap)
131338        || (overlap==fBestOverlap && area<fBestArea)
131339       ){
131340         iBestLeft = nLeft;
131341         fBestOverlap = overlap;
131342         fBestArea = area;
131343       }
131344     }
131345
131346     if( ii==0 || margin<fBestMargin ){
131347       iBestDim = ii;
131348       fBestMargin = margin;
131349       iBestSplit = iBestLeft;
131350     }
131351   }
131352
131353   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
131354   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
131355   for(ii=0; ii<nCell; ii++){
131356     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
131357     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
131358     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
131359     nodeInsertCell(pRtree, pTarget, pCell);
131360     cellUnion(pRtree, pBbox, pCell);
131361   }
131362
131363   sqlcipher3_free(aaSorted);
131364   return SQLCIPHER_OK;
131365 }
131366 #endif
131367
131368 #if VARIANT_GUTTMAN_SPLIT
131369 /*
131370 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
131371 */
131372 static int splitNodeGuttman(
131373   Rtree *pRtree,
131374   RtreeCell *aCell,
131375   int nCell,
131376   RtreeNode *pLeft,
131377   RtreeNode *pRight,
131378   RtreeCell *pBboxLeft,
131379   RtreeCell *pBboxRight
131380 ){
131381   int iLeftSeed = 0;
131382   int iRightSeed = 1;
131383   int *aiUsed;
131384   int i;
131385
131386   aiUsed = sqlcipher3_malloc(sizeof(int)*nCell);
131387   if( !aiUsed ){
131388     return SQLCIPHER_NOMEM;
131389   }
131390   memset(aiUsed, 0, sizeof(int)*nCell);
131391
131392   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
131393
131394   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
131395   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
131396   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
131397   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
131398   aiUsed[iLeftSeed] = 1;
131399   aiUsed[iRightSeed] = 1;
131400
131401   for(i=nCell-2; i>0; i--){
131402     RtreeCell *pNext;
131403     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
131404     float diff =  
131405       cellGrowth(pRtree, pBboxLeft, pNext) - 
131406       cellGrowth(pRtree, pBboxRight, pNext)
131407     ;
131408     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
131409      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
131410     ){
131411       nodeInsertCell(pRtree, pRight, pNext);
131412       cellUnion(pRtree, pBboxRight, pNext);
131413     }else{
131414       nodeInsertCell(pRtree, pLeft, pNext);
131415       cellUnion(pRtree, pBboxLeft, pNext);
131416     }
131417   }
131418
131419   sqlcipher3_free(aiUsed);
131420   return SQLCIPHER_OK;
131421 }
131422 #endif
131423
131424 static int updateMapping(
131425   Rtree *pRtree, 
131426   i64 iRowid, 
131427   RtreeNode *pNode, 
131428   int iHeight
131429 ){
131430   int (*xSetMapping)(Rtree *, sqlcipher3_int64, sqlcipher3_int64);
131431   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
131432   if( iHeight>0 ){
131433     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
131434     if( pChild ){
131435       nodeRelease(pRtree, pChild->pParent);
131436       nodeReference(pNode);
131437       pChild->pParent = pNode;
131438     }
131439   }
131440   return xSetMapping(pRtree, iRowid, pNode->iNode);
131441 }
131442
131443 static int SplitNode(
131444   Rtree *pRtree,
131445   RtreeNode *pNode,
131446   RtreeCell *pCell,
131447   int iHeight
131448 ){
131449   int i;
131450   int newCellIsRight = 0;
131451
131452   int rc = SQLCIPHER_OK;
131453   int nCell = NCELL(pNode);
131454   RtreeCell *aCell;
131455   int *aiUsed;
131456
131457   RtreeNode *pLeft = 0;
131458   RtreeNode *pRight = 0;
131459
131460   RtreeCell leftbbox;
131461   RtreeCell rightbbox;
131462
131463   /* Allocate an array and populate it with a copy of pCell and 
131464   ** all cells from node pLeft. Then zero the original node.
131465   */
131466   aCell = sqlcipher3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
131467   if( !aCell ){
131468     rc = SQLCIPHER_NOMEM;
131469     goto splitnode_out;
131470   }
131471   aiUsed = (int *)&aCell[nCell+1];
131472   memset(aiUsed, 0, sizeof(int)*(nCell+1));
131473   for(i=0; i<nCell; i++){
131474     nodeGetCell(pRtree, pNode, i, &aCell[i]);
131475   }
131476   nodeZero(pRtree, pNode);
131477   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
131478   nCell++;
131479
131480   if( pNode->iNode==1 ){
131481     pRight = nodeNew(pRtree, pNode);
131482     pLeft = nodeNew(pRtree, pNode);
131483     pRtree->iDepth++;
131484     pNode->isDirty = 1;
131485     writeInt16(pNode->zData, pRtree->iDepth);
131486   }else{
131487     pLeft = pNode;
131488     pRight = nodeNew(pRtree, pLeft->pParent);
131489     nodeReference(pLeft);
131490   }
131491
131492   if( !pLeft || !pRight ){
131493     rc = SQLCIPHER_NOMEM;
131494     goto splitnode_out;
131495   }
131496
131497   memset(pLeft->zData, 0, pRtree->iNodeSize);
131498   memset(pRight->zData, 0, pRtree->iNodeSize);
131499
131500   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
131501   if( rc!=SQLCIPHER_OK ){
131502     goto splitnode_out;
131503   }
131504
131505   /* Ensure both child nodes have node numbers assigned to them by calling
131506   ** nodeWrite(). Node pRight always needs a node number, as it was created
131507   ** by nodeNew() above. But node pLeft sometimes already has a node number.
131508   ** In this case avoid the all to nodeWrite().
131509   */
131510   if( SQLCIPHER_OK!=(rc = nodeWrite(pRtree, pRight))
131511    || (0==pLeft->iNode && SQLCIPHER_OK!=(rc = nodeWrite(pRtree, pLeft)))
131512   ){
131513     goto splitnode_out;
131514   }
131515
131516   rightbbox.iRowid = pRight->iNode;
131517   leftbbox.iRowid = pLeft->iNode;
131518
131519   if( pNode->iNode==1 ){
131520     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
131521     if( rc!=SQLCIPHER_OK ){
131522       goto splitnode_out;
131523     }
131524   }else{
131525     RtreeNode *pParent = pLeft->pParent;
131526     int iCell;
131527     rc = nodeParentIndex(pRtree, pLeft, &iCell);
131528     if( rc==SQLCIPHER_OK ){
131529       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
131530       rc = AdjustTree(pRtree, pParent, &leftbbox);
131531     }
131532     if( rc!=SQLCIPHER_OK ){
131533       goto splitnode_out;
131534     }
131535   }
131536   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
131537     goto splitnode_out;
131538   }
131539
131540   for(i=0; i<NCELL(pRight); i++){
131541     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
131542     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
131543     if( iRowid==pCell->iRowid ){
131544       newCellIsRight = 1;
131545     }
131546     if( rc!=SQLCIPHER_OK ){
131547       goto splitnode_out;
131548     }
131549   }
131550   if( pNode->iNode==1 ){
131551     for(i=0; i<NCELL(pLeft); i++){
131552       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
131553       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
131554       if( rc!=SQLCIPHER_OK ){
131555         goto splitnode_out;
131556       }
131557     }
131558   }else if( newCellIsRight==0 ){
131559     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
131560   }
131561
131562   if( rc==SQLCIPHER_OK ){
131563     rc = nodeRelease(pRtree, pRight);
131564     pRight = 0;
131565   }
131566   if( rc==SQLCIPHER_OK ){
131567     rc = nodeRelease(pRtree, pLeft);
131568     pLeft = 0;
131569   }
131570
131571 splitnode_out:
131572   nodeRelease(pRtree, pRight);
131573   nodeRelease(pRtree, pLeft);
131574   sqlcipher3_free(aCell);
131575   return rc;
131576 }
131577
131578 /*
131579 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
131580 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
131581 ** the pLeaf->pParent chain all the way up to the root node.
131582 **
131583 ** This operation is required when a row is deleted (or updated - an update
131584 ** is implemented as a delete followed by an insert). SQLite provides the
131585 ** rowid of the row to delete, which can be used to find the leaf on which
131586 ** the entry resides (argument pLeaf). Once the leaf is located, this 
131587 ** function is called to determine its ancestry.
131588 */
131589 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
131590   int rc = SQLCIPHER_OK;
131591   RtreeNode *pChild = pLeaf;
131592   while( rc==SQLCIPHER_OK && pChild->iNode!=1 && pChild->pParent==0 ){
131593     int rc2 = SQLCIPHER_OK;          /* sqlcipher3_reset() return code */
131594     sqlcipher3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
131595     rc = sqlcipher3_step(pRtree->pReadParent);
131596     if( rc==SQLCIPHER_ROW ){
131597       RtreeNode *pTest;           /* Used to test for reference loops */
131598       i64 iNode;                  /* Node number of parent node */
131599
131600       /* Before setting pChild->pParent, test that we are not creating a
131601       ** loop of references (as we would if, say, pChild==pParent). We don't
131602       ** want to do this as it leads to a memory leak when trying to delete
131603       ** the referenced counted node structures.
131604       */
131605       iNode = sqlcipher3_column_int64(pRtree->pReadParent, 0);
131606       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
131607       if( !pTest ){
131608         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
131609       }
131610     }
131611     rc = sqlcipher3_reset(pRtree->pReadParent);
131612     if( rc==SQLCIPHER_OK ) rc = rc2;
131613     if( rc==SQLCIPHER_OK && !pChild->pParent ) rc = SQLCIPHER_CORRUPT_VTAB;
131614     pChild = pChild->pParent;
131615   }
131616   return rc;
131617 }
131618
131619 static int deleteCell(Rtree *, RtreeNode *, int, int);
131620
131621 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
131622   int rc;
131623   int rc2;
131624   RtreeNode *pParent = 0;
131625   int iCell;
131626
131627   assert( pNode->nRef==1 );
131628
131629   /* Remove the entry in the parent cell. */
131630   rc = nodeParentIndex(pRtree, pNode, &iCell);
131631   if( rc==SQLCIPHER_OK ){
131632     pParent = pNode->pParent;
131633     pNode->pParent = 0;
131634     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
131635   }
131636   rc2 = nodeRelease(pRtree, pParent);
131637   if( rc==SQLCIPHER_OK ){
131638     rc = rc2;
131639   }
131640   if( rc!=SQLCIPHER_OK ){
131641     return rc;
131642   }
131643
131644   /* Remove the xxx_node entry. */
131645   sqlcipher3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
131646   sqlcipher3_step(pRtree->pDeleteNode);
131647   if( SQLCIPHER_OK!=(rc = sqlcipher3_reset(pRtree->pDeleteNode)) ){
131648     return rc;
131649   }
131650
131651   /* Remove the xxx_parent entry. */
131652   sqlcipher3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
131653   sqlcipher3_step(pRtree->pDeleteParent);
131654   if( SQLCIPHER_OK!=(rc = sqlcipher3_reset(pRtree->pDeleteParent)) ){
131655     return rc;
131656   }
131657   
131658   /* Remove the node from the in-memory hash table and link it into
131659   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
131660   */
131661   nodeHashDelete(pRtree, pNode);
131662   pNode->iNode = iHeight;
131663   pNode->pNext = pRtree->pDeleted;
131664   pNode->nRef++;
131665   pRtree->pDeleted = pNode;
131666
131667   return SQLCIPHER_OK;
131668 }
131669
131670 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
131671   RtreeNode *pParent = pNode->pParent;
131672   int rc = SQLCIPHER_OK; 
131673   if( pParent ){
131674     int ii; 
131675     int nCell = NCELL(pNode);
131676     RtreeCell box;                            /* Bounding box for pNode */
131677     nodeGetCell(pRtree, pNode, 0, &box);
131678     for(ii=1; ii<nCell; ii++){
131679       RtreeCell cell;
131680       nodeGetCell(pRtree, pNode, ii, &cell);
131681       cellUnion(pRtree, &box, &cell);
131682     }
131683     box.iRowid = pNode->iNode;
131684     rc = nodeParentIndex(pRtree, pNode, &ii);
131685     if( rc==SQLCIPHER_OK ){
131686       nodeOverwriteCell(pRtree, pParent, &box, ii);
131687       rc = fixBoundingBox(pRtree, pParent);
131688     }
131689   }
131690   return rc;
131691 }
131692
131693 /*
131694 ** Delete the cell at index iCell of node pNode. After removing the
131695 ** cell, adjust the r-tree data structure if required.
131696 */
131697 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
131698   RtreeNode *pParent;
131699   int rc;
131700
131701   if( SQLCIPHER_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
131702     return rc;
131703   }
131704
131705   /* Remove the cell from the node. This call just moves bytes around
131706   ** the in-memory node image, so it cannot fail.
131707   */
131708   nodeDeleteCell(pRtree, pNode, iCell);
131709
131710   /* If the node is not the tree root and now has less than the minimum
131711   ** number of cells, remove it from the tree. Otherwise, update the
131712   ** cell in the parent node so that it tightly contains the updated
131713   ** node.
131714   */
131715   pParent = pNode->pParent;
131716   assert( pParent || pNode->iNode==1 );
131717   if( pParent ){
131718     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
131719       rc = removeNode(pRtree, pNode, iHeight);
131720     }else{
131721       rc = fixBoundingBox(pRtree, pNode);
131722     }
131723   }
131724
131725   return rc;
131726 }
131727
131728 static int Reinsert(
131729   Rtree *pRtree, 
131730   RtreeNode *pNode, 
131731   RtreeCell *pCell, 
131732   int iHeight
131733 ){
131734   int *aOrder;
131735   int *aSpare;
131736   RtreeCell *aCell;
131737   float *aDistance;
131738   int nCell;
131739   float aCenterCoord[RTREE_MAX_DIMENSIONS];
131740   int iDim;
131741   int ii;
131742   int rc = SQLCIPHER_OK;
131743
131744   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
131745
131746   nCell = NCELL(pNode)+1;
131747
131748   /* Allocate the buffers used by this operation. The allocation is
131749   ** relinquished before this function returns.
131750   */
131751   aCell = (RtreeCell *)sqlcipher3_malloc(nCell * (
131752     sizeof(RtreeCell) +         /* aCell array */
131753     sizeof(int)       +         /* aOrder array */
131754     sizeof(int)       +         /* aSpare array */
131755     sizeof(float)               /* aDistance array */
131756   ));
131757   if( !aCell ){
131758     return SQLCIPHER_NOMEM;
131759   }
131760   aOrder    = (int *)&aCell[nCell];
131761   aSpare    = (int *)&aOrder[nCell];
131762   aDistance = (float *)&aSpare[nCell];
131763
131764   for(ii=0; ii<nCell; ii++){
131765     if( ii==(nCell-1) ){
131766       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
131767     }else{
131768       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
131769     }
131770     aOrder[ii] = ii;
131771     for(iDim=0; iDim<pRtree->nDim; iDim++){
131772       aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2]);
131773       aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2+1]);
131774     }
131775   }
131776   for(iDim=0; iDim<pRtree->nDim; iDim++){
131777     aCenterCoord[iDim] = (float)(aCenterCoord[iDim]/((float)nCell*2.0));
131778   }
131779
131780   for(ii=0; ii<nCell; ii++){
131781     aDistance[ii] = 0.0;
131782     for(iDim=0; iDim<pRtree->nDim; iDim++){
131783       float coord = (float)(DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
131784           DCOORD(aCell[ii].aCoord[iDim*2]));
131785       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
131786     }
131787   }
131788
131789   SortByDistance(aOrder, nCell, aDistance, aSpare);
131790   nodeZero(pRtree, pNode);
131791
131792   for(ii=0; rc==SQLCIPHER_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
131793     RtreeCell *p = &aCell[aOrder[ii]];
131794     nodeInsertCell(pRtree, pNode, p);
131795     if( p->iRowid==pCell->iRowid ){
131796       if( iHeight==0 ){
131797         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
131798       }else{
131799         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
131800       }
131801     }
131802   }
131803   if( rc==SQLCIPHER_OK ){
131804     rc = fixBoundingBox(pRtree, pNode);
131805   }
131806   for(; rc==SQLCIPHER_OK && ii<nCell; ii++){
131807     /* Find a node to store this cell in. pNode->iNode currently contains
131808     ** the height of the sub-tree headed by the cell.
131809     */
131810     RtreeNode *pInsert;
131811     RtreeCell *p = &aCell[aOrder[ii]];
131812     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
131813     if( rc==SQLCIPHER_OK ){
131814       int rc2;
131815       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
131816       rc2 = nodeRelease(pRtree, pInsert);
131817       if( rc==SQLCIPHER_OK ){
131818         rc = rc2;
131819       }
131820     }
131821   }
131822
131823   sqlcipher3_free(aCell);
131824   return rc;
131825 }
131826
131827 /*
131828 ** Insert cell pCell into node pNode. Node pNode is the head of a 
131829 ** subtree iHeight high (leaf nodes have iHeight==0).
131830 */
131831 static int rtreeInsertCell(
131832   Rtree *pRtree,
131833   RtreeNode *pNode,
131834   RtreeCell *pCell,
131835   int iHeight
131836 ){
131837   int rc = SQLCIPHER_OK;
131838   if( iHeight>0 ){
131839     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
131840     if( pChild ){
131841       nodeRelease(pRtree, pChild->pParent);
131842       nodeReference(pNode);
131843       pChild->pParent = pNode;
131844     }
131845   }
131846   if( nodeInsertCell(pRtree, pNode, pCell) ){
131847 #if VARIANT_RSTARTREE_REINSERT
131848     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
131849       rc = SplitNode(pRtree, pNode, pCell, iHeight);
131850     }else{
131851       pRtree->iReinsertHeight = iHeight;
131852       rc = Reinsert(pRtree, pNode, pCell, iHeight);
131853     }
131854 #else
131855     rc = SplitNode(pRtree, pNode, pCell, iHeight);
131856 #endif
131857   }else{
131858     rc = AdjustTree(pRtree, pNode, pCell);
131859     if( rc==SQLCIPHER_OK ){
131860       if( iHeight==0 ){
131861         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
131862       }else{
131863         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
131864       }
131865     }
131866   }
131867   return rc;
131868 }
131869
131870 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
131871   int ii;
131872   int rc = SQLCIPHER_OK;
131873   int nCell = NCELL(pNode);
131874
131875   for(ii=0; rc==SQLCIPHER_OK && ii<nCell; ii++){
131876     RtreeNode *pInsert;
131877     RtreeCell cell;
131878     nodeGetCell(pRtree, pNode, ii, &cell);
131879
131880     /* Find a node to store this cell in. pNode->iNode currently contains
131881     ** the height of the sub-tree headed by the cell.
131882     */
131883     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
131884     if( rc==SQLCIPHER_OK ){
131885       int rc2;
131886       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
131887       rc2 = nodeRelease(pRtree, pInsert);
131888       if( rc==SQLCIPHER_OK ){
131889         rc = rc2;
131890       }
131891     }
131892   }
131893   return rc;
131894 }
131895
131896 /*
131897 ** Select a currently unused rowid for a new r-tree record.
131898 */
131899 static int newRowid(Rtree *pRtree, i64 *piRowid){
131900   int rc;
131901   sqlcipher3_bind_null(pRtree->pWriteRowid, 1);
131902   sqlcipher3_bind_null(pRtree->pWriteRowid, 2);
131903   sqlcipher3_step(pRtree->pWriteRowid);
131904   rc = sqlcipher3_reset(pRtree->pWriteRowid);
131905   *piRowid = sqlcipher3_last_insert_rowid(pRtree->db);
131906   return rc;
131907 }
131908
131909 /*
131910 ** Remove the entry with rowid=iDelete from the r-tree structure.
131911 */
131912 static int rtreeDeleteRowid(Rtree *pRtree, sqlcipher3_int64 iDelete){
131913   int rc;                         /* Return code */
131914   RtreeNode *pLeaf;               /* Leaf node containing record iDelete */
131915   int iCell;                      /* Index of iDelete cell in pLeaf */
131916   RtreeNode *pRoot;               /* Root node of rtree structure */
131917
131918
131919   /* Obtain a reference to the root node to initialise Rtree.iDepth */
131920   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
131921
131922   /* Obtain a reference to the leaf node that contains the entry 
131923   ** about to be deleted. 
131924   */
131925   if( rc==SQLCIPHER_OK ){
131926     rc = findLeafNode(pRtree, iDelete, &pLeaf);
131927   }
131928
131929   /* Delete the cell in question from the leaf node. */
131930   if( rc==SQLCIPHER_OK ){
131931     int rc2;
131932     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
131933     if( rc==SQLCIPHER_OK ){
131934       rc = deleteCell(pRtree, pLeaf, iCell, 0);
131935     }
131936     rc2 = nodeRelease(pRtree, pLeaf);
131937     if( rc==SQLCIPHER_OK ){
131938       rc = rc2;
131939     }
131940   }
131941
131942   /* Delete the corresponding entry in the <rtree>_rowid table. */
131943   if( rc==SQLCIPHER_OK ){
131944     sqlcipher3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
131945     sqlcipher3_step(pRtree->pDeleteRowid);
131946     rc = sqlcipher3_reset(pRtree->pDeleteRowid);
131947   }
131948
131949   /* Check if the root node now has exactly one child. If so, remove
131950   ** it, schedule the contents of the child for reinsertion and 
131951   ** reduce the tree height by one.
131952   **
131953   ** This is equivalent to copying the contents of the child into
131954   ** the root node (the operation that Gutman's paper says to perform 
131955   ** in this scenario).
131956   */
131957   if( rc==SQLCIPHER_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
131958     int rc2;
131959     RtreeNode *pChild;
131960     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
131961     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
131962     if( rc==SQLCIPHER_OK ){
131963       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
131964     }
131965     rc2 = nodeRelease(pRtree, pChild);
131966     if( rc==SQLCIPHER_OK ) rc = rc2;
131967     if( rc==SQLCIPHER_OK ){
131968       pRtree->iDepth--;
131969       writeInt16(pRoot->zData, pRtree->iDepth);
131970       pRoot->isDirty = 1;
131971     }
131972   }
131973
131974   /* Re-insert the contents of any underfull nodes removed from the tree. */
131975   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
131976     if( rc==SQLCIPHER_OK ){
131977       rc = reinsertNodeContent(pRtree, pLeaf);
131978     }
131979     pRtree->pDeleted = pLeaf->pNext;
131980     sqlcipher3_free(pLeaf);
131981   }
131982
131983   /* Release the reference to the root node. */
131984   if( rc==SQLCIPHER_OK ){
131985     rc = nodeRelease(pRtree, pRoot);
131986   }else{
131987     nodeRelease(pRtree, pRoot);
131988   }
131989
131990   return rc;
131991 }
131992
131993 /*
131994 ** The xUpdate method for rtree module virtual tables.
131995 */
131996 static int rtreeUpdate(
131997   sqlcipher3_vtab *pVtab, 
131998   int nData, 
131999   sqlcipher3_value **azData, 
132000   sqlcipher_int64 *pRowid
132001 ){
132002   Rtree *pRtree = (Rtree *)pVtab;
132003   int rc = SQLCIPHER_OK;
132004   RtreeCell cell;                 /* New cell to insert if nData>1 */
132005   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
132006
132007   rtreeReference(pRtree);
132008   assert(nData>=1);
132009
132010   /* Constraint handling. A write operation on an r-tree table may return
132011   ** SQLCIPHER_CONSTRAINT for two reasons:
132012   **
132013   **   1. A duplicate rowid value, or
132014   **   2. The supplied data violates the "x2>=x1" constraint.
132015   **
132016   ** In the first case, if the conflict-handling mode is REPLACE, then
132017   ** the conflicting row can be removed before proceeding. In the second
132018   ** case, SQLCIPHER_CONSTRAINT must be returned regardless of the
132019   ** conflict-handling mode specified by the user.
132020   */
132021   if( nData>1 ){
132022     int ii;
132023
132024     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
132025     assert( nData==(pRtree->nDim*2 + 3) );
132026     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
132027       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
132028         cell.aCoord[ii].f = (float)sqlcipher3_value_double(azData[ii+3]);
132029         cell.aCoord[ii+1].f = (float)sqlcipher3_value_double(azData[ii+4]);
132030         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
132031           rc = SQLCIPHER_CONSTRAINT;
132032           goto constraint;
132033         }
132034       }
132035     }else{
132036       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
132037         cell.aCoord[ii].i = sqlcipher3_value_int(azData[ii+3]);
132038         cell.aCoord[ii+1].i = sqlcipher3_value_int(azData[ii+4]);
132039         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
132040           rc = SQLCIPHER_CONSTRAINT;
132041           goto constraint;
132042         }
132043       }
132044     }
132045
132046     /* If a rowid value was supplied, check if it is already present in 
132047     ** the table. If so, the constraint has failed. */
132048     if( sqlcipher3_value_type(azData[2])!=SQLCIPHER_NULL ){
132049       cell.iRowid = sqlcipher3_value_int64(azData[2]);
132050       if( sqlcipher3_value_type(azData[0])==SQLCIPHER_NULL
132051        || sqlcipher3_value_int64(azData[0])!=cell.iRowid
132052       ){
132053         int steprc;
132054         sqlcipher3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
132055         steprc = sqlcipher3_step(pRtree->pReadRowid);
132056         rc = sqlcipher3_reset(pRtree->pReadRowid);
132057         if( SQLCIPHER_ROW==steprc ){
132058           if( sqlcipher3_vtab_on_conflict(pRtree->db)==SQLCIPHER_REPLACE ){
132059             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
132060           }else{
132061             rc = SQLCIPHER_CONSTRAINT;
132062             goto constraint;
132063           }
132064         }
132065       }
132066       bHaveRowid = 1;
132067     }
132068   }
132069
132070   /* If azData[0] is not an SQL NULL value, it is the rowid of a
132071   ** record to delete from the r-tree table. The following block does
132072   ** just that.
132073   */
132074   if( sqlcipher3_value_type(azData[0])!=SQLCIPHER_NULL ){
132075     rc = rtreeDeleteRowid(pRtree, sqlcipher3_value_int64(azData[0]));
132076   }
132077
132078   /* If the azData[] array contains more than one element, elements
132079   ** (azData[2]..azData[argc-1]) contain a new record to insert into
132080   ** the r-tree structure.
132081   */
132082   if( rc==SQLCIPHER_OK && nData>1 ){
132083     /* Insert the new record into the r-tree */
132084     RtreeNode *pLeaf;
132085
132086     /* Figure out the rowid of the new row. */
132087     if( bHaveRowid==0 ){
132088       rc = newRowid(pRtree, &cell.iRowid);
132089     }
132090     *pRowid = cell.iRowid;
132091
132092     if( rc==SQLCIPHER_OK ){
132093       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
132094     }
132095     if( rc==SQLCIPHER_OK ){
132096       int rc2;
132097       pRtree->iReinsertHeight = -1;
132098       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
132099       rc2 = nodeRelease(pRtree, pLeaf);
132100       if( rc==SQLCIPHER_OK ){
132101         rc = rc2;
132102       }
132103     }
132104   }
132105
132106 constraint:
132107   rtreeRelease(pRtree);
132108   return rc;
132109 }
132110
132111 /*
132112 ** The xRename method for rtree module virtual tables.
132113 */
132114 static int rtreeRename(sqlcipher3_vtab *pVtab, const char *zNewName){
132115   Rtree *pRtree = (Rtree *)pVtab;
132116   int rc = SQLCIPHER_NOMEM;
132117   char *zSql = sqlcipher3_mprintf(
132118     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
132119     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
132120     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
132121     , pRtree->zDb, pRtree->zName, zNewName 
132122     , pRtree->zDb, pRtree->zName, zNewName 
132123     , pRtree->zDb, pRtree->zName, zNewName
132124   );
132125   if( zSql ){
132126     rc = sqlcipher3_exec(pRtree->db, zSql, 0, 0, 0);
132127     sqlcipher3_free(zSql);
132128   }
132129   return rc;
132130 }
132131
132132 static sqlcipher3_module rtreeModule = {
132133   0,                          /* iVersion */
132134   rtreeCreate,                /* xCreate - create a table */
132135   rtreeConnect,               /* xConnect - connect to an existing table */
132136   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
132137   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
132138   rtreeDestroy,               /* xDestroy - Drop a table */
132139   rtreeOpen,                  /* xOpen - open a cursor */
132140   rtreeClose,                 /* xClose - close a cursor */
132141   rtreeFilter,                /* xFilter - configure scan constraints */
132142   rtreeNext,                  /* xNext - advance a cursor */
132143   rtreeEof,                   /* xEof */
132144   rtreeColumn,                /* xColumn - read data */
132145   rtreeRowid,                 /* xRowid - read data */
132146   rtreeUpdate,                /* xUpdate - write data */
132147   0,                          /* xBegin - begin transaction */
132148   0,                          /* xSync - sync transaction */
132149   0,                          /* xCommit - commit transaction */
132150   0,                          /* xRollback - rollback transaction */
132151   0,                          /* xFindFunction - function overloading */
132152   rtreeRename,                /* xRename - rename the table */
132153   0,                          /* xSavepoint */
132154   0,                          /* xRelease */
132155   0                           /* xRollbackTo */
132156 };
132157
132158 static int rtreeSqlInit(
132159   Rtree *pRtree, 
132160   sqlcipher3 *db, 
132161   const char *zDb, 
132162   const char *zPrefix, 
132163   int isCreate
132164 ){
132165   int rc = SQLCIPHER_OK;
132166
132167   #define N_STATEMENT 9
132168   static const char *azSql[N_STATEMENT] = {
132169     /* Read and write the xxx_node table */
132170     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
132171     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
132172     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
132173
132174     /* Read and write the xxx_rowid table */
132175     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
132176     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
132177     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
132178
132179     /* Read and write the xxx_parent table */
132180     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
132181     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
132182     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
132183   };
132184   sqlcipher3_stmt **appStmt[N_STATEMENT];
132185   int i;
132186
132187   pRtree->db = db;
132188
132189   if( isCreate ){
132190     char *zCreate = sqlcipher3_mprintf(
132191 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
132192 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
132193 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
132194 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
132195       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
132196     );
132197     if( !zCreate ){
132198       return SQLCIPHER_NOMEM;
132199     }
132200     rc = sqlcipher3_exec(db, zCreate, 0, 0, 0);
132201     sqlcipher3_free(zCreate);
132202     if( rc!=SQLCIPHER_OK ){
132203       return rc;
132204     }
132205   }
132206
132207   appStmt[0] = &pRtree->pReadNode;
132208   appStmt[1] = &pRtree->pWriteNode;
132209   appStmt[2] = &pRtree->pDeleteNode;
132210   appStmt[3] = &pRtree->pReadRowid;
132211   appStmt[4] = &pRtree->pWriteRowid;
132212   appStmt[5] = &pRtree->pDeleteRowid;
132213   appStmt[6] = &pRtree->pReadParent;
132214   appStmt[7] = &pRtree->pWriteParent;
132215   appStmt[8] = &pRtree->pDeleteParent;
132216
132217   for(i=0; i<N_STATEMENT && rc==SQLCIPHER_OK; i++){
132218     char *zSql = sqlcipher3_mprintf(azSql[i], zDb, zPrefix);
132219     if( zSql ){
132220       rc = sqlcipher3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
132221     }else{
132222       rc = SQLCIPHER_NOMEM;
132223     }
132224     sqlcipher3_free(zSql);
132225   }
132226
132227   return rc;
132228 }
132229
132230 /*
132231 ** The second argument to this function contains the text of an SQL statement
132232 ** that returns a single integer value. The statement is compiled and executed
132233 ** using database connection db. If successful, the integer value returned
132234 ** is written to *piVal and SQLCIPHER_OK returned. Otherwise, an SQLite error
132235 ** code is returned and the value of *piVal after returning is not defined.
132236 */
132237 static int getIntFromStmt(sqlcipher3 *db, const char *zSql, int *piVal){
132238   int rc = SQLCIPHER_NOMEM;
132239   if( zSql ){
132240     sqlcipher3_stmt *pStmt = 0;
132241     rc = sqlcipher3_prepare_v2(db, zSql, -1, &pStmt, 0);
132242     if( rc==SQLCIPHER_OK ){
132243       if( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
132244         *piVal = sqlcipher3_column_int(pStmt, 0);
132245       }
132246       rc = sqlcipher3_finalize(pStmt);
132247     }
132248   }
132249   return rc;
132250 }
132251
132252 /*
132253 ** This function is called from within the xConnect() or xCreate() method to
132254 ** determine the node-size used by the rtree table being created or connected
132255 ** to. If successful, pRtree->iNodeSize is populated and SQLCIPHER_OK returned.
132256 ** Otherwise, an SQLite error code is returned.
132257 **
132258 ** If this function is being called as part of an xConnect(), then the rtree
132259 ** table already exists. In this case the node-size is determined by inspecting
132260 ** the root node of the tree.
132261 **
132262 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
132263 ** This ensures that each node is stored on a single database page. If the 
132264 ** database page-size is so large that more than RTREE_MAXCELLS entries 
132265 ** would fit in a single node, use a smaller node-size.
132266 */
132267 static int getNodeSize(
132268   sqlcipher3 *db,                    /* Database handle */
132269   Rtree *pRtree,                  /* Rtree handle */
132270   int isCreate                    /* True for xCreate, false for xConnect */
132271 ){
132272   int rc;
132273   char *zSql;
132274   if( isCreate ){
132275     int iPageSize = 0;
132276     zSql = sqlcipher3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
132277     rc = getIntFromStmt(db, zSql, &iPageSize);
132278     if( rc==SQLCIPHER_OK ){
132279       pRtree->iNodeSize = iPageSize-64;
132280       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
132281         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
132282       }
132283     }
132284   }else{
132285     zSql = sqlcipher3_mprintf(
132286         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
132287         pRtree->zDb, pRtree->zName
132288     );
132289     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
132290   }
132291
132292   sqlcipher3_free(zSql);
132293   return rc;
132294 }
132295
132296 /* 
132297 ** This function is the implementation of both the xConnect and xCreate
132298 ** methods of the r-tree virtual table.
132299 **
132300 **   argv[0]   -> module name
132301 **   argv[1]   -> database name
132302 **   argv[2]   -> table name
132303 **   argv[...] -> column names...
132304 */
132305 static int rtreeInit(
132306   sqlcipher3 *db,                        /* Database connection */
132307   void *pAux,                         /* One of the RTREE_COORD_* constants */
132308   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
132309   sqlcipher3_vtab **ppVtab,              /* OUT: New virtual table */
132310   char **pzErr,                       /* OUT: Error message, if any */
132311   int isCreate                        /* True for xCreate, false for xConnect */
132312 ){
132313   int rc = SQLCIPHER_OK;
132314   Rtree *pRtree;
132315   int nDb;              /* Length of string argv[1] */
132316   int nName;            /* Length of string argv[2] */
132317   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
132318
132319   const char *aErrMsg[] = {
132320     0,                                                    /* 0 */
132321     "Wrong number of columns for an rtree table",         /* 1 */
132322     "Too few columns for an rtree table",                 /* 2 */
132323     "Too many columns for an rtree table"                 /* 3 */
132324   };
132325
132326   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
132327   if( aErrMsg[iErr] ){
132328     *pzErr = sqlcipher3_mprintf("%s", aErrMsg[iErr]);
132329     return SQLCIPHER_ERROR;
132330   }
132331
132332   sqlcipher3_vtab_config(db, SQLCIPHER_VTAB_CONSTRAINT_SUPPORT, 1);
132333
132334   /* Allocate the sqlcipher3_vtab structure */
132335   nDb = strlen(argv[1]);
132336   nName = strlen(argv[2]);
132337   pRtree = (Rtree *)sqlcipher3_malloc(sizeof(Rtree)+nDb+nName+2);
132338   if( !pRtree ){
132339     return SQLCIPHER_NOMEM;
132340   }
132341   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
132342   pRtree->nBusy = 1;
132343   pRtree->base.pModule = &rtreeModule;
132344   pRtree->zDb = (char *)&pRtree[1];
132345   pRtree->zName = &pRtree->zDb[nDb+1];
132346   pRtree->nDim = (argc-4)/2;
132347   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
132348   pRtree->eCoordType = eCoordType;
132349   memcpy(pRtree->zDb, argv[1], nDb);
132350   memcpy(pRtree->zName, argv[2], nName);
132351
132352   /* Figure out the node size to use. */
132353   rc = getNodeSize(db, pRtree, isCreate);
132354
132355   /* Create/Connect to the underlying relational database schema. If
132356   ** that is successful, call sqlcipher3_declare_vtab() to configure
132357   ** the r-tree table schema.
132358   */
132359   if( rc==SQLCIPHER_OK ){
132360     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
132361       *pzErr = sqlcipher3_mprintf("%s", sqlcipher3_errmsg(db));
132362     }else{
132363       char *zSql = sqlcipher3_mprintf("CREATE TABLE x(%s", argv[3]);
132364       char *zTmp;
132365       int ii;
132366       for(ii=4; zSql && ii<argc; ii++){
132367         zTmp = zSql;
132368         zSql = sqlcipher3_mprintf("%s, %s", zTmp, argv[ii]);
132369         sqlcipher3_free(zTmp);
132370       }
132371       if( zSql ){
132372         zTmp = zSql;
132373         zSql = sqlcipher3_mprintf("%s);", zTmp);
132374         sqlcipher3_free(zTmp);
132375       }
132376       if( !zSql ){
132377         rc = SQLCIPHER_NOMEM;
132378       }else if( SQLCIPHER_OK!=(rc = sqlcipher3_declare_vtab(db, zSql)) ){
132379         *pzErr = sqlcipher3_mprintf("%s", sqlcipher3_errmsg(db));
132380       }
132381       sqlcipher3_free(zSql);
132382     }
132383   }
132384
132385   if( rc==SQLCIPHER_OK ){
132386     *ppVtab = (sqlcipher3_vtab *)pRtree;
132387   }else{
132388     rtreeRelease(pRtree);
132389   }
132390   return rc;
132391 }
132392
132393
132394 /*
132395 ** Implementation of a scalar function that decodes r-tree nodes to
132396 ** human readable strings. This can be used for debugging and analysis.
132397 **
132398 ** The scalar function takes two arguments, a blob of data containing
132399 ** an r-tree node, and the number of dimensions the r-tree indexes.
132400 ** For a two-dimensional r-tree structure called "rt", to deserialize
132401 ** all nodes, a statement like:
132402 **
132403 **   SELECT rtreenode(2, data) FROM rt_node;
132404 **
132405 ** The human readable string takes the form of a Tcl list with one
132406 ** entry for each cell in the r-tree node. Each entry is itself a
132407 ** list, containing the 8-byte rowid/pageno followed by the 
132408 ** <num-dimension>*2 coordinates.
132409 */
132410 static void rtreenode(sqlcipher3_context *ctx, int nArg, sqlcipher3_value **apArg){
132411   char *zText = 0;
132412   RtreeNode node;
132413   Rtree tree;
132414   int ii;
132415
132416   UNUSED_PARAMETER(nArg);
132417   memset(&node, 0, sizeof(RtreeNode));
132418   memset(&tree, 0, sizeof(Rtree));
132419   tree.nDim = sqlcipher3_value_int(apArg[0]);
132420   tree.nBytesPerCell = 8 + 8 * tree.nDim;
132421   node.zData = (u8 *)sqlcipher3_value_blob(apArg[1]);
132422
132423   for(ii=0; ii<NCELL(&node); ii++){
132424     char zCell[512];
132425     int nCell = 0;
132426     RtreeCell cell;
132427     int jj;
132428
132429     nodeGetCell(&tree, &node, ii, &cell);
132430     sqlcipher3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
132431     nCell = strlen(zCell);
132432     for(jj=0; jj<tree.nDim*2; jj++){
132433       sqlcipher3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
132434       nCell = strlen(zCell);
132435     }
132436
132437     if( zText ){
132438       char *zTextNew = sqlcipher3_mprintf("%s {%s}", zText, zCell);
132439       sqlcipher3_free(zText);
132440       zText = zTextNew;
132441     }else{
132442       zText = sqlcipher3_mprintf("{%s}", zCell);
132443     }
132444   }
132445   
132446   sqlcipher3_result_text(ctx, zText, -1, sqlcipher3_free);
132447 }
132448
132449 static void rtreedepth(sqlcipher3_context *ctx, int nArg, sqlcipher3_value **apArg){
132450   UNUSED_PARAMETER(nArg);
132451   if( sqlcipher3_value_type(apArg[0])!=SQLCIPHER_BLOB 
132452    || sqlcipher3_value_bytes(apArg[0])<2
132453   ){
132454     sqlcipher3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
132455   }else{
132456     u8 *zBlob = (u8 *)sqlcipher3_value_blob(apArg[0]);
132457     sqlcipher3_result_int(ctx, readInt16(zBlob));
132458   }
132459 }
132460
132461 /*
132462 ** Register the r-tree module with database handle db. This creates the
132463 ** virtual table module "rtree" and the debugging/analysis scalar 
132464 ** function "rtreenode".
132465 */
132466 SQLCIPHER_PRIVATE int sqlcipher3RtreeInit(sqlcipher3 *db){
132467   const int utf8 = SQLCIPHER_UTF8;
132468   int rc;
132469
132470   rc = sqlcipher3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
132471   if( rc==SQLCIPHER_OK ){
132472     rc = sqlcipher3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
132473   }
132474   if( rc==SQLCIPHER_OK ){
132475     void *c = (void *)RTREE_COORD_REAL32;
132476     rc = sqlcipher3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
132477   }
132478   if( rc==SQLCIPHER_OK ){
132479     void *c = (void *)RTREE_COORD_INT32;
132480     rc = sqlcipher3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
132481   }
132482
132483   return rc;
132484 }
132485
132486 /*
132487 ** A version of sqlcipher3_free() that can be used as a callback. This is used
132488 ** in two places - as the destructor for the blob value returned by the
132489 ** invocation of a geometry function, and as the destructor for the geometry
132490 ** functions themselves.
132491 */
132492 static void doSqlite3Free(void *p){
132493   sqlcipher3_free(p);
132494 }
132495
132496 /*
132497 ** Each call to sqlcipher3_rtree_geometry_callback() creates an ordinary SQLite
132498 ** scalar user function. This C function is the callback used for all such
132499 ** registered SQL functions.
132500 **
132501 ** The scalar user functions return a blob that is interpreted by r-tree
132502 ** table MATCH operators.
132503 */
132504 static void geomCallback(sqlcipher3_context *ctx, int nArg, sqlcipher3_value **aArg){
132505   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlcipher3_user_data(ctx);
132506   RtreeMatchArg *pBlob;
132507   int nBlob;
132508
132509   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
132510   pBlob = (RtreeMatchArg *)sqlcipher3_malloc(nBlob);
132511   if( !pBlob ){
132512     sqlcipher3_result_error_nomem(ctx);
132513   }else{
132514     int i;
132515     pBlob->magic = RTREE_GEOMETRY_MAGIC;
132516     pBlob->xGeom = pGeomCtx->xGeom;
132517     pBlob->pContext = pGeomCtx->pContext;
132518     pBlob->nParam = nArg;
132519     for(i=0; i<nArg; i++){
132520       pBlob->aParam[i] = sqlcipher3_value_double(aArg[i]);
132521     }
132522     sqlcipher3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
132523   }
132524 }
132525
132526 /*
132527 ** Register a new geometry function for use with the r-tree MATCH operator.
132528 */
132529 SQLCIPHER_API int sqlcipher3_rtree_geometry_callback(
132530   sqlcipher3 *db,
132531   const char *zGeom,
132532   int (*xGeom)(sqlcipher3_rtree_geometry *, int, double *, int *),
132533   void *pContext
132534 ){
132535   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
132536
132537   /* Allocate and populate the context object. */
132538   pGeomCtx = (RtreeGeomCallback *)sqlcipher3_malloc(sizeof(RtreeGeomCallback));
132539   if( !pGeomCtx ) return SQLCIPHER_NOMEM;
132540   pGeomCtx->xGeom = xGeom;
132541   pGeomCtx->pContext = pContext;
132542
132543   /* Create the new user-function. Register a destructor function to delete
132544   ** the context object when it is no longer required.  */
132545   return sqlcipher3_create_function_v2(db, zGeom, -1, SQLCIPHER_ANY, 
132546       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
132547   );
132548 }
132549
132550 #if !SQLCIPHER_CORE
132551 SQLCIPHER_API int sqlcipher3_extension_init(
132552   sqlcipher3 *db,
132553   char **pzErrMsg,
132554   const sqlcipher3_api_routines *pApi
132555 ){
132556   SQLCIPHER_EXTENSION_INIT2(pApi)
132557   return sqlcipher3RtreeInit(db);
132558 }
132559 #endif
132560
132561 #endif
132562
132563 /************** End of rtree.c ***********************************************/
132564 /************** Begin file icu.c *********************************************/
132565 /*
132566 ** 2007 May 6
132567 **
132568 ** The author disclaims copyright to this source code.  In place of
132569 ** a legal notice, here is a blessing:
132570 **
132571 **    May you do good and not evil.
132572 **    May you find forgiveness for yourself and forgive others.
132573 **    May you share freely, never taking more than you give.
132574 **
132575 *************************************************************************
132576 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
132577 **
132578 ** This file implements an integration between the ICU library 
132579 ** ("International Components for Unicode", an open-source library 
132580 ** for handling unicode data) and SQLite. The integration uses 
132581 ** ICU to provide the following to SQLite:
132582 **
132583 **   * An implementation of the SQL regexp() function (and hence REGEXP
132584 **     operator) using the ICU uregex_XX() APIs.
132585 **
132586 **   * Implementations of the SQL scalar upper() and lower() functions
132587 **     for case mapping.
132588 **
132589 **   * Integration of ICU and SQLite collation seqences.
132590 **
132591 **   * An implementation of the LIKE operator that uses ICU to 
132592 **     provide case-independent matching.
132593 */
132594
132595 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_ICU)
132596
132597 /* Include ICU headers */
132598 #include <unicode/utypes.h>
132599 #include <unicode/uregex.h>
132600 #include <unicode/ustring.h>
132601 #include <unicode/ucol.h>
132602
132603 /* #include <assert.h> */
132604
132605 #ifndef SQLCIPHER_CORE
132606   SQLCIPHER_EXTENSION_INIT1
132607 #else
132608 #endif
132609
132610 /*
132611 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
132612 ** operator.
132613 */
132614 #ifndef SQLCIPHER_MAX_LIKE_PATTERN_LENGTH
132615 # define SQLCIPHER_MAX_LIKE_PATTERN_LENGTH 50000
132616 #endif
132617
132618 /*
132619 ** Version of sqlcipher3_free() that is always a function, never a macro.
132620 */
132621 static void xFree(void *p){
132622   sqlcipher3_free(p);
132623 }
132624
132625 /*
132626 ** Compare two UTF-8 strings for equality where the first string is
132627 ** a "LIKE" expression. Return true (1) if they are the same and 
132628 ** false (0) if they are different.
132629 */
132630 static int icuLikeCompare(
132631   const uint8_t *zPattern,   /* LIKE pattern */
132632   const uint8_t *zString,    /* The UTF-8 string to compare against */
132633   const UChar32 uEsc         /* The escape character */
132634 ){
132635   static const int MATCH_ONE = (UChar32)'_';
132636   static const int MATCH_ALL = (UChar32)'%';
132637
132638   int iPattern = 0;       /* Current byte index in zPattern */
132639   int iString = 0;        /* Current byte index in zString */
132640
132641   int prevEscape = 0;     /* True if the previous character was uEsc */
132642
132643   while( zPattern[iPattern]!=0 ){
132644
132645     /* Read (and consume) the next character from the input pattern. */
132646     UChar32 uPattern;
132647     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
132648     assert(uPattern!=0);
132649
132650     /* There are now 4 possibilities:
132651     **
132652     **     1. uPattern is an unescaped match-all character "%",
132653     **     2. uPattern is an unescaped match-one character "_",
132654     **     3. uPattern is an unescaped escape character, or
132655     **     4. uPattern is to be handled as an ordinary character
132656     */
132657     if( !prevEscape && uPattern==MATCH_ALL ){
132658       /* Case 1. */
132659       uint8_t c;
132660
132661       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
132662       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
132663       ** test string.
132664       */
132665       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
132666         if( c==MATCH_ONE ){
132667           if( zString[iString]==0 ) return 0;
132668           U8_FWD_1_UNSAFE(zString, iString);
132669         }
132670         iPattern++;
132671       }
132672
132673       if( zPattern[iPattern]==0 ) return 1;
132674
132675       while( zString[iString] ){
132676         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
132677           return 1;
132678         }
132679         U8_FWD_1_UNSAFE(zString, iString);
132680       }
132681       return 0;
132682
132683     }else if( !prevEscape && uPattern==MATCH_ONE ){
132684       /* Case 2. */
132685       if( zString[iString]==0 ) return 0;
132686       U8_FWD_1_UNSAFE(zString, iString);
132687
132688     }else if( !prevEscape && uPattern==uEsc){
132689       /* Case 3. */
132690       prevEscape = 1;
132691
132692     }else{
132693       /* Case 4. */
132694       UChar32 uString;
132695       U8_NEXT_UNSAFE(zString, iString, uString);
132696       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
132697       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
132698       if( uString!=uPattern ){
132699         return 0;
132700       }
132701       prevEscape = 0;
132702     }
132703   }
132704
132705   return zString[iString]==0;
132706 }
132707
132708 /*
132709 ** Implementation of the like() SQL function.  This function implements
132710 ** the build-in LIKE operator.  The first argument to the function is the
132711 ** pattern and the second argument is the string.  So, the SQL statements:
132712 **
132713 **       A LIKE B
132714 **
132715 ** is implemented as like(B, A). If there is an escape character E, 
132716 **
132717 **       A LIKE B ESCAPE E
132718 **
132719 ** is mapped to like(B, A, E).
132720 */
132721 static void icuLikeFunc(
132722   sqlcipher3_context *context, 
132723   int argc, 
132724   sqlcipher3_value **argv
132725 ){
132726   const unsigned char *zA = sqlcipher3_value_text(argv[0]);
132727   const unsigned char *zB = sqlcipher3_value_text(argv[1]);
132728   UChar32 uEsc = 0;
132729
132730   /* Limit the length of the LIKE or GLOB pattern to avoid problems
132731   ** of deep recursion and N*N behavior in patternCompare().
132732   */
132733   if( sqlcipher3_value_bytes(argv[0])>SQLCIPHER_MAX_LIKE_PATTERN_LENGTH ){
132734     sqlcipher3_result_error(context, "LIKE or GLOB pattern too complex", -1);
132735     return;
132736   }
132737
132738
132739   if( argc==3 ){
132740     /* The escape character string must consist of a single UTF-8 character.
132741     ** Otherwise, return an error.
132742     */
132743     int nE= sqlcipher3_value_bytes(argv[2]);
132744     const unsigned char *zE = sqlcipher3_value_text(argv[2]);
132745     int i = 0;
132746     if( zE==0 ) return;
132747     U8_NEXT(zE, i, nE, uEsc);
132748     if( i!=nE){
132749       sqlcipher3_result_error(context, 
132750           "ESCAPE expression must be a single character", -1);
132751       return;
132752     }
132753   }
132754
132755   if( zA && zB ){
132756     sqlcipher3_result_int(context, icuLikeCompare(zA, zB, uEsc));
132757   }
132758 }
132759
132760 /*
132761 ** This function is called when an ICU function called from within
132762 ** the implementation of an SQL scalar function returns an error.
132763 **
132764 ** The scalar function context passed as the first argument is 
132765 ** loaded with an error message based on the following two args.
132766 */
132767 static void icuFunctionError(
132768   sqlcipher3_context *pCtx,       /* SQLite scalar function context */
132769   const char *zName,           /* Name of ICU function that failed */
132770   UErrorCode e                 /* Error code returned by ICU function */
132771 ){
132772   char zBuf[128];
132773   sqlcipher3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
132774   zBuf[127] = '\0';
132775   sqlcipher3_result_error(pCtx, zBuf, -1);
132776 }
132777
132778 /*
132779 ** Function to delete compiled regexp objects. Registered as
132780 ** a destructor function with sqlcipher3_set_auxdata().
132781 */
132782 static void icuRegexpDelete(void *p){
132783   URegularExpression *pExpr = (URegularExpression *)p;
132784   uregex_close(pExpr);
132785 }
132786
132787 /*
132788 ** Implementation of SQLite REGEXP operator. This scalar function takes
132789 ** two arguments. The first is a regular expression pattern to compile
132790 ** the second is a string to match against that pattern. If either 
132791 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
132792 ** is 1 if the string matches the pattern, or 0 otherwise.
132793 **
132794 ** SQLite maps the regexp() function to the regexp() operator such
132795 ** that the following two are equivalent:
132796 **
132797 **     zString REGEXP zPattern
132798 **     regexp(zPattern, zString)
132799 **
132800 ** Uses the following ICU regexp APIs:
132801 **
132802 **     uregex_open()
132803 **     uregex_matches()
132804 **     uregex_close()
132805 */
132806 static void icuRegexpFunc(sqlcipher3_context *p, int nArg, sqlcipher3_value **apArg){
132807   UErrorCode status = U_ZERO_ERROR;
132808   URegularExpression *pExpr;
132809   UBool res;
132810   const UChar *zString = sqlcipher3_value_text16(apArg[1]);
132811
132812   (void)nArg;  /* Unused parameter */
132813
132814   /* If the left hand side of the regexp operator is NULL, 
132815   ** then the result is also NULL. 
132816   */
132817   if( !zString ){
132818     return;
132819   }
132820
132821   pExpr = sqlcipher3_get_auxdata(p, 0);
132822   if( !pExpr ){
132823     const UChar *zPattern = sqlcipher3_value_text16(apArg[0]);
132824     if( !zPattern ){
132825       return;
132826     }
132827     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
132828
132829     if( U_SUCCESS(status) ){
132830       sqlcipher3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
132831     }else{
132832       assert(!pExpr);
132833       icuFunctionError(p, "uregex_open", status);
132834       return;
132835     }
132836   }
132837
132838   /* Configure the text that the regular expression operates on. */
132839   uregex_setText(pExpr, zString, -1, &status);
132840   if( !U_SUCCESS(status) ){
132841     icuFunctionError(p, "uregex_setText", status);
132842     return;
132843   }
132844
132845   /* Attempt the match */
132846   res = uregex_matches(pExpr, 0, &status);
132847   if( !U_SUCCESS(status) ){
132848     icuFunctionError(p, "uregex_matches", status);
132849     return;
132850   }
132851
132852   /* Set the text that the regular expression operates on to a NULL
132853   ** pointer. This is not really necessary, but it is tidier than 
132854   ** leaving the regular expression object configured with an invalid
132855   ** pointer after this function returns.
132856   */
132857   uregex_setText(pExpr, 0, 0, &status);
132858
132859   /* Return 1 or 0. */
132860   sqlcipher3_result_int(p, res ? 1 : 0);
132861 }
132862
132863 /*
132864 ** Implementations of scalar functions for case mapping - upper() and 
132865 ** lower(). Function upper() converts its input to upper-case (ABC).
132866 ** Function lower() converts to lower-case (abc).
132867 **
132868 ** ICU provides two types of case mapping, "general" case mapping and
132869 ** "language specific". Refer to ICU documentation for the differences
132870 ** between the two.
132871 **
132872 ** To utilise "general" case mapping, the upper() or lower() scalar 
132873 ** functions are invoked with one argument:
132874 **
132875 **     upper('ABC') -> 'abc'
132876 **     lower('abc') -> 'ABC'
132877 **
132878 ** To access ICU "language specific" case mapping, upper() or lower()
132879 ** should be invoked with two arguments. The second argument is the name
132880 ** of the locale to use. Passing an empty string ("") or SQL NULL value
132881 ** as the second argument is the same as invoking the 1 argument version
132882 ** of upper() or lower().
132883 **
132884 **     lower('I', 'en_us') -> 'i'
132885 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
132886 **
132887 ** http://www.icu-project.org/userguide/posix.html#case_mappings
132888 */
132889 static void icuCaseFunc16(sqlcipher3_context *p, int nArg, sqlcipher3_value **apArg){
132890   const UChar *zInput;
132891   UChar *zOutput;
132892   int nInput;
132893   int nOutput;
132894
132895   UErrorCode status = U_ZERO_ERROR;
132896   const char *zLocale = 0;
132897
132898   assert(nArg==1 || nArg==2);
132899   if( nArg==2 ){
132900     zLocale = (const char *)sqlcipher3_value_text(apArg[1]);
132901   }
132902
132903   zInput = sqlcipher3_value_text16(apArg[0]);
132904   if( !zInput ){
132905     return;
132906   }
132907   nInput = sqlcipher3_value_bytes16(apArg[0]);
132908
132909   nOutput = nInput * 2 + 2;
132910   zOutput = sqlcipher3_malloc(nOutput);
132911   if( !zOutput ){
132912     return;
132913   }
132914
132915   if( sqlcipher3_user_data(p) ){
132916     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
132917   }else{
132918     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
132919   }
132920
132921   if( !U_SUCCESS(status) ){
132922     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
132923     return;
132924   }
132925
132926   sqlcipher3_result_text16(p, zOutput, -1, xFree);
132927 }
132928
132929 /*
132930 ** Collation sequence destructor function. The pCtx argument points to
132931 ** a UCollator structure previously allocated using ucol_open().
132932 */
132933 static void icuCollationDel(void *pCtx){
132934   UCollator *p = (UCollator *)pCtx;
132935   ucol_close(p);
132936 }
132937
132938 /*
132939 ** Collation sequence comparison function. The pCtx argument points to
132940 ** a UCollator structure previously allocated using ucol_open().
132941 */
132942 static int icuCollationColl(
132943   void *pCtx,
132944   int nLeft,
132945   const void *zLeft,
132946   int nRight,
132947   const void *zRight
132948 ){
132949   UCollationResult res;
132950   UCollator *p = (UCollator *)pCtx;
132951   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
132952   switch( res ){
132953     case UCOL_LESS:    return -1;
132954     case UCOL_GREATER: return +1;
132955     case UCOL_EQUAL:   return 0;
132956   }
132957   assert(!"Unexpected return value from ucol_strcoll()");
132958   return 0;
132959 }
132960
132961 /*
132962 ** Implementation of the scalar function icu_load_collation().
132963 **
132964 ** This scalar function is used to add ICU collation based collation 
132965 ** types to an SQLite database connection. It is intended to be called
132966 ** as follows:
132967 **
132968 **     SELECT icu_load_collation(<locale>, <collation-name>);
132969 **
132970 ** Where <locale> is a string containing an ICU locale identifier (i.e.
132971 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
132972 ** collation sequence to create.
132973 */
132974 static void icuLoadCollation(
132975   sqlcipher3_context *p, 
132976   int nArg, 
132977   sqlcipher3_value **apArg
132978 ){
132979   sqlcipher3 *db = (sqlcipher3 *)sqlcipher3_user_data(p);
132980   UErrorCode status = U_ZERO_ERROR;
132981   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
132982   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
132983   UCollator *pUCollator;    /* ICU library collation object */
132984   int rc;                   /* Return code from sqlcipher3_create_collation_x() */
132985
132986   assert(nArg==2);
132987   zLocale = (const char *)sqlcipher3_value_text(apArg[0]);
132988   zName = (const char *)sqlcipher3_value_text(apArg[1]);
132989
132990   if( !zLocale || !zName ){
132991     return;
132992   }
132993
132994   pUCollator = ucol_open(zLocale, &status);
132995   if( !U_SUCCESS(status) ){
132996     icuFunctionError(p, "ucol_open", status);
132997     return;
132998   }
132999   assert(p);
133000
133001   rc = sqlcipher3_create_collation_v2(db, zName, SQLCIPHER_UTF16, (void *)pUCollator, 
133002       icuCollationColl, icuCollationDel
133003   );
133004   if( rc!=SQLCIPHER_OK ){
133005     ucol_close(pUCollator);
133006     sqlcipher3_result_error(p, "Error registering collation function", -1);
133007   }
133008 }
133009
133010 /*
133011 ** Register the ICU extension functions with database db.
133012 */
133013 SQLCIPHER_PRIVATE int sqlcipher3IcuInit(sqlcipher3 *db){
133014   struct IcuScalar {
133015     const char *zName;                        /* Function name */
133016     int nArg;                                 /* Number of arguments */
133017     int enc;                                  /* Optimal text encoding */
133018     void *pContext;                           /* sqlcipher3_user_data() context */
133019     void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**);
133020   } scalars[] = {
133021     {"regexp", 2, SQLCIPHER_ANY,          0, icuRegexpFunc},
133022
133023     {"lower",  1, SQLCIPHER_UTF16,        0, icuCaseFunc16},
133024     {"lower",  2, SQLCIPHER_UTF16,        0, icuCaseFunc16},
133025     {"upper",  1, SQLCIPHER_UTF16, (void*)1, icuCaseFunc16},
133026     {"upper",  2, SQLCIPHER_UTF16, (void*)1, icuCaseFunc16},
133027
133028     {"lower",  1, SQLCIPHER_UTF8,         0, icuCaseFunc16},
133029     {"lower",  2, SQLCIPHER_UTF8,         0, icuCaseFunc16},
133030     {"upper",  1, SQLCIPHER_UTF8,  (void*)1, icuCaseFunc16},
133031     {"upper",  2, SQLCIPHER_UTF8,  (void*)1, icuCaseFunc16},
133032
133033     {"like",   2, SQLCIPHER_UTF8,         0, icuLikeFunc},
133034     {"like",   3, SQLCIPHER_UTF8,         0, icuLikeFunc},
133035
133036     {"icu_load_collation",  2, SQLCIPHER_UTF8, (void*)db, icuLoadCollation},
133037   };
133038
133039   int rc = SQLCIPHER_OK;
133040   int i;
133041
133042   for(i=0; rc==SQLCIPHER_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
133043     struct IcuScalar *p = &scalars[i];
133044     rc = sqlcipher3_create_function(
133045         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
133046     );
133047   }
133048
133049   return rc;
133050 }
133051
133052 #if !SQLCIPHER_CORE
133053 SQLCIPHER_API int sqlcipher3_extension_init(
133054   sqlcipher3 *db, 
133055   char **pzErrMsg,
133056   const sqlcipher3_api_routines *pApi
133057 ){
133058   SQLCIPHER_EXTENSION_INIT2(pApi)
133059   return sqlcipher3IcuInit(db);
133060 }
133061 #endif
133062
133063 #endif
133064
133065 /************** End of icu.c *************************************************/
133066 /************** Begin file fts3_icu.c ****************************************/
133067 /*
133068 ** 2007 June 22
133069 **
133070 ** The author disclaims copyright to this source code.  In place of
133071 ** a legal notice, here is a blessing:
133072 **
133073 **    May you do good and not evil.
133074 **    May you find forgiveness for yourself and forgive others.
133075 **    May you share freely, never taking more than you give.
133076 **
133077 *************************************************************************
133078 ** This file implements a tokenizer for fts3 based on the ICU library.
133079 */
133080 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
133081 #ifdef SQLCIPHER_ENABLE_ICU
133082
133083 /* #include <assert.h> */
133084 /* #include <string.h> */
133085
133086 #include <unicode/ubrk.h>
133087 /* #include <unicode/ucol.h> */
133088 /* #include <unicode/ustring.h> */
133089 #include <unicode/utf16.h>
133090
133091 typedef struct IcuTokenizer IcuTokenizer;
133092 typedef struct IcuCursor IcuCursor;
133093
133094 struct IcuTokenizer {
133095   sqlcipher3_tokenizer base;
133096   char *zLocale;
133097 };
133098
133099 struct IcuCursor {
133100   sqlcipher3_tokenizer_cursor base;
133101
133102   UBreakIterator *pIter;      /* ICU break-iterator object */
133103   int nChar;                  /* Number of UChar elements in pInput */
133104   UChar *aChar;               /* Copy of input using utf-16 encoding */
133105   int *aOffset;               /* Offsets of each character in utf-8 input */
133106
133107   int nBuffer;
133108   char *zBuffer;
133109
133110   int iToken;
133111 };
133112
133113 /*
133114 ** Create a new tokenizer instance.
133115 */
133116 static int icuCreate(
133117   int argc,                            /* Number of entries in argv[] */
133118   const char * const *argv,            /* Tokenizer creation arguments */
133119   sqlcipher3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
133120 ){
133121   IcuTokenizer *p;
133122   int n = 0;
133123
133124   if( argc>0 ){
133125     n = strlen(argv[0])+1;
133126   }
133127   p = (IcuTokenizer *)sqlcipher3_malloc(sizeof(IcuTokenizer)+n);
133128   if( !p ){
133129     return SQLCIPHER_NOMEM;
133130   }
133131   memset(p, 0, sizeof(IcuTokenizer));
133132
133133   if( n ){
133134     p->zLocale = (char *)&p[1];
133135     memcpy(p->zLocale, argv[0], n);
133136   }
133137
133138   *ppTokenizer = (sqlcipher3_tokenizer *)p;
133139
133140   return SQLCIPHER_OK;
133141 }
133142
133143 /*
133144 ** Destroy a tokenizer
133145 */
133146 static int icuDestroy(sqlcipher3_tokenizer *pTokenizer){
133147   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
133148   sqlcipher3_free(p);
133149   return SQLCIPHER_OK;
133150 }
133151
133152 /*
133153 ** Prepare to begin tokenizing a particular string.  The input
133154 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
133155 ** used to incrementally tokenize this string is returned in 
133156 ** *ppCursor.
133157 */
133158 static int icuOpen(
133159   sqlcipher3_tokenizer *pTokenizer,         /* The tokenizer */
133160   const char *zInput,                    /* Input string */
133161   int nInput,                            /* Length of zInput in bytes */
133162   sqlcipher3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
133163 ){
133164   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
133165   IcuCursor *pCsr;
133166
133167   const int32_t opt = U_FOLD_CASE_DEFAULT;
133168   UErrorCode status = U_ZERO_ERROR;
133169   int nChar;
133170
133171   UChar32 c;
133172   int iInput = 0;
133173   int iOut = 0;
133174
133175   *ppCursor = 0;
133176
133177   if( nInput<0 ){
133178     nInput = strlen(zInput);
133179   }
133180   nChar = nInput+1;
133181   pCsr = (IcuCursor *)sqlcipher3_malloc(
133182       sizeof(IcuCursor) +                /* IcuCursor */
133183       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
133184       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
133185   );
133186   if( !pCsr ){
133187     return SQLCIPHER_NOMEM;
133188   }
133189   memset(pCsr, 0, sizeof(IcuCursor));
133190   pCsr->aChar = (UChar *)&pCsr[1];
133191   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
133192
133193   pCsr->aOffset[iOut] = iInput;
133194   U8_NEXT(zInput, iInput, nInput, c); 
133195   while( c>0 ){
133196     int isError = 0;
133197     c = u_foldCase(c, opt);
133198     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
133199     if( isError ){
133200       sqlcipher3_free(pCsr);
133201       return SQLCIPHER_ERROR;
133202     }
133203     pCsr->aOffset[iOut] = iInput;
133204
133205     if( iInput<nInput ){
133206       U8_NEXT(zInput, iInput, nInput, c);
133207     }else{
133208       c = 0;
133209     }
133210   }
133211
133212   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
133213   if( !U_SUCCESS(status) ){
133214     sqlcipher3_free(pCsr);
133215     return SQLCIPHER_ERROR;
133216   }
133217   pCsr->nChar = iOut;
133218
133219   ubrk_first(pCsr->pIter);
133220   *ppCursor = (sqlcipher3_tokenizer_cursor *)pCsr;
133221   return SQLCIPHER_OK;
133222 }
133223
133224 /*
133225 ** Close a tokenization cursor previously opened by a call to icuOpen().
133226 */
133227 static int icuClose(sqlcipher3_tokenizer_cursor *pCursor){
133228   IcuCursor *pCsr = (IcuCursor *)pCursor;
133229   ubrk_close(pCsr->pIter);
133230   sqlcipher3_free(pCsr->zBuffer);
133231   sqlcipher3_free(pCsr);
133232   return SQLCIPHER_OK;
133233 }
133234
133235 /*
133236 ** Extract the next token from a tokenization cursor.
133237 */
133238 static int icuNext(
133239   sqlcipher3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
133240   const char **ppToken,               /* OUT: *ppToken is the token text */
133241   int *pnBytes,                       /* OUT: Number of bytes in token */
133242   int *piStartOffset,                 /* OUT: Starting offset of token */
133243   int *piEndOffset,                   /* OUT: Ending offset of token */
133244   int *piPosition                     /* OUT: Position integer of token */
133245 ){
133246   IcuCursor *pCsr = (IcuCursor *)pCursor;
133247
133248   int iStart = 0;
133249   int iEnd = 0;
133250   int nByte = 0;
133251
133252   while( iStart==iEnd ){
133253     UChar32 c;
133254
133255     iStart = ubrk_current(pCsr->pIter);
133256     iEnd = ubrk_next(pCsr->pIter);
133257     if( iEnd==UBRK_DONE ){
133258       return SQLCIPHER_DONE;
133259     }
133260
133261     while( iStart<iEnd ){
133262       int iWhite = iStart;
133263       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
133264       if( u_isspace(c) ){
133265         iStart = iWhite;
133266       }else{
133267         break;
133268       }
133269     }
133270     assert(iStart<=iEnd);
133271   }
133272
133273   do {
133274     UErrorCode status = U_ZERO_ERROR;
133275     if( nByte ){
133276       char *zNew = sqlcipher3_realloc(pCsr->zBuffer, nByte);
133277       if( !zNew ){
133278         return SQLCIPHER_NOMEM;
133279       }
133280       pCsr->zBuffer = zNew;
133281       pCsr->nBuffer = nByte;
133282     }
133283
133284     u_strToUTF8(
133285         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
133286         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
133287         &status                                  /* Output success/failure */
133288     );
133289   } while( nByte>pCsr->nBuffer );
133290
133291   *ppToken = pCsr->zBuffer;
133292   *pnBytes = nByte;
133293   *piStartOffset = pCsr->aOffset[iStart];
133294   *piEndOffset = pCsr->aOffset[iEnd];
133295   *piPosition = pCsr->iToken++;
133296
133297   return SQLCIPHER_OK;
133298 }
133299
133300 /*
133301 ** The set of routines that implement the simple tokenizer
133302 */
133303 static const sqlcipher3_tokenizer_module icuTokenizerModule = {
133304   0,                           /* iVersion */
133305   icuCreate,                   /* xCreate  */
133306   icuDestroy,                  /* xCreate  */
133307   icuOpen,                     /* xOpen    */
133308   icuClose,                    /* xClose   */
133309   icuNext,                     /* xNext    */
133310 };
133311
133312 /*
133313 ** Set *ppModule to point at the implementation of the ICU tokenizer.
133314 */
133315 SQLCIPHER_PRIVATE void sqlcipher3Fts3IcuTokenizerModule(
133316   sqlcipher3_tokenizer_module const**ppModule
133317 ){
133318   *ppModule = &icuTokenizerModule;
133319 }
133320
133321 #endif /* defined(SQLCIPHER_ENABLE_ICU) */
133322 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
133323
133324 #pragma GCC diagnostic pop
133325 /************** End of fts3_icu.c ********************************************/